diff --git a/dogfooding/index.js b/dogfooding/index.js index e472c07..597fbb4 100644 --- a/dogfooding/index.js +++ b/dogfooding/index.js @@ -1,3 +1,3 @@ /*! For license information please see index.js.LICENSE.txt */ -(()=>{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,s=2,o=!0;s{"use strict";var r=t;r.length=function(e){var t=e.length;if(!t)return 0;for(var r=0;--t%4>1&&"="===e.charAt(t);)++r;return Math.ceil(3*e.length)/4-r};for(var n=new Array(64),s=new Array(123),o=0;o<64;)s[n[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;r.encode=function(e,t,r){for(var s,o=null,i=[],a=0,c=0;t>2],s=(3&l)<<4,c=1;break;case 1:i[a++]=n[s|l>>4],s=(15&l)<<2,c=2;break;case 2:i[a++]=n[s|l>>6],i[a++]=n[63&l],c=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,i)),a=0)}return c&&(i[a++]=n[s],i[a++]=61,1===c&&(i[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,i.slice(0,a))),o.join("")):String.fromCharCode.apply(String,i.slice(0,a))};var i="invalid encoding";r.decode=function(e,t,r){for(var n,o=r,a=0,c=0;c1)break;if(void 0===(l=s[l]))throw Error(i);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(i);return r-o},r.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},8561:e=>{"use strict";function t(e,r){"string"==typeof e&&(r=e,e=void 0);var n=[];function s(e){if("string"!=typeof e){var r=o();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var i=Object.keys(e),a=new Array(i.length+1),c=new Array(i.length),l=0;l{"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{"use strict";e.exports=o;var n=r(8045),s=r(4153)("fs");function o(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&s&&s.readFile?s.readFile(e,(function(n,s){return n&&"undefined"!=typeof XMLHttpRequest?o.xhr(e,t,r):n?r(n):r(null,t.binary?s:s.toString("utf8"))})):o.xhr(e,t,r):n(o,this,e,t)}o.xhr=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){if(4===n.readyState){if(0!==n.status&&200!==n.status)return r(Error("status "+n.status));if(t.binary){var e=n.response;if(!e){e=[];for(var s=0;s{"use strict";function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),r=new Uint8Array(t.buffer),n=128===r[3];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3]}function o(e,n,s){t[0]=e,n[s]=r[3],n[s+1]=r[2],n[s+2]=r[1],n[s+3]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?s:o,e.writeFloatBE=n?o:s,e.readFloatLE=n?i:a,e.readFloatBE=n?a:i}():function(){function t(e,t,r,n){var s=t<0?1:0;if(s&&(t=-t),0===t)e(1/t>0?0:2147483648,r,n);else if(isNaN(t))e(2143289344,r,n);else if(t>34028234663852886e22)e((s<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((s<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var o=Math.floor(Math.log(t)/Math.LN2);e((s<<31|o+127<<23|8388607&Math.round(t*Math.pow(2,-o)*8388608))>>>0,r,n)}}function i(e,t,r){var n=e(t,r),s=2*(n>>31)+1,o=n>>>23&255,i=8388607&n;return 255===o?i?NaN:s*(1/0):0===o?1401298464324817e-60*s*i:s*Math.pow(2,o-150)*(i+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=i.bind(null,s),e.readFloatBE=i.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function s(e,n,s){t[0]=e,n[s]=r[0],n[s+1]=r[1],n[s+2]=r[2],n[s+3]=r[3],n[s+4]=r[4],n[s+5]=r[5],n[s+6]=r[6],n[s+7]=r[7]}function o(e,n,s){t[0]=e,n[s]=r[7],n[s+1]=r[6],n[s+2]=r[5],n[s+3]=r[4],n[s+4]=r[3],n[s+5]=r[2],n[s+6]=r[1],n[s+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?s:o,e.writeDoubleBE=n?o:s,e.readDoubleLE=n?i:a,e.readDoubleBE=n?a:i}():function(){function t(e,t,r,n,s,o){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,s,o+t),e(1/n>0?0:2147483648,s,o+r);else if(isNaN(n))e(0,s,o+t),e(2146959360,s,o+r);else if(n>17976931348623157e292)e(0,s,o+t),e((i<<31|2146435072)>>>0,s,o+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,s,o+t),e((i<<31|a/4294967296)>>>0,s,o+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,s,o+t),e((i<<31|c+1023<<20|1048576*a&1048575)>>>0,s,o+r)}}}function i(e,t,r,n,s){var o=e(n,s+t),i=e(n,s+r),a=2*(i>>31)+1,c=i>>>20&2047,l=4294967296*(1048575&i)+o;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=i.bind(null,s,0,4),e.readDoubleBE=i.bind(null,o,4,0)}(),e}function r(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function n(e,t,r){t[r]=e>>>24,t[r+1]=e>>>16&255,t[r+2]=e>>>8&255,t[r+3]=255&e}function s(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function o(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},4153:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},9207:(e,t)=>{"use strict";var r=t,n=r.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},s=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),s="";r&&(s=t.shift()+"/");for(var o=0;o0&&".."!==t[o-1]?t.splice(--o,2):r?t.splice(o,1):++o:"."===t[o]?t.splice(o,1):++o;return s+t.join("/")};r.resolve=function(e,t,r){return r||(t=s(t)),n(t)?t:(r||(e=s(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?s(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,s=n>>>1,o=null,i=n;return function(r){if(r<1||r>s)return e(r);i+r>n&&(o=e(n),i=0);var a=t.call(o,i,i+=r);return 7&i&&(i=1+(7|i)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?o[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(n>>10),o[i++]=56320+(1023&n)):o[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,o)),i=0);return s?(i&&s.push(String.fromCharCode.apply(String,o.slice(0,i))),s.join("")):String.fromCharCode.apply(String,o.slice(0,i))},r.write=function(e,t,r){for(var n,s,o=r,i=0;i>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(s=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&s),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}},7833:(e,t,r)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,s,o,i=null;function a(...e){if(!a.enabled)return;const n=a,s=Number(new Date),o=s-(r||s);n.diff=o,n.prev=r,n.curr=s,r=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,s)=>{if("%%"===r)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];r=o.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function s(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(s),...t.skips.map(s).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"use strict";function t(e,t){for(const r in t)Object.defineProperty(e,r,{value:t[r],enumerable:!0,configurable:!0});return e}e.exports=function(e,r,n){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");n||(n={}),"object"==typeof r&&(n=r,r=""),r&&(n.code=r);try{return t(e,n)}catch(r){n.message=e.message,n.stack=e.stack;const s=function(){};return s.prototype=Object.create(Object.getPrototypeOf(e)),t(new s,n)}}},544:(e,t,r)=>{"use strict";const n=r(9939);t.PP=n.EventIterator,n.EventIterator},9939:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});class r{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;const t={value:e,done:!1};if(this.pullQueue.length){const e=this.pullQueue.shift();e&&e.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(const e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(const t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{const t=Promise.reject(e);t.catch((()=>{})),this.pushQueue.push(t)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{const t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class n{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){const s=new r;s.highWaterMark=t,s.lowWaterMark=n,s.removeCallback=e({push:e=>s.push(e),stop:()=>s.stop(),fail:e=>s.fail(e),on:(e,t)=>{s.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>s[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function s(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new s(n,o||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,s=[];if(0===this._eventsCount)return s;for(n in e=this._events)t.call(e,n)&&s.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},a.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,o=n.length,i=new Array(o);s{e.exports=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function s(s,o){r[s]=o,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(s(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:s(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var s=!t.HI_BASE32_NO_COMMON_JS&&e.exports,o=r.amdO,i="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,s,o,i,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|i<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],s=a[e.charAt(p++)],o=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|s>>>4),u[h++]=255&(s<<4|o>>>1),u[h++]=255&(o<<7|i<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",s=e.length,o=0,i=0;o191&&t<=223?(r=31&t,i=1):t<=239?(r=15&t,i=2):t<=247?(r=7&t,i=3):l(o,n);for(var a=0;a191)&&l(o,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(o,n),r>1114111&&l(o,n),r<=65535?n+=String.fromCharCode(r):(r-=65536,n+=String.fromCharCode(55296+(r>>10)),n+=String.fromCharCode(56320+(1023&r)))}return n}(u(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var r,n,s,o,i,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,y=f>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var m=f-y;return 2===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))):5===m?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],i=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))):7===m&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],s=a[e.charAt(g++)],o=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|s<<1|o>>>4))+String.fromCharCode(255&(o<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,s,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o];var h=c-u;return 1===h?(t=e[l],a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],s=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,s,o,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),s=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"="),a}(e):function(e){var t,r,n,s,o,a,l,u=!1,h="",d=0,p=0,f=e.length;if(""===e)return h;do{for(c[0]=c[5],c[1]=c[6],c[2]=c[7],l=p;d>6,c[l++]=128|63&a):a<55296||a>=57344?(c[l++]=224|a>>12,c[l++]=128|a>>6&63,c[l++]=128|63&a):(a=65536+((1023&a)<<10|1023&e.charCodeAt(++d)),c[l++]=240|a>>18,c[l++]=128|a>>12&63,c[l++]=128|a>>6&63,c[l++]=128|63&a);p=l-5,d===f&&++d,d>f&&l<6&&(u=!0),t=c[0],l>4?(r=c[1],n=c[2],s=c[3],o=c[4],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[31&(s<<3|o>>>5)]+i[31&o]):1===l?h+=i[t>>>3]+i[t<<2&31]+"======":2===l?(r=c[1],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):(r=c[1],n=c[2],s=c[3],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|s>>>7)]+i[s>>>2&31]+i[s<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,s?e.exports=d:(t.base32=d,o&&(void 0===(n=function(){return d}.call(d,r,d,e))||(e.exports=n)))}()},4866:e=>{e.exports=function(){return"undefined"!=typeof window&&"object"==typeof window.process&&"renderer"===window.process.type||!("undefined"==typeof process||"object"!=typeof process.versions||!process.versions.electron)||"object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0}},6368:e=>{"use strict";e.exports=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;const t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}},1176:(e,t,r)=>{var n;!function(){"use strict";var s="input is invalid type",o="object"==typeof window,i=o?window:{};i.JS_SHA3_NO_WINDOW&&(o=!1);var a=!o&&"object"==typeof self;!i.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?i=global:a&&(i=self);for(var c=!i.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!i.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],y=[128,256],m=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=i.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(s);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(s);return[e,!1]},S=function(e){return 0===E(e)[0].length},A=function(e){for(var t=[],r=0;r>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function $(e,t,r){F.call(this,e,t,r)}F.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,s=t[1],o=this.blocks,i=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(o[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[l]<=i){for(this.start=r-i,this.block=o[c],r=0;r>=8);r>0;)s.unshift(r),r=255&(e>>=8),++n;return t?s.push(n):s.unshift(n),this.update(s),s.length},F.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,s=e.length;if(r)for(var o=0;o=57344?n+=3:(i=65536+((1023&i)<<10|1023&e.charCodeAt(++o)),n+=4)}else n=s;return n+=this.encode(8*n),this.update(e),n},F.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];i%t==0&&(r=A(r),H(r),o=0)}return s&&(e=r[o],a+=h[e>>4&15]+h[15&e],s>1&&(a+=h[e>>12&15]+h[e>>8&15]),s>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},F.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,s=this.extraBytes,o=0,i=0,a=this.outputBits>>3;e=s?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);i>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=A(n),H(n))}return o&&(e=a<<2,t=n[i],c[e]=255&t,o>1&&(c[e+1]=t>>8&255),o>2&&(c[e+2]=t>>16&255)),c},$.prototype=new F,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),F.prototype.finalize.call(this)};var H=function(e){var t,r,n,s,o,i,a,c,l,u,h,d,p,g,y,m,b,w,v,E,S,A,_,k,I,R,T,C,N,x,P,O,L,D,B,U,M,F,$,H,q,V,j,K,z,G,W,Y,J,X,Q,Z,ee,te,re,ne,se,oe,ie,ae,ce,le,ue;for(n=0;n<48;n+=2)s=e[0]^e[10]^e[20]^e[30]^e[40],o=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(i<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|i>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=s^(c<<1|l>>>31),r=o^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=i^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=l^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(s<<1|o>>>31),r=h^(o<<1|s>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],y=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,C=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,V=e[40]<<18|e[41]>>>14,j=e[41]<<18|e[40]>>>14,D=e[2]<<1|e[3]>>>31,B=e[3]<<1|e[2]>>>31,m=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,Y=e[22]<<10|e[23]>>>22,J=e[23]<<10|e[22]>>>22,x=e[33]<<13|e[32]>>>19,P=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,M=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,X=e[34]<<15|e[35]>>>17,Q=e[35]<<15|e[34]>>>17,O=e[45]<<29|e[44]>>>3,L=e[44]<<29|e[45]>>>3,k=e[6]<<28|e[7]>>>4,I=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,se=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Z=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,K=e[8]<<27|e[9]>>>5,z=e[9]<<27|e[8]>>>5,R=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,oe=e[29]<<7|e[28]>>>25,ie=e[28]<<7|e[29]>>>25,H=e[38]<<8|e[39]>>>24,q=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,_=e[49]<<14|e[48]>>>18,e[0]=g^~m&w,e[1]=y^~b&v,e[10]=k^~R&C,e[11]=I^~T&N,e[20]=D^~U&F,e[21]=B^~M&$,e[30]=K^~G&Y,e[31]=z^~W&J,e[40]=te^~ne&oe,e[41]=re^~se&ie,e[2]=m^~w&E,e[3]=b^~v&S,e[12]=R^~C&x,e[13]=T^~N&P,e[22]=U^~F&H,e[23]=M^~$&q,e[32]=G^~Y&X,e[33]=W^~J&Q,e[42]=ne^~oe&ae,e[43]=se^~ie&ce,e[4]=w^~E&A,e[5]=v^~S&_,e[14]=C^~x&O,e[15]=N^~P&L,e[24]=F^~H&V,e[25]=$^~q&j,e[34]=Y^~X&Z,e[35]=J^~Q&ee,e[44]=oe^~ae&le,e[45]=ie^~ce&ue,e[6]=E^~A&g,e[7]=S^~_&y,e[16]=x^~O&k,e[17]=P^~L&I,e[26]=H^~V&D,e[27]=q^~j&B,e[36]=X^~Z&K,e[37]=Q^~ee&z,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&m,e[9]=_^~y&b,e[18]=O^~k&R,e[19]=L^~I&T,e[28]=V^~D&U,e[29]=j^~B&M,e[38]=Z^~K&G,e[39]=ee^~z&W,e[48]=le^~te&ne,e[49]=ue^~re&se,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=x;else{for(O=0;OObject.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),a=this,c={concatArrays:!1,ignoreUndefined:!1},l=e=>{const t=[];for(const r in e)s.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)o.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?i(e,r,p(e[r],t[r],n)):i(e,r,u(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),o=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!a.includes(e))),r)})),n};function p(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?d(e,t,r):n(t)&&n(e)?h(e,t,l(t),r):u(t)}e.exports=function(...e){const t=p(u(c),this!==a&&this||{},c);let r={_:{}};for(const s of e)if(void 0!==s){if(!n(s))throw new TypeError("`"+s+"` is not an Option Object");r=p(r,{_:s},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,s=24*n,o=7*s;function i(e,t,r,n){var s=t>=1.5*r;return Math.round(e/r)+" "+n+(s?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*o;case"days":case"day":case"d":return a*s;case"hours":case"hour":case"hrs":case"hr":case"h":return a*n;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}(e);if("number"===u&&isFinite(e))return a.long?(c=e,(l=Math.abs(c))>=s?i(c,l,s,"day"):l>=n?i(c,l,n,"hour"):l>=r?i(c,l,r,"minute"):l>=t?i(c,l,t,"second"):c+" ms"):function(e){var o=Math.abs(e);return o>=s?Math.round(e/s)+"d":o>=n?Math.round(e/n)+"h":o>=r?Math.round(e/r)+"m":o>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},8437:(e,t,r)=>{e.exports=r(4327)},4327:function(e,t){!function(r,n){"use strict";var s={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function o(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t255)return!1;return!0}function i(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<>>32-t}function c(e){return e=i(e^=e>>>16,2246822507),(e=i(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<>>32-t,e[1]<>>32-t]:(t-=32,[e[1]<>>32-t,e[0]<>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<>>32-t,e[1]<>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}s.x86.hash32=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%4,l=e.length-r,u=t,h=0,d=3432918353,p=461845907,f=0;f>>0},s.x86.hash128=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,l=e.length-r,u=t,h=t,d=t,p=t,f=0,g=0,y=0,m=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},s.x64.hash128=function(e,t){if(s.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,i=e.length-r,a=[0,t],c=[0,t],g=[0,0],y=[0,0],m=[2277735313,289559509],b=[1291169091,658871167],w=0;w>>0).toString(16)).slice(-8)+("00000000"+(a[1]>>>0).toString(16)).slice(-8)+("00000000"+(c[0]>>>0).toString(16)).slice(-8)+("00000000"+(c[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=s),t.murmurHash3=s}()},5507:function(e,t){(function(){var e,r,n,s,o,i,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,s,o,i,a;for(t=[],s=o=0;o<=3&&0!==e.length;s=++o){if(s>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}i=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(i)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},s=(n=function(e){return e.charCodeAt(0)})("0"),i=n("a"),o=n("A"),r=function(e){var t,r,a,c,l;for(c=0,t=10,r="9",a=0,e.length>1&&"0"===e[a]&&("x"===e[a+1]||"X"===e[a+1]?(a+=2,t=16):"0"<=e[a+1]&&e[a+1]<="9"&&(a++,t=8,r="7")),l=a;a>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-o)>>>0}}if(c>4294967295)throw new Error("too large");a++}if(a===l)throw new Error("empty octet");return[c,a]},e=function(){function e(e,t){var r,n,s;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(s=e.split("/",2),e=s[0],t=s[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},2549:(e,t,r)=>{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,s=r(5643),o=r(3262);function i(e,t,r,n){var o=!1;if(t.resolvedType)if(t.resolvedType instanceof s){e("switch(d%s){",n);for(var i=t.resolvedType.values,a=Object.keys(i),c=0;c>>0",n,n);break;case"int32":case"sint32":case"sfixed32":e("m%s=d%s|0",n,n);break;case"uint64":l=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",n,n,l)('else if(typeof d%s==="string")',n)("m%s=parseInt(d%s,10)",n,n)('else if(typeof d%s==="number")',n)("m%s=d%s",n,n)('else if(typeof d%s==="object")',n)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",n,n,n,l?"true":"");break;case"bytes":e('if(typeof d%s==="string")',n)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",n,n,n)("else if(d%s.length >= 0)",n)("m%s=d%s",n,n);break;case"string":e("m%s=String(d%s)",n,n);break;case"bool":e("m%s=Boolean(d%s)",n,n)}}return e}function a(e,t,r,n){if(t.resolvedType)t.resolvedType instanceof s?e("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",n,r,n,n,r,n,n):e("d%s=types[%i].toObject(m%s,o)",n,r,n);else{var o=!1;switch(t.type){case"double":case"float":e("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",n,n,n,n);break;case"uint64":o=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":e('if(typeof m%s==="number")',n)("d%s=o.longs===String?String(m%s):m%s",n,n,n)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",n,n,n,n,o?"true":"",n);break;case"bytes":e("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",n,n,n,n,n);break;default:e("d%s=m%s",n,n)}}return e}n.fromObject=function(e){var t=e.fieldsArray,r=o.codegen(["d"],e.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!t.length)return r("return new this.ctor");r("var m=new this.ctor");for(var n=0;n{"use strict";e.exports=function(e){var t=o.codegen(["r","l"],e.name+"$decode")("if(!(r instanceof Reader))")("r=Reader.create(r)")("var c=l===undefined?r.len:r.pos+l,m=new this.ctor"+(e.fieldsArray.filter((function(e){return e.map})).length?",k,value":""))("while(r.pos>>3){");for(var r=0;r>>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{"use strict";e.exports=function(e){for(var t,r=o.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(o.compareFieldsById),c=0;c>>0,8|s.mapKey[l.keyType],l.keyType),void 0===d?r("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,t):r(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|d,h,t),r("}")("}")):l.repeated?(r("if(%s!=null&&%s.length){",t,t),l.packed&&void 0!==s.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?i(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?i(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),s=r(361),o=r(3262);function i(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Enum";var s=r(8923),o=r(3262);function i(e,t,r,s,o,i){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=s,this.comments=o||{},this.valuesOptions=i,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var s,o=r(5643),i=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,s,o,l,u){if(a.isObject(s)?(u=o,l=s,s=o=void 0):a.isObject(o)&&(u=l,l=o,o=void 0),n.call(this,e,l),!a.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!a.isString(r))throw TypeError("type must be a string");if(void 0!==s&&!c.test(s=s.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==o&&!a.isString(o))throw TypeError("extend must be a string");"proto3_optional"===s&&(s="optional"),this.rule=s&&"optional"!==s?s:void 0,this.type=r,this.id=t,this.extend=o||void 0,this.required="required"===s,this.optional=!this.required,this.repeated="repeated"===s,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==i.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=i.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof s?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof o&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof o)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var e;a.base64.test(this.typeDefault)?a.base64.decode(this.typeDefault,e=a.newBuffer(a.base64.length(this.typeDefault)),0):a.utf8.write(this.typeDefault,e=a.newBuffer(a.utf8.length(this.typeDefault)),0),this.typeDefault=e}return this.map?this.defaultValue=a.emptyObject:this.repeated?this.defaultValue=a.emptyArray:this.defaultValue=this.typeDefault,this.parent instanceof s&&(this.parent.ctor.prototype[this.name]=this.defaultValue),n.prototype.resolve.call(this)},l.d=function(e,t,r,n){return"function"==typeof t?t=a.decorateType(t).name:t&&"object"==typeof t&&(t=a.decorateEnum(t).name),function(s,o){a.decorateType(s.constructor).add(new l(o,e,t,r,{default:n}))}},l._configure=function(e){s=e}},5325:(e,t,r)=>{"use strict";var n=e.exports=r(4394);n.build="light",n.load=function(e,t,r){return"function"==typeof t?(r=t,t=new n.Root):t||(t=new n.Root),t.load(e,r)},n.loadSync=function(e,t){return t||(t=new n.Root),t.loadSync(e)},n.encoder=r(1080),n.decoder=r(7728),n.verifier=r(420),n.converter=r(744),n.ReflectionObject=r(7209),n.Namespace=r(8923),n.Root=r(5330),n.Enum=r(5643),n.Type=r(7882),n.Field=r(1344),n.OneOf=r(1457),n.MapField=r(8252),n.Service=r(9687),n.Method=r(8811),n.Message=r(2551),n.wrappers=r(6434),n.types=r(361),n.util=r(3262),n.ReflectionObject._configure(n.Root),n.Namespace._configure(n.Type,n.Service,n.Enum),n.Root._configure(n.Type),n.Field._configure(n.Type)},4394:(e,t,r)=>{"use strict";var n=t;function s(){n.util._configure(),n.Writer._configure(n.BufferWriter),n.Reader._configure(n.BufferReader)}n.build="minimal",n.Writer=r(3449),n.BufferWriter=r(818),n.Reader=r(6237),n.BufferReader=r(3158),n.util=r(3610),n.rpc=r(5047),n.roots=r(4529),n.configure=s,s()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=i;var n=r(1344);((i.prototype=Object.create(n.prototype)).constructor=i).className="MapField";var s=r(361),o=r(3262);function i(e,t,r,s,i,a){if(n.call(this,e,t,s,void 0,void 0,i,a),!o.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}i.fromJSON=function(e,t){return new i(e,t.id,t.keyType,t.type,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},i.prototype.resolve=function(){if(this.resolved)return this;if(void 0===s.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},i.d=function(e,t,r){return"function"==typeof r?r=o.decorateType(r).name:r&&"object"==typeof r&&(r=o.decorateEnum(r).name),function(n,s){o.decorateType(n.constructor).add(new i(s,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=o;var n=r(7209);((o.prototype=Object.create(n.prototype)).constructor=o).className="Method";var s=r(3262);function o(e,t,r,o,i,a,c,l,u){if(s.isObject(i)?(c=i,i=a=void 0):s.isObject(a)&&(c=a,a=void 0),void 0!==t&&!s.isString(t))throw TypeError("type must be a string");if(!s.isString(r))throw TypeError("requestType must be a string");if(!s.isString(o))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!i||void 0,this.responseType=o,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}o.fromJSON=function(e,t){return new o(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},o.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["type","rpc"!==this.type&&this.type||void 0,"requestType",this.requestType,"requestStream",this.requestStream,"responseType",this.responseType,"responseStream",this.responseStream,"options",this.options,"comment",t?this.comment:void 0,"parsedOptions",this.parsedOptions])},o.prototype.resolve=function(){return this.resolved?this:(this.resolvedRequestType=this.parent.lookupType(this.requestType),this.resolvedResponseType=this.parent.lookupType(this.responseType),n.prototype.resolve.call(this))}},8923:(e,t,r)=>{"use strict";e.exports=h;var n=r(7209);((h.prototype=Object.create(n.prototype)).constructor=h).className="Namespace";var s,o,i,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){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-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var s=0;s{"use strict";e.exports=o,o.className="ReflectionObject";var n,s=r(3262);function o(e,t){if(!s.isString(e))throw TypeError("name must be a string");if(t&&!s.isObject(t))throw TypeError("options must be an object");this.options=t,this.parsedOptions=null,this.name=e,this.parent=null,this.resolved=!1,this.comment=null,this.filename=null}Object.defineProperties(o.prototype,{root:{get:function(){for(var e=this;null!==e.parent;)e=e.parent;return e}},fullName:{get:function(){for(var e=[this.name],t=this.parent;t;)e.unshift(t.name),t=t.parent;return e.join(".")}}}),o.prototype.toJSON=function(){throw Error()},o.prototype.onAdd=function(e){this.parent&&this.parent!==e&&this.parent.remove(this),this.parent=e,this.resolved=!1;var t=e.root;t instanceof n&&t._handleAdd(this)},o.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},o.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},o.prototype.getOption=function(e){if(this.options)return this.options[e]},o.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},o.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var o=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(o){var i=o[e];s.setProperty(i,r,t)}else(o={})[e]=s.setProperty({},r,t),n.push(o)}else{var a={};a[e]=t,n.push(a)}return this},o.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="OneOf";var s=r(1344),o=r(3262);function i(e,t,r,s){if(Array.isArray(t)||(r=t,t=void 0),n.call(this,e,r),void 0!==t&&!Array.isArray(t))throw TypeError("fieldNames must be an Array");this.oneof=t||[],this.fieldsArray=[],this.comment=s}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},i.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=_,_.filename=null,_.defaults={keepCase:!1};var n=r(527),s=r(5330),o=r(7882),i=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,y=/^0[x][0-9a-fA-F]+$/,m=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,A=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function _(e,t,r){t instanceof s||(r=t,t=new s),r||(r=_.defaults);var k,I,R,T,C,N=r.preferTrailingComment||!1,x=n(e,r.alternateCommentMode||!1),P=x.next,O=x.push,L=x.peek,D=x.skip,B=x.cmnt,U=!0,M=!1,F=t,$=r.keepCase?function(e){return e}:p.camelCase;function H(e,t,r){var n=_.filename;return r||(_.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+x.line+")")}function q(){var e,t=[];do{if('"'!==(e=P())&&"'"!==e)throw H(e);t.push(P()),D(e),e=L()}while('"'===e||"'"===e);return t.join("")}function V(e){var t=P();switch(t){case"'":case'"':return O(t),q();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e){var t=1;switch("-"===e.charAt(0)&&(t=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return t*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return t*parseInt(e,10);if(y.test(e))return t*parseInt(e,16);if(b.test(e))return t*parseInt(e,8);if(v.test(e))return t*parseFloat(e);throw H(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw H(t,"value")}}function j(e,t){var r,n;do{!t||'"'!==(r=L())&&"'"!==r?e.push([n=K(P()),D("to",!0)?K(P()):n]):e.push(q())}while(D(",",!0));var s={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};J(s,(function(e){if("option"!==e)throw H(e);ee(s,e),D(";")}),(function(){ne(s)}))}function K(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw H(e,"id");if(g.test(e))return parseInt(e,10);if(m.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw H(e,"id")}function z(){if(void 0!==k)throw H("package");if(k=P(),!S.test(k))throw H(k,"name");F=F.define(k),D(";")}function G(){var e,t=L();switch(t){case"weak":e=R||(R=[]),P();break;case"public":P();default:e=I||(I=[])}t=q(),D(";"),e.push(t)}function W(){if(D("="),T=q(),!(M="proto3"===T)&&"proto2"!==T)throw H(T,"syntax");t.setOption("syntax",T),D(";")}function Y(e,t){switch(t){case"option":return ee(e,t),D(";"),!0;case"message":return X(e,t),!0;case"enum":return Z(e,t),!0;case"service":return function(e,t){if(!E.test(t=P()))throw H(t,"service name");var r=new u(t);J(r,(function(e){if(!Y(r,e)){if("rpc"!==e)throw H(e);!function(e,t){var r=B(),n=t;if(!E.test(t=P()))throw H(t,"name");var s,o,i,a,c=t;if(D("("),D("stream",!0)&&(o=!0),!S.test(t=P()))throw H(t);if(s=t,D(")"),D("returns"),D("("),D("stream",!0)&&(a=!0),!S.test(t=P()))throw H(t);i=t,D(")");var l=new h(c,n,s,i,o,a);l.comment=r,J(l,(function(e){if("option"!==e)throw H(e);ee(l,e),D(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=P()))throw H(t,"reference");var r=t;J(null,(function(t){switch(t){case"required":case"repeated":Q(e,t,r);break;case"optional":Q(e,M?"proto3_optional":"optional",r);break;default:if(!M||!S.test(t))throw H(t);O(t),Q(e,"optional",r)}}))}(e,t),!0}return!1}function J(e,t,r){var n=x.line;if(e&&("string"!=typeof e.comment&&(e.comment=B()),e.filename=_.filename),D("{",!0)){for(var s;"}"!==(s=P());)t(s);D(";",!0)}else r&&r(),D(";"),e&&("string"!=typeof e.comment||N)&&(e.comment=B(n)||e.comment)}function X(e,t){if(!E.test(t=P()))throw H(t,"type name");var r=new o(t);J(r,(function(e){if(!Y(r,e))switch(e){case"map":!function(e){D("<");var t=P();if(void 0===d.mapKey[t])throw H(t,"type");D(",");var r=P();if(!S.test(r))throw H(r,"type");D(">");var n=P();if(!E.test(n))throw H(n,"name");D("=");var s=new a($(n),K(P()),t,r);J(s,(function(e){if("option"!==e)throw H(e);ee(s,e),D(";")}),(function(){ne(s)})),e.add(s)}(r);break;case"required":case"repeated":Q(r,e);break;case"optional":Q(r,M?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=P()))throw H(t,"name");var r=new c($(t));J(r,(function(e){"option"===e?(ee(r,e),D(";")):(O(e),Q(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":j(r.extensions||(r.extensions=[]));break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:if(!M||!S.test(e))throw H(e);O(e),Q(r,"optional")}})),e.add(r)}function Q(e,t,r){var n=P();if("group"!==n){for(;n.endsWith(".")||L().startsWith(".");)n+=P();if(!S.test(n))throw H(n,"type");var s=P();if(!E.test(s))throw H(s,"name");s=$(s),D("=");var a=new i(s,K(P()),n,t,r);if(J(a,(function(e){if("option"!==e)throw H(e);ee(a,e),D(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+s);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);M||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=P();if(!E.test(r))throw H(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),D("=");var s=K(P()),a=new o(r);a.group=!0;var c=new i(n,s,r,t);c.filename=_.filename,J(a,(function(e){switch(e){case"option":ee(a,e),D(";");break;case"required":case"repeated":Q(a,e);break;case"optional":Q(a,M?"proto3_optional":"optional");break;case"message":X(a,e);break;case"enum":Z(a,e);break;default:throw H(e)}})),e.add(a).add(c)}(e,t)}function Z(e,t){if(!E.test(t=P()))throw H(t,"name");var r=new l(t);J(r,(function(e){switch(e){case"option":ee(r,e),D(";");break;case"reserved":j(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw H(t,"name");D("=");var r=K(P(),!0),n={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};J(n,(function(e){if("option"!==e)throw H(e);ee(n,e),D(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=D("(",!0);if(!S.test(t=P()))throw H(t,"name");var n,s=t,o=s;r&&(D(")"),o=s="("+s+")",t=L(),A.test(t)&&(n=t.slice(1),s+=t,P())),D("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,o,te(e,s),n)}function te(e,t){if(D("{",!0)){for(var r={};!D("}",!0);){if(!E.test(C=P()))throw H(C,"name");if(null===C)throw H(C,"end of input");var n,s=C;if(D(":",!0),"{"===L())n=te(e,t+"."+C);else if("["===L()){var o;if(n=[],D("[",!0)){do{o=V(!0),n.push(o)}while(D(",",!0));D("]"),void 0!==o&&re(e,t+"."+C,o)}}else n=V(!0),re(e,t+"."+C,n);var i=r[s];i&&(n=[].concat(i).concat(n)),r[s]=n,D(",",!0),D(";",!0)}return r}var a=V(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(D("[",!0)){do{ee(e,"option")}while(D(",",!0));D("]")}return e}for(;null!==(C=P());)switch(C){case"package":if(!U)throw H(C);z();break;case"import":if(!U)throw H(C);G();break;case"syntax":if(!U)throw H(C);W();break;case"option":ee(F,C),D(";");break;default:if(Y(F,C)){U=!1;continue}throw H(C)}return _.filename=null,{package:k,imports:I,weakImports:R,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,s=r(3610),o=s.LongBits,i=s.utf8;function a(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function c(e){this.buf=e,this.pos=0,this.len=e.length}var l,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new c(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new c(e);throw Error("illegal buffer")},h=function(){return s.Buffer?function(e){return(c.create=function(e){return s.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new o(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw a(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw a(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function f(){if(this.pos+8>this.len)throw a(this,8);return new o(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=s.Array.prototype.subarray||s.Array.prototype.slice,c.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),c.prototype.int32=function(){return 0|this.uint32()},c.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},c.prototype.bool=function(){return 0!==this.uint32()},c.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return p(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|p(this.buf,this.pos+=4)},c.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var e=s.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},c.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var e=s.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},c.prototype.bytes=function(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw a(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,r);if(t===r){var n=s.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return i.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=h(),n._configure();var t=s.Long?"toLong":"toNumber";s.merge(c.prototype,{int64:function(){return d.call(this)[t](!1)},uint64:function(){return d.call(this)[t](!0)},sint64:function(){return d.call(this).zzDecode()[t](!1)},fixed64:function(){return f.call(this)[t](!0)},sfixed64:function(){return f.call(this)[t](!1)}})}},3158:(e,t,r)=>{"use strict";e.exports=o;var n=r(6237);(o.prototype=Object.create(n.prototype)).constructor=o;var s=r(3610);function o(e){n.call(this,e)}o._configure=function(){s.Buffer&&(o.prototype._slice=s.Buffer.prototype.slice)},o.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},o._configure()},5330:(e,t,r)=>{"use strict";e.exports=h;var n=r(8923);((h.prototype=Object.create(n.prototype)).constructor=h).className="Root";var s,o,i,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var s=this;if(!n)return u.asPromise(e,s,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in i)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){o.filename=e;var n,i=o(t,s,r),h=0;if(i.imports)for(;h-1))if(s.files.push(e),e in i)a?h(e,i[e]):(++f,setTimeout((function(){--f,h(e,i[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,s.fetch(e,(function(r,o){--f,n&&(r?t?f||c(null,s):c(r):h(e,o))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,y=0;y-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{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t,r){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(r)}(s.prototype=Object.create(n.EventEmitter.prototype)).constructor=s,s.prototype.rpcCall=function e(t,r,s,o,i){if(!o)throw TypeError("request must be specified");var a=this;if(!i)return n.asPromise(e,a,t,r,s,o);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(e,r){if(e)return a.emit("error",e,t),i(e);if(null!==r){if(!(r instanceof s))try{r=s[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),i(e)}return a.emit("data",r,t),i(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){i(e)}),0)}else setTimeout((function(){i(Error("already ended"))}),0)},s.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},9687:(e,t,r)=>{"use strict";e.exports=a;var n=r(8923);((a.prototype=Object.create(n.prototype)).constructor=a).className="Service";var s=r(8811),o=r(3262),i=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),o=0;o{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,s=/^ *[*/]+ */,o=/^\s*\*?\/*/,i=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],y=null;function m(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(i),g=0;g0)return g.shift();if(y)return function(){var t="'"===y?n:r;t.lastIndex=l-1;var s=t.exec(e);if(!s)throw m("string");return l=t.lastIndex,A(y),y=null,u(s[1])}();var s,o,i,p,f,S=0===l;do{if(l===h)return null;for(s=!1;a.test(i=b(l));)if("\n"===i&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw m("comment");if("/"===b(l))if(c){if(p=l,f=!1,v(l-1)){f=!0;do{if((l=E(l))===h)break;if(l++,!S)break}while(v(l))}else l=Math.min(h,E(l)+1);f&&(w(p,l,S),S=!0),d++,s=!0}else{for(f="/"===b(p=l+1);"\n"!==b(++l);)if(l===h)return null;++l,f&&(w(p,l-1,S),S=!0),++d,s=!0}else{if("*"!==(i=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===i&&++d,++l===h)throw m("comment");o=i,i=b(l)}while("*"!==o||"/"!==i);++l,f&&(w(p,l-2,S),S=!0),s=!0}}}while(s);var _=l;if(t.lastIndex=0,!t.test(b(_++)))for(;_{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var s=r(5643),o=r(1457),i=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),y=r(744),m=r(6434);function b(e,t){n.call(this,e,t),this.fields={},this.oneofs=void 0,this.extensions=void 0,this.reserved=void 0,this.group=void 0,this._fieldsById=null,this._fieldsArray=null,this._oneofsArray=null,this._ctor=null}function w(e){return e._fieldsById=e._fieldsArray=e._oneofsArray=null,delete e.encode,delete e.decode,delete e.verify,e}Object.defineProperties(b.prototype,{fieldsById:{get:function(){if(this._fieldsById)return this._fieldsById;this._fieldsById={};for(var e=Object.keys(this.fields),t=0;t{"use strict";var n=t,s=r(3262),o=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,s,o=e.exports=r(3610),i=r(4529);o.codegen=r(8561),o.fetch=r(5212),o.path=r(9207),o.fs=o.inquire("fs"),o.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[s]=e(t[s]||{},r,n);else{var o=t[s];o&&(n=[].concat(o).concat(n)),t[s]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(o,"decorateRoot",{get:function(){return i.decorated||(i.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=s;var n=r(3610);function s(e,t){this.lo=e>>>0,this.hi=t>>>0}var o=s.zero=new s(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var i=s.zeroHash="\0\0\0\0\0\0\0\0";s.fromNumber=function(e){if(0===e)return o;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new s(r,n)},s.from=function(e){if("number"==typeof e)return s.fromNumber(e);if(n.isString(e)){if(!n.Long)return s.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new s(e.low>>>0,e.high>>>0):o},s.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,r=~this.hi>>>0;return t||(r=r+1>>>0),-(t+4294967296*r)}return this.lo+4294967296*this.hi},s.prototype.toLong=function(e){return n.Long?new n.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var a=String.prototype.charCodeAt;s.fromHash=function(e){return e===i?o:new s((a.call(e,0)|a.call(e,1)<<8|a.call(e,2)<<16|a.call(e,3)<<24)>>>0,(a.call(e,4)|a.call(e,5)<<8|a.call(e,6)<<16|a.call(e,7)<<24)>>>0)},s.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},s.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},s.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},s.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}},3610:function(e,t,r){"use strict";var n=t;function s(e,t,r){for(var n=Object.keys(t),s=0;s0)},n.Buffer=function(){try{var e=n.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),n._Buffer_from=null,n._Buffer_allocUnsafe=null,n.newBuffer=function(e){return"number"==typeof e?n.Buffer?n._Buffer_allocUnsafe(e):new n.Array(e):n.Buffer?n._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},n.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,n.Long=n.global.dcodeIO&&n.global.dcodeIO.Long||n.global.Long||n.inquire("long"),n.key2Re=/^true|false|0|1$/,n.key32Re=/^-?(?:0|[1-9][0-9]*)$/,n.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,n.longToHash=function(e){return e?n.LongBits.from(e).toHash():n.LongBits.zeroHash},n.longFromHash=function(e,t){var r=n.LongBits.fromHash(e);return n.Long?n.Long.fromBits(r.lo,r.hi,t):r.toNumber(Boolean(t))},n.merge=s,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=o,n.ProtocolError=o("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;r-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{"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{"use strict";var n=t,s=r(2551);n[".google.protobuf.Any"]={fromObject:function(e){if(e&&e["@type"]){var t=e["@type"].substring(e["@type"].lastIndexOf("/")+1),r=this.lookup(t);if(r){var n="."===e["@type"].charAt(0)?e["@type"].slice(1):e["@type"];return-1===n.indexOf("/")&&(n="/"+n),this.create({type_url:n,value:r.encode(r.fromObject(e)).finish()})}}return this.fromObject(e)},toObject:function(e,t){var r="",n="";if(t&&t.json&&e.type_url&&e.value){n=e.type_url.substring(e.type_url.lastIndexOf("/")+1),r=e.type_url.substring(0,e.type_url.lastIndexOf("/")+1);var o=this.lookup(n);o&&(e=o.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof s){var i=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),i["@type"]=n,i}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,s=r(3610),o=s.LongBits,i=s.base64,a=s.utf8;function c(e,t,r){this.fn=e,this.len=t,this.next=void 0,this.val=r}function l(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function h(){this.len=0,this.head=new c(l,0,0),this.tail=this.head,this.states=null}var d=function(){return s.Buffer?function(){return(h.create=function(){return new n})()}:function(){return new h}};function p(e,t,r){t[r]=255&e}function f(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,r){for(;e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function y(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}h.create=d(),h.alloc=function(e){return new s.Array(e)},s.Array!==Array&&(h.alloc=s.pool(h.alloc,s.Array.prototype.subarray)),h.prototype._push=function(e,t,r){return this.tail=this.tail.next=new c(e,t,r),this.len+=t,this},f.prototype=Object.create(c.prototype),f.prototype.fn=function(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e},h.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new f((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},h.prototype.int32=function(e){return e<0?this._push(g,10,o.fromNumber(e)):this.uint32(e)},h.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},h.prototype.uint64=function(e){var t=o.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=o.from(e).zzEncode();return this._push(g,t.length(),t)},h.prototype.bool=function(e){return this._push(p,1,e?1:0)},h.prototype.fixed32=function(e){return this._push(y,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=o.from(e);return this._push(y,4,t.lo)._push(y,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(s.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(s.float.writeDoubleLE,8,e)};var m=s.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(p,1,0);if(s.isString(e)){var r=h.alloc(t=i.length(e));i.decode(e,r,0),e=r}return this.uint32(t)._push(m,t,e)},h.prototype.string=function(e){var t=a.length(e);return t?this.uint32(t)._push(a.write,t,e):this._push(p,1,0)},h.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new c(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this},h.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),r=0;e;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t},h._configure=function(e){n=e,h.create=d(),n._configure()}},818:(e,t,r)=>{"use strict";e.exports=o;var n=r(3449);(o.prototype=Object.create(n.prototype)).constructor=o;var s=r(3610);function o(){n.call(this)}function i(e,t,r){e.length<40?s.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}o._configure=function(){o.alloc=s._Buffer_allocUnsafe,o.writeBytesBuffer=s.Buffer&&s.Buffer.prototype instanceof Uint8Array&&"set"===s.Buffer.prototype.set.name?function(e,t,r){t.set(e,r)}:function(e,t,r){if(e.copy)e.copy(t,r,0,e.length);else for(var n=0;n>>0;return this.uint32(t),t&&this._push(o.writeBytesBuffer,t,e),this},o.prototype.string=function(e){var t=s.Buffer.byteLength(e);return this.uint32(t),t&&this._push(i,t,e),this},o._configure()},152:(e,t)=>{"use strict";class r{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){const n=r.toUint8Array(e),s=r.toUint8Array(t);if(n.length!==s.byteLength)return!1;for(let e=0;e{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var s=2&t&&e;"object"==typeof s&&!~leafPrototypes.indexOf(s);s=getProto(s))Object.getOwnPropertyNames(s).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>ie});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>ae,base16upper:()=>ce});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>le});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>pe});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base32:()=>fe,base32hex:()=>be,base32hexpad:()=>ve,base32hexpadupper:()=>Ee,base32hexupper:()=>we,base32pad:()=>ye,base32padupper:()=>me,base32upper:()=>ge,base32z:()=>Se});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base36:()=>Ae,base36upper:()=>_e});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base58btc:()=>ke,base58flickr:()=>Ie});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>Re,base64pad:()=>Te,base64url:()=>Ce,base64urlpad:()=>Ne});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>xe});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>Pe});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Be,decode:()=>Me,encode:()=>Ue,name:()=>De});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>$e,decode:()=>qe,encode:()=>He,name:()=>Fe});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>ht});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>gt,sha512:()=>yt});var f={};__webpack_require__.r(f),__webpack_require__.d(f,{aK:()=>Di,e8:()=>wi,DO:()=>bi,dJ:()=>Bi,OG:()=>Ui,My:()=>Ei,Ph:()=>Ri,lX:()=>Ti,Id:()=>Pi,fg:()=>$i,qj:()=>xi,aT:()=>Ii,r4:()=>Li,aY:()=>mi,x:()=>Vi,lq:()=>Ci,z:()=>Ni,zW:()=>Si,Q5:()=>qi});var g={};__webpack_require__.r(g),__webpack_require__.d(g,{Ed25519PrivateKey:()=>za,Ed25519PublicKey:()=>Ka,generateKeyPair:()=>Ya,generateKeyPairFromSeed:()=>Ja,unmarshalEd25519PrivateKey:()=>Ga,unmarshalEd25519PublicKey:()=>Wa});var y={};__webpack_require__.r(y),__webpack_require__.d(y,{MAX_RSA_KEY_SIZE:()=>pu,RsaPrivateKey:()=>gu,RsaPublicKey:()=>fu,fromJwk:()=>bu,generateKeyPair:()=>wu,unmarshalRsaPrivateKey:()=>yu,unmarshalRsaPublicKey:()=>mu});var m={};function b(e=0){return new Uint8Array(e)}function w(e=0){return new Uint8Array(e)}__webpack_require__.r(m),__webpack_require__.d(m,{Secp256k1PrivateKey:()=>Mu,Secp256k1PublicKey:()=>Uu,generateKeyPair:()=>Hu,unmarshalSecp256k1PrivateKey:()=>Fu,unmarshalSecp256k1PublicKey:()=>$u});const v=Math.pow(2,7),E=Math.pow(2,14),S=Math.pow(2,21),A=Math.pow(2,28),_=Math.pow(2,35),k=Math.pow(2,42),I=Math.pow(2,49),R=128,T=127;function C(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function N(e,t,r=0){switch(C(e)){case 8:t[r++]=255&e|R,e/=128;case 7:t[r++]=255&e|R,e/=128;case 6:t[r++]=255&e|R,e/=128;case 5:t[r++]=255&e|R,e/=128;case 4:t[r++]=255&e|R,e>>>=7;case 3:t[r++]=255&e|R,e>>>=7;case 2:t[r++]=255&e|R,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function x(e,t){let r=e[t],n=0;if(n+=r&T,r>>=7;case 3:t.set(r++,255&e|R),e>>>=7;case 2:t.set(r++,255&e|R),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function O(e,t=0){return e instanceof Uint8Array?x(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&T,r>>31>0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){const e=1+~this.lo>>>0;let t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){const e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){const e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){const e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return V;if(e<$&&e>H)return this.fromNumber(Number(e));const t=e<0n;t&&(e=-e);let r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>j&&(n=0n,++r>j&&(r=0n))),new q(Number(n),Number(r))}static fromNumber(e){if(0===e)return V;const t=e<0;t&&(e=-e);let r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new q(r,n)}static from(e){return"number"==typeof e?q.fromNumber(e):"bigint"==typeof e?q.fromBigInt(e):"string"==typeof e?q.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new q(e.low>>>0,e.high>>>0):V}}const V=new q(0,0);V.toBigInt=function(){return 0n},V.zzEncode=V.zzDecode=function(){return this},V.length=function(){return 1};const j=4294967296n;function K(e,t,r){const n=r;let s,o;for(let n=0;n>6|192,t[r++]=63&s|128):55296==(64512&s)&&56320==(64512&(o=e.charCodeAt(n+1)))?(s=65536+((1023&s)<<10)+(1023&o),++n,t[r++]=s>>18|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128,t[r++]=63&s|128):(t[r++]=s>>12|224,t[r++]=s>>6&63|128,t[r++]=63&s|128);return r-n}function z(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function G(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class W{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,z(this,10);return e}int32(){return 0|this.uint32()}sint32(){const e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw z(this,4);return G(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw z(this,4);return 0|G(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw z(this,4);const e=(t=this.buf,r=this.pos,D[0]=t[r],D[1]=t[r+1],D[2]=t[r+2],D[3]=t[r+3],L[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw z(this,4);const e=(t=this.buf,r=this.pos,M[0]=t[r],M[1]=t[r+1],M[2]=t[r+2],M[3]=t[r+3],M[4]=t[r+4],M[5]=t[r+5],M[6]=t[r+6],M[7]=t[r+7],U[0]);var t,r;return this.pos+=8,e}bytes(){const e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw z(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){const e=this.bytes();return function(e,t,r){if(r-t<1)return"";let n;const s=[];let o,i=0;for(;t191&&o<224?s[i++]=(31&o)<<6|63&e[t++]:o>239&&o<365?(o=((7&o)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[i++]=55296+(o>>10),s[i++]=56320+(1023&o)):s[i++]=(15&o)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,s)),i=0);return null!=n?(i>0&&n.push(String.fromCharCode.apply(String,s.slice(0,i))),n.join("")):String.fromCharCode.apply(String,s.slice(0,i))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw z(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw z(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){const e=new q(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw z(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw z(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw z(this,8);const e=G(this.buf,this.pos+=4),t=G(this.buf,this.pos+=4);return new q(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){const e=x(this.buf,this.pos);return this.pos+=C(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Y(e,t,r){const n=function(e){return new W(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function J(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}new Uint8Array(0);const X=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,i=new Uint8Array(o);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=o-1;(0!==u||h>>0,i[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");s=h,t++}if(" "!==e[t]){for(var p=o-s;p!==o&&0===i[p];)p++;for(var f=new Uint8Array(n+(o-p)),g=n;p!==o;)f[g++]=i[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,s=0,o=t.length;s!==o&&0===t[s];)s++,r++;for(var i=(o-s)*u+1>>>0,l=new Uint8Array(i);s!==o;){for(var h=t[s],d=0,p=i-1;(0!==h||d>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,s++}for(var f=i-n;f!==i&&0===l[f];)f++;for(var g=c.repeat(r);fJ(s(e))})}function oe({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return ne({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],s=(1<r;)i-=r,o+=t[s&a>>i];if(0!==i&&(o+=t[s&a<function(e,t,r,n){const s={};for(let e=0;e=8&&(a-=8,i[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}(t,n,r,e)})}const ie=se({prefix:"9",name:"base10",alphabet:"0123456789"}),ae=oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ce=oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),le=oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ue=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),he=ue.reduce(((e,t,r)=>(e[r]=t,e)),[]),de=ue.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e}),[]),pe=ne({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+he[t]),"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=de[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),fe=oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ge=oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ye=oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),me=oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),be=oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),we=oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ve=oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ee=oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Se=oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),Ae=se({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_e=se({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),ke=se({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ie=se({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Re=oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Te=oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ce=oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ne=oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),xe=oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Pe=ne({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),Oe=new TextEncoder,Le=new TextDecoder,De="json",Be=512;function Ue(e){return Oe.encode(JSON.stringify(e))}function Me(e){return JSON.parse(Le.decode(e))}const Fe="raw",$e=85;function He(e){return J(e)}function qe(e){return J(e)}var Ve=128,je=-128,Ke=Math.pow(2,31),ze=128,Ge=127,We=Math.pow(2,7),Ye=Math.pow(2,14),Je=Math.pow(2,21),Xe=Math.pow(2,28),Qe=Math.pow(2,35),Ze=Math.pow(2,42),et=Math.pow(2,49),tt=Math.pow(2,56),rt=Math.pow(2,63);const nt={encode:function e(t,r,n){r=r||[];for(var s=n=n||0;t>=Ke;)r[n++]=255&t|Ve,t/=128;for(;t&je;)r[n++]=255&t|Ve,t>>>=7;return r[n]=0|t,e.bytes=n-s+1,r},decode:function e(t,r){var n,s=0,o=0,i=r=r||0,a=t.length;do{if(i>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[i++],s+=o<28?(n&Ge)<=ze);return e.bytes=i-r,s},encodingLength:function(e){return eat(this.code,e)))}throw Error("Unknown type, must be binary type")}}function ft(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const gt=dt({name:"sha2-256",code:18,encode:ft("SHA-256")}),yt=dt({name:"sha2-512",code:19,encode:ft("SHA-512")});function mt(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==ke.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const s=t.get(n);if(null==s){const s=r.encode(e).slice(1);return t.set(n,s),s}return s}(r,wt(e),t??ke.encoder):function(e,t,r){const{prefix:n}=r,s=t.get(n);if(null==s){const s=r.encode(e);return t.set(n,s),s}return s}(r,wt(e),t??fe.encoder)}const bt=new WeakMap;function wt(e){const t=bt.get(e);if(null==t){const t=new Map;return bt.set(e,t),t}return t}class vt{code;version;multihash;bytes;"/";constructor(e,t,r,n){this.code=t,this.version=e,this.multihash=r,this.bytes=n,this["/"]=n}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{const{code:e,multihash:t}=this;if(e!==Et)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==St)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return vt.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{const{code:e,digest:t}=this.multihash,r=at(e,t);return vt.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return vt.equals(this,e)}static equals(e,t){const r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;{const r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r{const[r,n]=st(e.subarray(t));return t+=n,r};let n=r(),s=Et;if(18===n?(n=0,t=0):s=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const o=t,i=r(),a=r(),c=t+a;return{version:n,codec:s,multihashCode:i,digestSize:a,multihashSize:c-o,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??ke;return[ke.prefix,r.decode(`${ke.prefix}${e}`)]}case ke.prefix:{const r=t??ke;return[ke.prefix,r.decode(e)]}case fe.prefix:{const r=t??fe;return[fe.prefix,r.decode(e)]}case Ae.prefix:{const r=t??Ae;return[Ae.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),s=vt.decode(n);if(0===s.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return wt(s).set(r,e),s}}const Et=112,St=18;function At(e,t,r){const n=it(e),s=n+it(t),o=new Uint8Array(s+r.byteLength);return ot(e,o,0),ot(t,o,n),o.set(r,s),o}const _t=Symbol.for("@ipld/js-cid/CID"),kt={...l,...r,...c,...e,...t,...s,...o,...i,...a,...n};function It(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const Rt=It("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Tt=It("ascii","a",(e=>{let t="a";for(let r=0;r{const t=w((e=e.substring(1)).length);for(let r=0;r4096)return w(n);r+n>e&&(t=w(e),r=0);const s=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),s}}();class Dt{len;head;tail;states;constructor(){this.len=0,this.head=new xt(Pt,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new xt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Mt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Ft,10,q.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=q.fromBigInt(e);return this._push(Ft,t.length(),t)}uint64Number(e){return this._push(N,C(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){const t=q.fromBigInt(e).zzEncode();return this._push(Ft,t.length(),t)}sint64Number(e){const t=q.fromNumber(e).zzEncode();return this._push(Ft,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Bt,1,e?1:0)}fixed32(e){return this._push($t,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=q.fromBigInt(e);return this._push($t,4,t.lo)._push($t,4,t.hi)}fixed64Number(e){const t=q.fromNumber(e);return this._push($t,4,t.lo)._push($t,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(B,4,e)}double(e){return this._push(F,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Bt,1,0):this.uint32(t)._push(Ht,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Mt extends xt{next;constructor(e,t){super(Ut,e,t),this.next=void 0}}function Ft(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function $t(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function Ht(e,t,r){t.set(e,r)}function qt(e,t,r){t.set(e,r)}function Vt(e,t,r){e.length<40?K(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(Nt(e),r)}function jt(e,t){const r=new Dt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Kt,zt,Gt,Wt,Yt,Jt,Xt,Qt,Zt,er,tr,rr,nr,sr,or,ir,ar,cr,lr,ur,hr,dr,pr,fr,gr,yr,mr,br,wr,vr;function Er(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function Sr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return Er("enum",Kt.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function Ar(e,t){return Er("message",Kt.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Dt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(qt,t,e),this},Dt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(Vt,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(Kt||(Kt={})),Error;class _r extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}function kr(e){return Boolean(e)}function Ir(e){const t=new Map;return e.forEach((e=>{let r=t.get(e.contentTopic);r||(t.set(e.contentTopic,[]),r=t.get(e.contentTopic)),r.push(e)})),t}function Rr(e){return new Promise((t=>{setTimeout(t,e)}))}!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(zt||(zt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),zt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=zt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Gt||(Gt={})),function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(10),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(t=e.ContentFilter||(e.ContentFilter={})),e.codec=()=>(null==r&&(r=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.subscribe&&!1!==t.subscribe&&(r.uint32(8),r.bool(t.subscribe)),null!=t.topic&&""!==t.topic&&(r.uint32(18),r.string(t.topic)),null!=t.contentFilters)for(const n of t.contentFilters)r.uint32(26),e.ContentFilter.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const s={subscribe:!1,topic:"",contentFilters:[]},o=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:s.subscribe=t.bool();break;case 2:s.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&s.contentFilters.length===n.limits.contentFilters)throw new _r('Decode error - map field "contentFilters" had too many elements');s.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return s}))),r),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Wt||(Wt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.messages)for(const r of e.messages)t.uint32(10),Qt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new _r('Decode error - map field "messages" had too many elements');n.messages.push(Qt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Yt||(Yt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),Wt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),Yt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=Wt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=Yt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Jt||(Jt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Xt||(Xt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),Xt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=Xt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Qt||(Qt={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(Zt||(Zt={})),function(e){let t,r,n;!function(e){e.SUBSCRIBER_PING="SUBSCRIBER_PING",e.SUBSCRIBE="SUBSCRIBE",e.UNSUBSCRIBE="UNSUBSCRIBE",e.UNSUBSCRIBE_ALL="UNSUBSCRIBE_ALL"}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),function(e){e[e.SUBSCRIBER_PING=0]="SUBSCRIBER_PING",e[e.SUBSCRIBE=1]="SUBSCRIBE",e[e.UNSUBSCRIBE=2]="UNSUBSCRIBE",e[e.UNSUBSCRIBE_ALL=3]="UNSUBSCRIBE_ALL"}(r||(r={})),function(e){e.codec=()=>Sr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=Ar(((t,n,s={})=>{if(!1!==s.lengthDelimited&&n.fork(),null!=t.requestId&&""!==t.requestId&&(n.uint32(10),n.string(t.requestId)),null!=t.filterSubscribeType&&0!==r[t.filterSubscribeType]&&(n.uint32(16),e.FilterSubscribeType.codec().encode(t.filterSubscribeType,n)),null!=t.pubsubTopic&&(n.uint32(82),n.string(t.pubsubTopic)),null!=t.contentTopics)for(const e of t.contentTopics)n.uint32(90),n.string(e);!1!==s.lengthDelimited&&n.ldelim()}),((r,n,s={})=>{const o={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},i=null==n?r.len:r.pos+n;for(;r.pos>>3){case 1:o.requestId=r.string();break;case 2:o.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:o.pubsubTopic=r.string();break;case 11:if(null!=s.limits?.contentTopics&&o.contentTopics.length===s.limits.contentTopics)throw new _r('Decode error - map field "contentTopics" had too many elements');o.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return o}))),n),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(er||(er={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&0!==e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",statusCode:0},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(tr||(tr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),sr.codec().encode(e.wakuMessage,t)),null!=e.pubsubTopic&&(t.uint32(18),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.wakuMessage=sr.codec().decode(e,e.uint32(),{limits:r.limits?.wakuMessage});break;case 2:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(rr||(rr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(nr||(nr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),nr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=nr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(sr||(sr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.pubsubTopic&&""!==e.pubsubTopic&&(t.uint32(10),t.string(e.pubsubTopic)),null!=e.message&&(t.uint32(18),lr.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=lr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(or||(or={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.isSuccess&&!1!==e.isSuccess&&(t.uint32(8),t.bool(e.isSuccess)),null!=e.info&&(t.uint32(18),t.string(e.info)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={isSuccess:!1},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.isSuccess=e.bool();break;case 2:n.info=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ir||(ir={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),or.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),ir.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=or.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=ir.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(cr||(cr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),cr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=cr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(lr||(lr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),fr.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=fr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(ur||(ur={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new _r('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new _r('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(hr||(hr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),ur.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new _r('Decode error - map field "messages" had too many elements');n.messages.push(ur.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(dr||(dr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.proof&&e.proof.byteLength>0&&(t.uint32(10),t.bytes(e.proof)),null!=e.merkleRoot&&e.merkleRoot.byteLength>0&&(t.uint32(18),t.bytes(e.merkleRoot)),null!=e.epoch&&e.epoch.byteLength>0&&(t.uint32(26),t.bytes(e.epoch)),null!=e.shareX&&e.shareX.byteLength>0&&(t.uint32(34),t.bytes(e.shareX)),null!=e.shareY&&e.shareY.byteLength>0&&(t.uint32(42),t.bytes(e.shareY)),null!=e.nullifier&&e.nullifier.byteLength>0&&(t.uint32(50),t.bytes(e.nullifier)),null!=e.rlnIdentifier&&e.rlnIdentifier.byteLength>0&&(t.uint32(58),t.bytes(e.rlnIdentifier)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={proof:b(0),merkleRoot:b(0),epoch:b(0),shareX:b(0),shareY:b(0),nullifier:b(0),rlnIdentifier:b(0)},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.proof=e.bytes();break;case 2:n.merkleRoot=e.bytes();break;case 3:n.epoch=e.bytes();break;case 4:n.shareX=e.bytes();break;case 5:n.shareY=e.bytes();break;case 6:n.nullifier=e.bytes();break;case 7:n.rlnIdentifier=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(pr||(pr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(10),t.bytes(e.payload)),null!=e.contentTopic&&""!==e.contentTopic&&(t.uint32(18),t.string(e.contentTopic)),null!=e.version&&(t.uint32(24),t.uint32(e.version)),null!=e.timestamp&&(t.uint32(80),t.sint64(e.timestamp)),null!=e.meta&&(t.uint32(90),t.bytes(e.meta)),null!=e.rateLimitProof&&(t.uint32(170),pr.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:b(0),contentTopic:""},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=pr.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(fr||(fr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(gr||(gr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(yr||(yr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.peerInfos)for(const r of e.peerInfos)t.uint32(10),gr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new _r('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(gr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(mr||(mr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),yr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),mr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.query=yr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=mr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(br||(br={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new _r('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(wr||(wr={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.clusterId&&(t.uint32(8),t.uint32(e.clusterId)),null!=e.shards)for(const r of e.shards)t.uint32(16),t.uint32(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={shards:[]},s=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new _r('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>jt(t,e.codec()),e.decode=(t,r)=>Y(t,e.codec(),r)}(vr||(vr={}));function Tr(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Cr(e,...t){if(!((r=e)instanceof Uint8Array||null!=r&&"object"==typeof r&&"Uint8Array"===r.constructor.name))throw new Error("Uint8Array expected");var r;if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Nr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Tr(e.outputLen),Tr(e.blockLen)}function xr(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Pr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Or=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),Lr=(e,t)=>e<<32-t|e>>>t;new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Dr=async()=>{};async function Br(e,t,r){let n=Date.now();for(let s=0;s=0&&ee().update(Ur(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Hr(e=32){if(Pr&&"function"==typeof Pr.getRandomValues)return Pr.getRandomValues(new Uint8Array(e));if(Pr&&"function"==typeof Pr.randomBytes)return Pr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}const qr=(e,t,r)=>e&t^e&r^t&r;class Vr extends Mr{constructor(e,t,r,n){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Or(this.buffer)}update(e){xr(this);const{view:t,buffer:r,blockLen:n}=this,s=(e=Ur(e)).length;for(let o=0;on-o&&(this.process(r,0),o=0);for(let e=o;e>s&o),a=Number(r&o),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),s),this.process(r,0);const i=Or(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,s=Lr(r,17)^Lr(r,19)^r>>>10;zr[e]=s+zr[e-7]+n+zr[e-16]|0}let{A:r,B:n,C:s,D:o,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Lr(i,6)^Lr(i,11)^Lr(i,25))+((u=i)&a^~u&c)+jr[e]+zr[e]|0,h=(Lr(r,2)^Lr(r,13)^Lr(r,22))+qr(r,n,s)|0;l=c,c=a,a=i,i=o+t|0,o=s,s=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,s,o,i,a,c,l)}roundClean(){zr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Wr=$r((()=>new Gr));var Yr,Jr,Xr,Qr,Zr;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(Yr||(Yr={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout",e.RLN_IDENTITY_MISSING="Identity credentials are not set",e.RLN_MEMBERSHIP_INDEX="Membership index is not set",e.RLN_LIMIT_MISSING="User message limit is not set",e.RLN_PROOF_GENERATION="Proof generation failed"}(Jr||(Jr={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(Xr||(Xr={})),function(e){e.PEER_DISCOVERY_BOOTSTRAP="peer:discovery:bootstrap",e.PEER_DISCOVERY_PEER_EXCHANGE="peer:discovery:peer-exchange",e.PEER_CONNECT_BOOTSTRAP="peer:connected:bootstrap",e.PEER_CONNECT_PEER_EXCHANGE="peer:connected:peer-exchange"}(Qr||(Qr={})),function(e){e.CONNECTION_STATUS="waku:connection"}(Zr||(Zr={}));const en="@waku/bootstrap",tn={clusterId:1,shards:[0,1,2,3,4,5,6,7,8]};var rn;function nn(e,t="utf8"){const r=Ct[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function sn(e){return"string"==typeof e?Nt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}!function(e){e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"}(rn||(rn={}));const on=e=>nn(e,"base16"),an=e=>nn(e,"utf8"),cn=e=>Nt(e,"utf8");function ln(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}const un=e=>{if("contentTopics"in e&&e.contentTopics)return Array.from(new Set(e.contentTopics.map((t=>fn(t,e.clusterId)))));if("shards"in e){if(void 0===e.shards)throw new Error("Invalid shard");return Array.from(new Set(e.shards.map((t=>`/waku/2/rs/${e.clusterId??1}/${t}`))))}if("application"in e&&"version"in e)return[fn(`/${e.application}/${e.version}/default/default`,e.clusterId)];throw new Error("Missing required configuration in shard parameters")},hn=e=>{const t=e.split("/");if(6!=t.length||"waku"!==t[1]||"2"!==t[2]||"rs"!==t[3])throw new Error("Invalid pubsub topic");const r=parseInt(t[4]),n=parseInt(t[5]);if(isNaN(r)||isNaN(n))throw new Error("Invalid clusterId or shard");return{clusterId:r,shard:n}},dn=e=>{const t=new Set,r=new Set;for(const n of e){const{clusterId:e,shard:s}=hn(n);t.add(`${e}:${s}`),r.add(e)}if(0===t.size)throw new Error("No valid pubsub topics provided");if(r.size>1)throw new Error("Pubsub topics from multiple cluster IDs are not supported");return{clusterId:r.values().next().value,shards:Array.from(t).map((e=>parseInt(e.split(":")[1])))}};function pn(e,t){if(!t.includes(e))throw new Error(`Pubsub topic ${e} has not been configured on this instance. Configured topics are: ${t}. Please update your configuration by passing in the topic during Waku node instantiation.`)}function fn(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${function(e,t=8){const{application:r,version:n}=function(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),s=Wr(ln([cn(r),cn(n)])),o=new DataView(s.buffer.slice(-8));return Number(o.getBigUint64(0,!1)%BigInt(t))}(e,r)}`}function gn(e,t){return"string"==typeof t?t:void 0!==t?.shard?(e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??1}/${e.shard}`})(t):fn(e,t?.clusterId??1)}const yn=e=>{if((e=new Uint8Array(e)).length<3)throw new Error("Insufficient data");const t=new DataView(e.buffer),r=t.getUint16(0),n=[];if(130===e.length)for(let e=0;e<1024;e++){const r=Math.floor(e/8)+2,s=7-e%8;t.getUint8(r)&1<=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(o))}}return{clusterId:r,shards:n}},mn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,s=new ArrayBuffer(n),o=new DataView(s);if(o.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;o.setUint8(t,o.getUint8(t)|1<{const t=[];for await(const r of e)t.push(r);return t})();const t=[];for(const r of e)t.push(r);return t};function Cn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=w(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Nn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(const r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!On(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(const r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!On(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){const t=Pn(this.bufs,e);return t.buf[t.index]}set(e,t){const r=Pn(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){const{bufs:r,length:n}=this._subList(e,t);return Cn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:Cn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),s=new Ln;return s.length=n,s.bufs=[...r],s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};const r=[];let n=0;for(let s=0;s=a)continue;const c=e>=i&&ei&&t<=a;if(c&&l){if(e===i&&t===a){r.push(o);break}const n=e-i;r.push(o.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(o);continue}r.push(o.subarray(e-i))}else{if(l){if(t===a){r.push(o);break}r.push(o.subarray(0,t-i));break}r.push(o)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(On(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');const r=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");const s=new Int32Array(256);for(let e=0;e<256;e++)s[e]=-1;for(let e=0;e=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-o[n]);break}}if(0===c)return e}return-1}getInt8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){const r=w(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){const n=b(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){const t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){const r=w(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){const r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){const n=b(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){const r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){const n=b(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){const r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){const n=b(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Ln))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;te+t.byteLength),0)),r.length=t,r}}function Dn(e){return null!=e[Symbol.asyncIterator]}const Bn=e=>{const t=C(e),r=w(t);return P(e,r),Bn.bytes=t,r};function Un(e,t){const r=(t=t??{}).lengthEncoder??Bn;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Dn(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Bn.bytes=0,Un.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Bn;return new Ln(r(e.byteLength),e)};class Mn extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class Fn extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class $n extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class Hn extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var qn;!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(qn||(qn={}));const Vn=e=>{const t=O(e);return Vn.bytes=C(t),t};function jn(e,t){const r=new Ln;let n=qn.LENGTH,s=-1;const o=t?.lengthDecoder??Vn,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===qn.LENGTH)try{if(s=o(r),s<0)throw new Mn("Invalid message length");if(s>a)throw new Fn("Message length too long");const e=o.bytes;r.consume(e),null!=t?.onLength&&t.onLength(s),n=qn.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>i)throw new $n("Message length length too long");break}throw e}if(n===qn.DATA){if(r.byteLength0)throw new Hn("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Hn("Unexpected end of input")}()}function Kn(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Vn.bytes=0,jn.fromReader=(e,t)=>{let r=1;return jn(async function*(){for(;;)try{const{done:t,value:n}=await e.next(r);if(!0===t)return;null!=n&&(yield n)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{r=1}}(),{...t??{},onLength:e=>{r=e}})};class zn{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||e-1&e)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){const e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Gn{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new zn(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=e?.byteLength?e.byteLength:1}push(e){if(null!=e?.value&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){const t=this.head;this.head=t.next=new zn(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(void 0===e&&null!=this.tail.next){const t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return null!=e?.value&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}}class Wn extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Yn(e={}){return function(e,t){let r,n,s,o=(t=t??{}).onEnd,i=new Gn,a=Kn();const c=e=>null!=n?n(e):(i.push(e),r),l=e=>{if(s)return r;if(!0!==t?.objectMode&&null==e?.byteLength)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return c({done:!1,value:e})},u=e=>s?r:(s=!0,null!=e?(e=>(i=new Gn,null!=n?n({error:e}):(i.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return i.isEmpty()?s?{done:!0}:await new Promise(((t,s)=>{n=o=>{n=null,i.push(o);try{t(e(i))}catch(e){s(e)}return r}})):e(i)}finally{i.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=Kn()}))}},return:()=>(i=new Gn,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return i.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),i.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new Wn)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==o)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=o&&(o(e),o=void 0),{done:!0}),return:()=>(h.return(),null!=o&&(o(),o=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=o&&(o(e),o=void 0),r),get readableLength(){return h.readableLength},onEmpty:e=>h.onEmpty(e)},r}((e=>{const t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),e)}const Jn=function(...e){const t=[];for(const r of e)null==r[Symbol.asyncIterator]&&t.push(r);return t.length===e.length?function*(){for(const e of t)yield*e}():async function*(){const t=Yn({objectMode:!0});Promise.resolve().then((async()=>{try{await Promise.all(e.map((async e=>{for await(const r of e)t.push(r)}))),t.end()}catch(e){t.end(e)}})),yield*t}()};function Xn(e,...t){if(null==e)throw new Error("Empty pipeline");if(ts(e)){const t=e;e=()=>t.source}else if(es(e)||Zn(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&ts(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e{let t;for(;e.length>0;)t=e.shift()(t);return t},Zn=e=>null!=e?.[Symbol.asyncIterator],es=e=>null!=e?.[Symbol.iterator],ts=e=>null!=e&&null!=e.sink&&null!=e.source,rs=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Yn({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const s=e.source;if(Zn(s))n=async function*(){yield*s,t.end()};else{if(!es(s))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*s,t.end()}}return Jn(t,n())}return e.source};function ns(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const ss="consumed";class os{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new vn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=ns(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,s;for(let o=0;o{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=ns(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[ss]=!0}isStreamLocked(e){return!!e.metadata[ss]}}class is{multicodec;components;log;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r,n){this.multicodec=e,this.components=t,this.log=r,this.pubsubTopics=n,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new os(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}async allPeers(){return async function(e,t){const r=[];return await e.forEach((e=>{for(let n=0;nthis.components.connectionManager.getConnections(e.id).length>0))}async getPeers({numPeers:e,maxBootstrapPeers:t}={maxBootstrapPeers:0,numPeers:0}){const r=function(e,t,r){let n=e.filter((e=>e.tags.has(Xr.BOOTSTRAP))).slice(0,r);t>0&&t!e.tags.has(Xr.BOOTSTRAP)));if(0===t)return[...n,...s];const o=[...n];for(;o.length0;){const e=Math.floor(Math.random()*s.length),t=s.splice(e,1)[0];o.push(t)}return o}(await this.connectedPeers(),e,t),n=await async function(e,t){return 0===t.length?[]:(await Promise.all(t.map((async t=>{try{const r=(await e.get(t.id)).metadata.get("ping");return r?{peer:t,ping:Number(an(r))}:{peer:t,ping:1/0}}catch(e){return{peer:t,ping:1/0}}})))).filter((e=>null!==e)).sort(((e,t)=>e.ping-t.ping)).map((e=>e.peer))}(this.components.peerStore,r);return 0===n.length&&this.log.warn("No peers found. Ensure you have a connection to the network."),n.length{ys.error("Failed to register ",bs,e)}))}async subscribe(e,t,r){const n=await this.getStream(t),s=fs.createSubscribeRequest(e,r);let o;try{o=await Xn([s.encode()],Un,n,jn,(async e=>await Tn(e)))}catch(e){return ys.error("Failed to send subscribe request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:t.id}}}const{statusCode:i,requestId:a,statusDesc:c}=gs.decode(o[0].slice());return i<200||i>=300?(ys.error(`Filter subscribe request ${a} failed with status code ${i}: ${c}`),{failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async unsubscribe(e,t,r){let n;try{n=await this.getStream(t)}catch(e){return ys.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:t.id}}}const s=fs.createUnsubscribeRequest(e,r);try{await Xn([s.encode()],Un,n.sink)}catch(e){return ys.error("Failed to send unsubscribe request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=fs.createUnsubscribeAllRequest(e),s=await Xn([n.encode()],Un,r,jn,(async e=>await Tn(e)));if(!s||!s.length)return{failure:{error:Jr.NO_RESPONSE,peerId:t.id},success:null};const{statusCode:o,requestId:i,statusDesc:a}=gs.decode(s[0].slice());return o<200||o>=300?(ys.error(`Filter unsubscribe all request ${i} failed with status code ${o}: ${a}`),{failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:t.id},success:null}):{failure:null,success:t.id}}async ping(e){let t;try{t=await this.getStream(e)}catch(t){return ys.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:e.id}}}const r=fs.createSubscriberPingRequest();let n;try{n=await Xn([r.encode()],Un,t,jn,(async e=>await Tn(e)))}catch(t){return ys.error("Failed to send ping request",t),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:Jr.NO_RESPONSE,peerId:e.id}};const{statusCode:s,requestId:o,statusDesc:i}=gs.decode(n[0].slice());return s<200||s>=300?(ys.error(`Filter ping request ${o} failed with status code ${s}: ${i}`),{success:null,failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;ys.info(`Received message from ${n.toString()}`);try{Xn(r,jn,(async e=>{for await(const r of e){const e=ps.decode(r.slice()),{pubsubTopic:n,wakuMessage:s}=e;if(!s)return void ys.error("Received empty message");if(!n)return void ys.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,s,t.remotePeer.toString())}})).then((()=>{ys.info("Receiving pipe closed.")}),(async e=>{ys.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){ys.error("Error decoding message",e)}}}class vs{proto;constructor(e){this.proto=e}static createRequest(e,t){return new vs({requestId:ds(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=ar.decode(e);return new vs(t)}encode(){return ar.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const Es=new vn("light-push"),Ss="/vac/waku/lightpush/2.0.0-beta1";class As extends is{pubsubTopics;constructor(e,t){super(Ss,t.components,Es,e),this.pubsubTopics=e}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return Es.error("Failed to send waku light push: payload is empty"),{query:null,error:Jr.EMPTY_PAYLOAD};if(!await async function(e,t){const r=await e.toWire(t);return!!r&&(e=>e.length/1048576<=1)(r)}(e,t))return Es.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:Jr.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:vs.createRequest(r,e.pubsubTopic),error:null}:(Es.error("Failed to encode to protoMessage, aborting push"),{query:null,error:Jr.ENCODE_FAILED})}catch(e){return Es.error("Failed to prepare push message",e),{query:null,error:Jr.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:s}=await this.preparePushMessage(e,t);if(s||!n)return{success:null,failure:{error:s,peerId:r.id}};let o,i;try{o=await this.getStream(r)}catch(e){return Es.error("Failed to get stream",e),{success:null,failure:{error:Jr.NO_STREAM_AVAILABLE,peerId:r.id}}}try{i=await Xn([n.encode()],Un,o,jn,(async e=>await Tn(e)))}catch(e){return Es.error("Failed to send waku light push request",e),{success:null,failure:{error:Jr.GENERIC_FAIL,peerId:r.id}}}const a=new Ln;let c;i.forEach((e=>{a.append(e)}));try{c=vs.decode(a).response}catch(e){return Es.error("Failed to decode push reply",e),{success:null,failure:{error:Jr.DECODE_FAILED,peerId:r.id}}}if(!c)return Es.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:Jr.NO_RESPONSE,peerId:r.id}};if((l=c.info)&&l.includes("could not generate rln-v2 proof")){const e=(e=>{const t={[Jr.RLN_IDENTITY_MISSING]:Jr.RLN_IDENTITY_MISSING,[Jr.RLN_MEMBERSHIP_INDEX]:Jr.RLN_MEMBERSHIP_INDEX,[Jr.RLN_LIMIT_MISSING]:Jr.RLN_LIMIT_MISSING},r=e.toLowerCase();for(const e in t)if(r.includes(e.toLowerCase()))return t[e];return Jr.RLN_PROOF_GENERATION})(c.info);return Es.error("Remote peer rejected the message: ",e),{success:null,failure:{error:e,peerId:r.id}}}var l;return c.isSuccess?{success:r.id,failure:null}:(Es.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:Jr.REMOTE_PEER_REJECTED,peerId:r.id}})}}const _s={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},ks=1e6;class Is{proto;constructor(e){this.proto=e}static create(e){const t=new Is({...e,requestId:ds(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*ks):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*ks):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0});if(e.pubsubTopic&&!e.contentTopics||!e.pubsubTopic&&e.contentTopics)throw new Error("Both pubsubTopic and contentTopics must be set or unset");if(e.messageHashes&&(e.pubsubTopic||e.contentTopics||e.timeStart||e.timeEnd))throw new Error("Message hash lookup queries cannot include content filter criteria");return t}static decode(e){const t=hr.decode(e);return new Is(t)}encode(){return hr.encode(this.proto)}}class Rs{proto;constructor(e){this.proto=e}static decode(e){const t=dr.decode(e);return new Rs(t)}encode(){return dr.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const Ts=new vn("store"),Cs="/vac/waku/store-query/3.0.0";class Ns extends is{pubsubTopics;constructor(e,t){super(Cs,t.components,Ts,e),this.pubsubTopics=e}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const s=Is.create({...e,paginationCursor:n});let o;try{o=await this.getStream(r)}catch(e){Ts.error("Failed to get stream",e);break}const i=await Xn([s.encode()],Un,o,jn,(async e=>await Tn(e))),a=new Ln;i.forEach((e=>{a.append(e)}));const c=Rs.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw Ts.error(e),new Error(e)}if(!c.messages||!c.messages.length){Ts.warn("Stopping pagination due to empty messages in response");break}Ts.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const s=t.get(r);if(s)return s.fromProtoObj(e.pubsubTopic||"",(n=e.message,{..._s,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}class xs extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new Ps(e,t))}}const Ps=globalThis.CustomEvent,Os=new vn("keep-alive");class Ls{relay;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,libp2p:r}){this.options=e,this.relay=t,this.libp2p=r}start(e){this.stop(e);const{pingKeepAlive:t,relayKeepAlive:r}=this.options,n=e.toString();if(0!==t){const r=setInterval((()=>{(async()=>{let r;try{try{r=await this.libp2p.services.ping.ping(e),Os.info(`Ping succeeded (${n})`,r)}catch(e){return void Os.error(`Ping failed for peer (${n}).\n Next ping will be attempted in ${t} seconds.\n `)}try{await this.libp2p.peerStore.merge(e,{metadata:{ping:cn(r.toString())}})}catch(e){Os.error("Failed to update ping",e)}}catch(e){Os.error(`Ping failed (${n})`,e)}})()}),1e3*t);this.pingKeepAliveTimers.set(n,r)}const s=this.relay;if(s&&0!==r){const t=this.scheduleRelayPings(s,r,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(const e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){const n=[];for(const s of e.pubsubTopics){if(!e.getMeshPeers(s).includes(r))continue;const o=kn({pubsubTopicShardInfo:hn(s),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),i=setInterval((()=>{Os.info("Sending Waku Relay ping message"),e.send(o,{payload:new Uint8Array([1])}).catch((e=>Os.error("Failed to send relay ping",e)))}),1e3*t);n.push(i)}return n}}const Ds=new vn("connection-manager");class Bs extends xs{configuredPubsubTopics;static instances=new Map;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];isP2PNetworkConnected=!1;isConnected(){return!(globalThis?.navigator&&!globalThis?.navigator?.onLine)&&this.isP2PNetworkConnected}static create(e,t,r,n,s,o){let i=Bs.instances.get(e);return i||(i=new Bs(t,r,n,s,o),Bs.instances.set(e,i)),i}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"]),this.stopNetworkStatusListener()}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),Ds.info(`Dropped connection with peer ${e.toString()}`)}catch(t){Ds.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],s=[],o=[],i=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(Xr.BOOTSTRAP)?r.push(t):e.includes(Xr.PEER_EXCHANGE)?n.push(t):e.includes(Xr.LOCAL)&&s.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(Xr.BOOTSTRAP)?o.push(t):r.includes(Xr.PEER_EXCHANGE)?i.push(t):r.includes(Xr.LOCAL)&&a.push(t)}return{DISCOVERED:{[Xr.BOOTSTRAP]:r,[Xr.PEER_EXCHANGE]:n,[Xr.LOCAL]:s},CONNECTED:{[Xr.BOOTSTRAP]:o,[Xr.PEER_EXCHANGE]:i,[Xr.LOCAL]:a}}}constructor(e,t,r,n,s){super(),this.configuredPubsubTopics=r,this.libp2p=e,this.configuredPubsubTopics=r,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,...s},this.keepAliveManager=new Ls({relay:n,libp2p:e,options:t}),this.startEventListeners().then((()=>Ds.info("Connection Manager is now running"))).catch((e=>Ds.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>Ds.error("Unexpected error while dialing peer store peers",e)))}async dialPeerStorePeers(){const e=await this.libp2p.peerStore.all(),t=[];for(const r of e)this.libp2p.getConnections().find((e=>e.remotePeer===r.id))||t.push(this.attemptDial(r.id));try{await Promise.all(t)}catch(e){Ds.error("Unexpected error while dialing peer store peers",e)}}async startEventListeners(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener(),this.startNetworkStatusListener()}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1),this.keepAliveManager.start(e);break}catch(r){r instanceof AggregateError?Ds.error(`Error dialing peer ${e.toString()} - ${r.errors}`):Ds.error(`Error dialing peer ${e.toString()} - ${r.message}`),this.dialErrorsForPeer.set(e.toString(),r),t++,this.dialAttemptsForPeer.set(e.toString(),t)}if(this.currentActiveParallelDialCount--,this.processDialQueue(),t===this.options.maxDialAttemptsForPeer)try{const t=this.dialErrorsForPeer.get(e.toString());if(t){let r;t instanceof AggregateError?t.errors?0===t.errors.length?Ds.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):Ds.warn("No errors array found for AggregateError"):r=t.message,Ds.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e),await this.attemptDnsDiscovery()}catch(t){throw new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async attemptDnsDiscovery(){if(this.libp2p.getConnections().length>0)return;if((await this.libp2p.peerStore.all()).length>0)return;Ds.info("Attempting to trigger DNS discovery.");const e=Object.values(this.libp2p.components.components).find((e=>!(!e||!e.toString)&&e.toString().includes(en)));e&&await e.findPeers()}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{Ds.error(e)}))}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(e){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):await this.dialPeer(e))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){Ds.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{Ds.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t),(await this.getTagNamesForPeer(t)).includes(Xr.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(Xr.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new Ps(Qr.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new Ps(Qr.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.setP2PNetworkConnected()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.setP2PNetworkDisconnected()})()},"browser:network":()=>{this.dispatchWakuConnectionEvent()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return Ds.warn(`Already connected to peer ${e.toString()}. Not dialing.`),!1;if(!await this.isPeerTopicConfigured(e)){const t=await this.getPeerShardInfo(e,this.libp2p.peerStore);return Ds.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(Ds.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(Ds.warn(`Peer ${e.toString()} is not dialable based on bootstrap status. Not dialing.`),!1)}async isPeerDialableBasedOnBootstrapStatus(e){return!(await this.getTagNamesForPeer(e)).some((e=>e===Xr.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===Xr.BOOTSTRAP)))).lengththis.configuredPubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return yn(r)}startNetworkStatusListener(){try{globalThis.addEventListener("online",this.onEventHandlers["browser:network"]),globalThis.addEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Ds.error(`Failed to start network listener: ${e}`)}}stopNetworkStatusListener(){try{globalThis.removeEventListener("online",this.onEventHandlers["browser:network"]),globalThis.removeEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Ds.error(`Failed to stop network listener: ${e}`)}}setP2PNetworkConnected(){this.isP2PNetworkConnected||(this.isP2PNetworkConnected=!0,this.dispatchWakuConnectionEvent())}setP2PNetworkDisconnected(){this.isP2PNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isP2PNetworkConnected=!1,this.dispatchWakuConnectionEvent())}dispatchWakuConnectionEvent(){this.dispatchEvent(new Ps(Zr.CONNECTION_STATUS,{detail:this.isConnected()}))}}class Us{static instance;health;constructor(){this.health={overallStatus:rn.Unhealthy,protocolStatuses:new Map}}static getInstance(){return Us.instance||(Us.instance=new Us),Us.instance}getHealthStatus(){return this.health.overallStatus}getProtocolStatus(e){return this.health.protocolStatuses.get(e)}updateProtocolHealth(e,t){const r=this.getNameFromMulticodec(e);let n=rn.Unhealthy;1==t?n=rn.MinimallyHealthy:t>=2&&(n=rn.SufficientlyHealthy),this.health.protocolStatuses.set(r,{name:r,status:n,lastUpdate:new Date}),this.updateOverallHealth()}getNameFromMulticodec(e){let t;if(e.includes("filter"))t=Yr.Filter;else if(e.includes("lightpush"))t=Yr.LightPush;else{if(!e.includes("store"))throw new Error(`Unknown protocol: ${e}`);t=Yr.Store}return t}updateOverallHealth(){const e=[Yr.LightPush,Yr.Filter].map((e=>this.getProtocolStatus(e)?.status));e.some((e=>e===rn.Unhealthy))?this.health.overallStatus=rn.Unhealthy:e.some((e=>e===rn.MinimallyHealthy))?this.health.overallStatus=rn.MinimallyHealthy:this.health.overallStatus=rn.SufficientlyHealthy}}const Ms=()=>Us.getInstance(),Fs=new vn("metadata"),$s="/vac/waku/metadata/1.0.0";class Hs extends is{pubsubTopics;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super($s,t.components,Fs,e),this.pubsubTopics=e,this.libp2pComponents=t,t.registrar.handle($s,(e=>{this.onRequest(e)}))}async query(e){const t=wr.encode(dn(this.pubsubTopics)),r=await this.libp2pComponents.peerStore.get(e);if(!r)return{shardInfo:null,error:Jr.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(o){return Fs.error("Failed to get stream",o),{shardInfo:null,error:Jr.NO_STREAM_AVAILABLE}}const s=await Xn([t],Un,n,jn,(async e=>await Tn(e))),{error:o,shardInfo:i}=this.decodeMetadataResponse(s);return o?{shardInfo:null,error:o}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=vr.encode(dn(this.pubsubTopics)),s=await Xn([n],Un,t,jn,(async e=>await Tn(e))),{error:o,shardInfo:i}=this.decodeMetadataResponse(s);if(o)return;await this.savePeerShardInfo(r.remotePeer,i)}catch(e){Fs.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new Ln;e.forEach((e=>{t.append(e)}));const r=vr.decode(t);return r?{shardInfo:r,error:null}:(Fs.error("Error decoding metadata response"),{shardInfo:null,error:Jr.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:mn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function qs(e){return t=>new Hs(e,t)}const Vs=Symbol.for("@libp2p/peer-id");function js(e){return null!=e&&Boolean(e[Vs])}const Ks=new class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){const t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){const t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{const t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{let s=0,o=0;const i=this.peekChar();if(void 0===i)return;const a="0"===i,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(s*=e,s+=r,s>c)return;if(o+=1,void 0!==t&&o>t)return}return 0===o||!r&&a&&o>1?void 0:s}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;tthis.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}const n=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===n)return[r,!1];e[r]=n>>8,e[r+1]=255&n}return[e.length,!1]};return this.readAtomically((()=>{const t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(n)return;if(void 0===this.readGivenChar(":"))return;if(void 0===this.readGivenChar(":"))return;const s=new Uint8Array(14),o=16-(r+2),[i]=e(s.subarray(0,o));return t.set(s.subarray(0,i),16-i),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function zs(e){return Boolean(function(e){if(!(e.length>15))return Ks.new(e).parseWith((()=>Ks.readIPv4Addr()))}(e))}function Gs(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ks.new(e).parseWith((()=>Ks.readIPv6Addr()))}(e))}function Ws(e){return Boolean(function(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Ks.new(e).parseWith((()=>Ks.readIPAddr()))}(e))}parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);const Ys=zs,Js=Gs,Xs=function(e){let t=0;if(e=e.toString().trim(),Ys(e)){const r=new Uint8Array(t+4);return e.split(/\./g).forEach((e=>{r[t++]=255&parseInt(e,10)})),r}if(Js(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)e.push("0");r.splice.apply(r,e)}const s=new Uint8Array(t+16);for(n=0;n>8&255,s[t++]=255&e}return s}throw new Error("invalid ip address")},Qs=-1,Zs={},eo={};function to(e){if("number"==typeof e){if(null!=eo[e])return eo[e];throw new Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=Zs[e])return Zs[e];throw new Error(`no protocol with name: ${e}`)}throw new Error("invalid protocol id type: "+typeof e)}function ro(e,t){switch(to(e).code){case 4:case 41:return function(e){const t=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let s=0;s65536)throw new Error("Port number is not in range(1, 65536)");const s=io(n);return Cn([r,s],r.length+s.length)}(t);case 445:return function(e){const t=e.split(":");if(2!==t.length)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(56!==t[0].length)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);const r=fe.decode(`b${t[0]}`),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");const s=io(n);return Cn([r,s],r.length+s.length)}(t);case 466:return function(e){const t=oo.decode(e),r=Uint8Array.from(P(t.length));return Cn([r,t],r.length+t.length)}(t);case 481:return co(globalThis.decodeURIComponent(t));default:return Nt(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Qs,"ip6zone"],[43,8,"ipcidr"],[53,Qs,"dns",!0],[54,Qs,"dns4",!0],[55,Qs,"dns6",!0],[56,Qs,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,Qs,"unix",!1,!0],[421,Qs,"ipfs"],[421,Qs,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Qs,"garlic64"],[448,0,"tls"],[449,Qs,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Qs,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Qs,"http-path"],[777,Qs,"memory"]].forEach((e=>{const t=function(e,t,r,n,s){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(s)}}(...e);eo[t.code]=t,Zs[t.name]=t})),to("ip4"),to("ip6"),to("ipcidr");const so=Object.values(kt).map((e=>e.decoder)),oo=function(){let e=so[0].or(so[1]);return so.slice(2).forEach((t=>e=e.or(t))),e}();function io(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function ao(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function co(e){const t=Nt(e),r=Uint8Array.from(P(t.length));return Cn([r,t],r.length+t.length)}function lo(e){const t=O(e);if((e=e.slice(C(t))).length!==t)throw new Error("inconsistent lengths");return nn(e)}function uo(e){const t=[],r=[];let n=null,s=0;for(;se.length)throw yo("Invalid address Uint8Array: "+nn(e,"base16"));t.push([o,l]);const u=ro(o,l);if(r.push([o,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:ho(r),tuples:t,stringTuples:r,path:n}}function ho(e){const t=[];return e.map((e=>{const r=to(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),go(t.join("/"))}function po(e){return Cn(e.map((e=>{const t=to(e[0]);let r=Uint8Array.from(P(t.code));return e.length>1&&null!=e[1]&&(r=Cn([r,e[1]])),r})))}function fo(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=O(t instanceof Uint8Array?t:Uint8Array.from(t));return e+C(e)}}function go(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function yo(e){return new Error("Error parsing address: "+e)}const mo=Symbol.for("nodejs.util.inspect.custom"),bo=Symbol.for("@multiformats/js-multiaddr/multiaddr"),wo=[to("dns").code,to("dns4").code,to("dns6").code,to("dnsaddr").code];class vo extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class Eo{bytes;#t;#r;#n;#s;[bo]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=uo(e);else if("string"==typeof e){if(e.length>0&&"/"!==e.charAt(0))throw new Error(`multiaddr "${e}" must start with a "/"`);t=function(e){const t=[],r=[];let n=null;const s=(e=go(e)).split("/").slice(1);if(1===s.length&&""===s[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let o=0;o=s.length)throw yo("invalid address: "+e);if(!0===i.path){n=go(s.slice(o).join("/")),t.push([i.code,no(i.code,n)]),r.push([i.code,n]);break}const a=no(i.code,s[o]);t.push([i.code,a]),r.push([i.code,ro(i.code,a)])}return{string:ho(r),bytes:po(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!Ao(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=uo(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#s=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,s="";const o=to("tcp"),i=to("udp"),a=to("ip4"),c=to("ip6"),l=to("dns6"),u=to("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(s=`%${d??""}`),wo.includes(h)&&(t=o.name,n=443,r=`${d??""}${s}`,e=h===l.code?6:4),h!==o.code&&h!==i.code||(t=to(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=to(h).name,r=`${d??""}${s}`,e=h===c.code?6:4);if(null==e||null==t||null==r||null==n)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:r,transport:t,port:n}}protos(){return this.#r.map((([e])=>Object.assign({},to(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>to(e).name))}tuples(){return this.#r}stringTuples(){return this.#n}encapsulate(e){return e=new Eo(e),new Eo(this.toString()+e.toString())}decapsulate(e){const t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new Eo(r.slice(0,n))}decapsulateCode(e){const t=this.tuples();for(let r=t.length-1;r>=0;r--)if(t[r][0]===e)return new Eo(po(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===Zs.p2p.code&&e.push([t,r]),t===Zs["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?nn(ke.decode(`z${e}`),"base58btc"):nn(vt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#s}equals(e){return Nn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=So.get(t.name);if(null==r)throw new vo(`no available resolver for ${t.name}`);return(await r(this,e)).map((e=>_o(e)))}nodeAddress(){const e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(e){const t=(e??this).protos();return!(2!==t.length||4!==t[0].code&&41!==t[0].code||6!==t[1].code&&273!==t[1].code)}[mo](){return`Multiaddr(${this.#t})`}}const So=new Map;function Ao(e){return Boolean(e?.[bo])}function _o(e){return new Eo(e)}new Error("timeout while waiting for mutex to become available"),new Error("mutex already locked");const ko=new Error("request for lock canceled");class Io{constructor(e,t=ko){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(((r,n)=>{const s={resolve:r,reject:n,weight:e,priority:t},o=Ro(this._queue,(e=>t<=e.priority));-1===o&&e<=this._value?this._dispatchItem(s):this._queue.splice(o+1,0,s)}))}runExclusive(e){return t=this,r=arguments,s=function*(e,t=1,r=0){const[n,s]=yield this.acquire(t,r);try{return yield e(n)}finally{s()}},new((n=void 0)||(n=Promise))((function(e,o){function i(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(t){var r;t.done?e(t.value):(r=t.value,r instanceof n?r:new n((function(e){e(r)}))).then(i,a)}c((s=s.apply(t,r||[])).next())}));var t,r,n,s}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise((r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),function(e,t){const r=Ro(e,(e=>t.priority<=e.priority));e.splice(r+1,0,t)}(this._weightedWaiters[e-1],{resolve:r,priority:t})}))}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach((e=>e.reject(this._cancelError))),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(0===this._queue.length)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach((e=>e.resolve())),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const r=this._weightedWaiters[t-1];if(!r)continue;const n=r.findIndex((t=>t.priority<=e));(-1===n?r:r.splice(0,n)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(0===this._queue.length||this._queue[0].priority=0;r--)if(t(e[r]))return r;return-1}class To{constructor(e){this._semaphore=new Io(1,e)}acquire(){return e=this,t=arguments,n=function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t},new((r=void 0)||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}));var e,t,r,n}runExclusive(e,t=0){return this._semaphore.runExclusive((()=>e()),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}class Co{connectionManager;core;log;peers=new Map;healthManager;readMutex=new To;writeMutex=new To;writeLockHolder=null;constructor(e,t,r){this.connectionManager=e,this.core=t,this.log=r,this.healthManager=Ms(),this.healthManager.updateProtocolHealth(this.core.multicodec,0)}getWriteLockHolder(){return this.writeLockHolder}getPeers(){return Array.from(this.peers.values())}async addPeer(e){return this.writeMutex.runExclusive((async()=>{this.writeLockHolder=`addPeer: ${e.id.toString()}`,await this.connectionManager.attemptDial(e.id),this.peers.set(e.id.toString(),e),this.log.info(`Added and dialed peer: ${e.id.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null}))}async removePeer(e){return this.writeMutex.runExclusive((()=>{this.writeLockHolder=`removePeer: ${e.toString()}`,this.peers.delete(e.toString()),this.log.info(`Removed peer: ${e.toString()}`),this.healthManager.updateProtocolHealth(this.core.multicodec,this.peers.size),this.writeLockHolder=null}))}async getPeerCount(){return this.readMutex.runExclusive((()=>this.peers.size))}async hasPeers(){return this.readMutex.runExclusive((()=>this.peers.size>0))}async removeExcessPeers(e){this.log.info(`Removing ${e} excess peer(s)`);const t=Array.from(this.peers.values()).slice(0,e);for(const e of t)await this.removePeer(e.id)}async findAndAddPeers(e){const t=await this.findPeers(e);return 0===t.length?(this.log.warn("No additional peers found"),[]):this.addMultiplePeers(t)}async findPeers(e){const t=await this.core.getPeers();return this.readMutex.runExclusive((async()=>t.filter((e=>!this.peers.has(e.id.toString()))).slice(0,e)))}async addMultiplePeers(e){const t=[];for(const r of e)await this.addPeer(r),t.push(r);return t}}class No{core;connectionManager;peerManager;numPeersToUse;maintainPeersIntervalId=null;log;constructor(e,t,r){this.core=e,this.connectionManager=t,this.log=new vn(`sdk:${e.multicodec}`),this.numPeersToUse=r?.numPeersToUse??2;const n=r?.maintainPeersInterval??3e4;this.peerManager=new Co(t,e,this.log),this.log.info(`Initializing BaseProtocolSDK with numPeersToUse: ${this.numPeersToUse}, maintainPeersInterval: ${n}ms`),this.startMaintainPeersInterval(n)}get connectedPeers(){return this.peerManager.getPeers().slice(0,this.numPeersToUse)}async renewPeer(e){this.log.info(`Attempting to renew peer ${e}`);const t=await this.peerManager.findPeers(1);if(0!==t.length)return await this.peerManager.removePeer(e),await this.peerManager.addPeer(t[0]),this.log.info(`Successfully renewed peer. New peer: ${t[0].id}`),t[0];this.log.error("Failed to find a new peer to replace the disconnected one")}stopMaintainPeersInterval(){this.maintainPeersIntervalId?(clearInterval(this.maintainPeersIntervalId),this.maintainPeersIntervalId=null,this.log.info("Maintain peers interval stopped")):this.log.info("Maintain peers interval was not running")}async hasPeers(e={}){const{forceUseAllPeers:t=!1,maxAttempts:r=3}=e;this.log.info(`Checking for peers. forceUseAllPeers: ${t}, maxAttempts: ${r}`);for(let e=0;e0)return this.log.info(`At least one peer connected (${this.connectedPeers.length}), not forcing use of all peers`),!0;if(this.connectedPeers.length>=this.numPeersToUse)return this.log.info(`Required number of peers (${this.numPeersToUse}) reached`),!0;this.log.warn(`Found only ${this.connectedPeers.length}/${this.numPeersToUse} required peers. Retrying...`)}return this.log.error(`Failed to find required number of peers (${this.numPeersToUse}) after ${r} attempts`),!1}async startMaintainPeersInterval(e){this.log.info(`Starting maintain peers interval with ${e}ms interval`);try{this.maintainPeersIntervalId=setInterval((()=>{this.log.info("Running scheduled peer maintenance"),this.maintainPeers().catch((e=>{this.log.error("Error during scheduled peer maintenance:",e)}))}),e),this.log.info("Maintain peers interval started successfully")}catch(e){throw this.log.error("Error starting maintain peers interval:",e),e}}async maintainPeers(){try{const e=await this.peerManager.getPeerCount(),t=this.numPeersToUse-e;if(this.log.info(`Current peer count: ${e}, target: ${this.numPeersToUse}`),0===t)return void this.log.info("Peer count is at target, no maintenance required");t>0?(this.log.info(`Attempting to add ${t} peer(s)`),await this.peerManager.findAndAddPeers(t)):(this.log.info(`Attempting to remove ${Math.abs(t)} excess peer(s)`),await this.peerManager.removeExcessPeers(Math.abs(t)));const r=await this.peerManager.getPeerCount();this.log.info(`Peer maintenance completed. Initial count: ${e}, Final count: ${r}`)}catch(e){this.log.error("Error during peer maintenance",{error:e})}}}const xo=1e4,Po=!1,Oo={keepAlive:xo,enableLightPushFilterCheck:Po};function Lo(e,t){const r=cn(e),n=cn(t.contentTopic),s=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(t)}(t.timestamp),o=ln([r,t.payload,n,t.meta,s].filter(kr));return Wr(o)}const Do=new vn("sdk:receiver:reliability_monitor");class Bo{pubsubTopic;getPeers;renewPeer;getContentTopics;protocolSubscribe;addLibp2pEventListener;sendLightPushMessage;receivedMessagesFormPeer=new Set;receivedMessages=new Set;scheduledVerification=new Map;verifiedPeers=new Set;peerFailures=new Map;maxPingFailures=3;peerRenewalLocks=new Set;constructor(e,t,r,n,s,o,i){this.pubsubTopic=e,this.getPeers=t,this.renewPeer=r,this.getContentTopics=n,this.protocolSubscribe=s,this.addLibp2pEventListener=o,this.sendLightPushMessage=i,this.addLibp2pEventListener("peer:disconnect",(e=>{const t=e.detail;this.getPeers().some((e=>e.id.equals(t)))&&this.renewAndSubscribePeer(t)}))}setMaxPingFailures(e){void 0!==e&&(this.maxPingFailures=e)}async handlePingResult(e,t){if(t?.success)return void this.peerFailures.delete(e.toString());const r=(this.peerFailures.get(e.toString())||0)+1;if(this.peerFailures.set(e.toString(),r),r>=this.maxPingFailures)try{Do.info(`Attempting to renew ${e.toString()} due to ping failures.`),await this.renewAndSubscribePeer(e),this.peerFailures.delete(e.toString())}catch(t){Do.error(`Failed to renew peer ${e.toString()}: ${t}.`)}}notifyMessageReceived(e,t){const r=this.buildMessageHash(t);return this.verifiedPeers.add(e),this.receivedMessagesFormPeer.add(`${e}-${r}`),Do.info(`notifyMessage received debug: ephemeral:${t.ephemeral}\t${an(t.payload)}`),Do.info(`notifyMessage received: peer:${e}\tmessage:${r}`),!!this.receivedMessages.has(r)||(this.receivedMessages.add(r),!1)}notifyMessageSent(e,t){const r=e.toString(),n=this.buildMessageHash(t);if(Do.info(`notifyMessage sent debug: ${an(t.payload)}`),this.scheduledVerification.has(r))return void Do.warn(`notifyMessage sent: attempting to schedule verification for pending peer:${r}\tmessage:${n}`);const s=window.setTimeout((async()=>{const t=this.verifiedPeers.has(r),s=this.receivedMessagesFormPeer.has(`${r}-${n}`);t||s?Do.info(`notifyMessage sent setTimeout: verified that peer pushes filter messages, peer:${r}\tmessage:${n}`):(Do.warn(`notifyMessage sent setTimeout: peer didn't return probe message, attempting renewAndSubscribe, peer:${r}\tmessage:${n}`),this.scheduledVerification.delete(r),await this.renewAndSubscribePeer(e))}),5e3);this.scheduledVerification.set(r,s)}shouldVerifyPeer(e){const t=e.toString(),r=this.verifiedPeers.has(t),n=this.scheduledVerification.has(t);return!(r||n)}buildMessageHash(e){return function(e,t){const r=Lo(e,t);return on(r)}(this.pubsubTopic,e)}async renewAndSubscribePeer(e){const t=e.toString();try{if(this.peerRenewalLocks.has(t))return void Do.info(`Peer ${t} is already being renewed.`);this.peerRenewalLocks.add(t);const r=await this.renewPeer(e);return r?(await this.protocolSubscribe(this.pubsubTopic,r,this.getContentTopics()),await this.sendLightPushMessage(r),this.peerFailures.delete(t),r):void Do.warn(`Failed to renew peer ${t}: No new peer found.`)}catch(e){return void Do.error(`Failed to renew peer ${t}: ${e}.`)}finally{this.peerRenewalLocks.delete(t)}}}class Uo{static receiverMonitors=new Map;static createReceiverMonitor(e,t,r,n,s,o,i){if(Uo.receiverMonitors.has(e))return Uo.receiverMonitors.get(e);const a=new Bo(e,t,r,n,s,o,i);return Uo.receiverMonitors.set(e,a),a}constructor(){}static stop(e){this.receiverMonitors.delete(e)}static stopAll(){for(const[e,t]of this.receiverMonitors)t.setMaxPingFailures(void 0),this.receiverMonitors.delete(e)}}const Mo=new vn("sdk:filter:subscription_manager");class Fo{pubsubTopic;protocol;connectionManager;getPeers;renewPeer;libp2p;lightPush;reliabilityMonitor;keepAliveTimeout=xo;keepAliveInterval=null;enableLightPushFilterCheck=Po;subscriptionCallbacks;constructor(e,t,r,n,s,o,i){this.pubsubTopic=e,this.protocol=t,this.connectionManager=r,this.getPeers=n,this.renewPeer=s,this.libp2p=o,this.lightPush=i,this.pubsubTopic=e,this.subscriptionCallbacks=new Map,this.reliabilityMonitor=Uo.createReceiverMonitor(this.pubsubTopic,this.getPeers.bind(this),this.renewPeer.bind(this),(()=>Array.from(this.subscriptionCallbacks.keys())),this.protocol.subscribe.bind(this.protocol),this.protocol.addLibp2pEventListener.bind(this.protocol),this.sendLightPushCheckMessage.bind(this))}async subscribe(e,t,r=Oo){this.reliabilityMonitor.setMaxPingFailures(r.pingsBeforePeerRenewed),this.keepAliveTimeout=r.keepAlive||xo,this.enableLightPushFilterCheck=r?.enableLightPushFilterCheck||Po;const n=Array.isArray(e)?e:[e];for(const e of n)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:Jr.TOPIC_DECODER_MISMATCH}],successes:[]};this.enableLightPushFilterCheck&&n.push(Rn(this.buildLightPushContentTopic(),this.pubsubTopic));const s=Ir(n),o=Array.from(s.keys()),i=this.getPeers().map((async e=>this.subscribeWithPeerVerification(e,o))),a=await Promise.allSettled(i),c=this.handleResult(a,"subscribe");return s.forEach(((e,r)=>{const n={decoders:e,callback:t};r!==this.buildLightPushContentTopic()&&this.subscriptionCallbacks.set(r,n)})),this.startSubscriptionsMaintenance(this.keepAliveTimeout),c}async unsubscribe(e){const t=this.getPeers().map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.stopSubscriptionsMaintenance(),n}async ping(e){Mo.info("Sending keep-alive ping");const t=(e?[e]:this.getPeers().map((e=>e.id))).map((e=>this.pingSpecificPeer(e))),r=await Promise.allSettled(t);return this.handleResult(r,"ping")}async unsubscribeAll(){const e=this.getPeers().map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.stopSubscriptionsMaintenance(),r}async processIncomingMessage(e,t){if(this.reliabilityMonitor.notifyMessageReceived(t,e))return void Mo.info("Message already received, skipping");const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(Mo.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:s}=e,{contentTopic:o}=r;if(o)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),o=await Promise.any(e);await s(o)}catch(e){Mo.error("Error decoding message",e)}else Mo.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):Mo.error("No subscription callback available for ",r)}async subscribeWithPeerVerification(e,t){const r=await this.protocol.subscribe(this.pubsubTopic,e,t);return await this.sendLightPushCheckMessage(e),r}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)Mo.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:Jr.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}async pingSpecificPeer(e){const t=this.getPeers().find((t=>t.id.equals(e)));if(!t)return{success:null,failure:{peerId:e,error:Jr.NO_PEER_AVAILABLE}};let r;try{r=await this.protocol.ping(t)}catch(t){r={success:null,failure:{peerId:e,error:Jr.GENERIC_FAIL}}}return Mo.info(`Received result from filter ping peerId:${e.toString()}\tsuccess:${r.success?.toString()}\tfailure:${r.failure?.error}`),await this.reliabilityMonitor.handlePingResult(e,r),r}startSubscriptionsMaintenance(e){Mo.info("Starting subscriptions maintenance"),this.startKeepAlivePings(e),this.startConnectionListener()}stopSubscriptionsMaintenance(){Mo.info("Stopping subscriptions maintenance"),this.stopKeepAlivePings(),this.stopConnectionListener()}startConnectionListener(){this.connectionManager.addEventListener(Zr.CONNECTION_STATUS,this.connectionListener.bind(this))}stopConnectionListener(){this.connectionManager.removeEventListener(Zr.CONNECTION_STATUS,this.connectionListener.bind(this))}async connectionListener({detail:e}){if(e){try{await this.ping()}catch(e){Mo.error(`networkStateListener failed to recover: ${e}`)}this.startKeepAlivePings(this.keepAliveTimeout)}else this.stopKeepAlivePings()}startKeepAlivePings(e){this.keepAliveInterval?Mo.info("Recurring pings already set up."):this.keepAliveInterval=setInterval((()=>{this.ping()}),e)}stopKeepAlivePings(){this.keepAliveInterval?(Mo.info("Stopping recurring pings."),clearInterval(this.keepAliveInterval),this.keepAliveInterval=null):Mo.info("Already stopped recurring pings.")}async sendLightPushCheckMessage(e){if(this.lightPush&&this.libp2p&&this.reliabilityMonitor.shouldVerifyPeer(e.id)){const t=kn({contentTopic:this.buildLightPushContentTopic(),pubsubTopic:this.pubsubTopic,ephemeral:!0}),r={payload:new Uint8Array(1)},n=await t.toProtoObj(r);setTimeout((async()=>{const s=await this.lightPush.protocol.send(t,r,e);this.reliabilityMonitor.notifyMessageSent(e.id,n),s.failure&&Mo.error(`failed to send lightPush ping message to peer:${e.id.toString()}\t${s.failure.error}`)}),1e4)}}buildLightPushContentTopic(){return`/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`}}const $o=new vn("sdk:filter");class Ho extends No{libp2p;lightPush;protocol;activeSubscriptions=new Map;constructor(e,t,r,n){super(new ws((async(e,t,r)=>{const n=this.getActiveSubscription(e);n?await n.processIncomingMessage(t,r):$o.error(`No subscription locally registered for topic ${e}`)}),e.configuredPubsubTopics,t),e,{numPeersToUse:n?.numPeersToUse}),this.libp2p=t,this.lightPush=r,this.protocol=this.core,this.activeSubscriptions=new Map}async subscribe(e,t,r,n=Oo){const s=this.getUniquePubsubTopics(e);if(1!==s.length)return{subscription:null,error:Jr.INVALID_DECODER_TOPICS,results:null};const o=s[0],{subscription:i,error:a}=await this.createSubscription(o,r);if(a)return{subscription:null,error:a,results:null};const{failures:c,successes:l}=await i.subscribe(e,t,n);return{subscription:i,error:null,results:{failures:c,successes:l}}}async createSubscription(e,t){t={autoRetry:!0,...t};const r="string"==typeof e?e:un(e)?.[0];return pn(r,this.protocol.pubsubTopics),await this.hasPeers(t)?($o.info(`Creating filter subscription with ${this.connectedPeers.length} peers: `,this.connectedPeers.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(r)??this.setActiveSubscription(r,new Fo(r,this.protocol,this.connectionManager,(()=>this.connectedPeers),this.renewPeer.bind(this),this.libp2p,this.lightPush))}):{error:Jr.NO_PEER_AVAILABLE,subscription:null}}async subscribeWithUnsubscribe(e,t,r=Oo){const n=this.getUniquePubsubTopics(e);if(0===n.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(n.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:s,error:o}=await this.createSubscription(n[0]);if(o)throw Error(`Failed to create subscription: ${o}`);await s.subscribe(e,t,r);const i=Array.from(Ir(Array.isArray(e)?e:[e]).keys());return async()=>{await s.unsubscribe(i)}}toSubscriptionIterator(e){return async function(e,t,r){const n=[];let s;s=await e.subscribeWithUnsubscribe(t,(e=>{n.push(e)}));const o=Number.isInteger(r?.timeoutMs),i=Date.now();return{iterator:async function*(){for(;;){if(o&&Date.now()-i>=0)return;await Rr(60);const e=n.shift();if(!s&&0===n.length)return e;!e&&s||(yield e)}}(),async stop(){s&&(await s(),s=void 0)}}}(this,e)}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}getUniquePubsubTopics(e){if(!Array.isArray(e))return[e.pubsubTopic];if(0===e.length)return[];const t=new Set(e.map((e=>e.pubsubTopic)));return[...t]}}const qo=new vn("sdk:light-push"),Vo={autoRetry:!1,maxAttempts:3};class jo{libp2p;numPeersToUse=2;protocol;constructor(e,t,r){this.libp2p=t,this.numPeersToUse=r?.numPeersToUse??2,this.protocol=new As(e.configuredPubsubTopics,t)}async send(e,t,r=Vo){const n=[],s=[],{pubsubTopic:o}=e;try{pn(o,this.protocol.pubsubTopics)}catch(e){return qo.error("Failed to send waku light push: pubsub topic not configured"),{successes:n,failures:[{error:Jr.TOPIC_NOT_CONFIGURED}]}}const i=await this.getConnectedPeers();if(0===i.length)return{successes:n,failures:[{error:Jr.NO_PEER_AVAILABLE}]};const a=await Promise.allSettled(i.map((r=>this.protocol.send(e,t,r))));for(const o of a){if("fulfilled"!==o.status){qo.error("Failed unexpectedly while sending:",o.reason),s.push({error:Jr.GENERIC_FAIL});continue}const{failure:i,success:a}=o.value;a?n.push(a):i&&(s.push(i),r?.autoRetry&&this.attemptRetries((r=>this.protocol.send(e,t,r)),r.maxAttempts))}return Ms().updateProtocolHealth(this.protocol.multicodec,n.length),{successes:n,failures:s}}async attemptRetries(e,t){t=t||3;const r=await this.getConnectedPeers();if(0!==r.length)for(let n=0;n{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((e=>e.protocols.includes(Ss))).slice(0,this.numPeersToUse)}}const Ko=new vn("waku:store:sdk");class zo extends No{protocol;constructor(e,t){super(new Ns(e.configuredPubsubTopics,t),e,{numPeersToUse:1}),this.protocol=this.core}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:s}=this.validateDecodersAndPubsubTopic(e),o={pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t},i=(await this.protocol.getPeers({numPeers:this.numPeersToUse,maxBootstrapPeers:1}))[0];if(!i)throw Ko.error("No peers available to query"),new Error("No peers available to query");Ko.info(`Querying store with options: ${JSON.stringify(t)}`);const a=this.protocol.queryPerPage(o,s,i);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){Ko.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){Ko.info("Querying store with promise callback");let n=!1;for await(const s of this.queryGenerator(e,r)){const e=s.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(kr);return await Promise.all(n.map((async e=>{e&&!r&&(r=Boolean(await t(e)))}))),r}createCursor(e){return Lo(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw Ko.error("No decoders provided"),new Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw Ko.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=t[0];pn(r,this.protocol.pubsubTopics);const n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw Ko.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const s=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===s.length)throw Ko.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:s,decodersAsMap:n}}}const Go=new vn("wait-for-remote-peer");async function Wo(e,t){Go.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async s=>{if(s.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(s.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Go.error("Connection closed. Some peers can be on different shard."),Go.error(`Error waiting for metadata: ${e}`)}}};t.addEventListener("peer:identify",n)}))}const Yo=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Jo=new vn("waku");class Xo{pubsubTopics;libp2p;relay;store;filter;lightPush;connectionManager;health;constructor(e,t,r,n,s){this.pubsubTopics=e,this.relay=s,this.libp2p=r,n={filter:!1,lightpush:!1,store:!1,...n};const o=t.pingKeepAlive||300,i=this.relay?t.relayKeepAlive||300:0,a=this.libp2p.peerId.toString();if(this.connectionManager=Bs.create(a,r,{pingKeepAlive:o,relayKeepAlive:i},this.pubsubTopics,this.relay),this.health=Ms(),n.store){const e=(c=this.connectionManager,e=>new zo(c,e));this.store=e(r)}var c;if(n.lightpush){const e=function(e,t={}){return r=>new jo(e,r,t)}(this.connectionManager,t);this.lightPush=e(r)}if(n.filter){const e=function(e,t,r){return n=>new Ho(e,n,t,r)}(this.connectionManager,this.lightPush,t);this.filter=e(r)}Jo.info("Waku node created",a,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}async dial(e,t){const r=t??[],n=this.mapToPeerIdOrMultiaddr(e);void 0===t&&(this.relay&&r.push(Yr.Relay),this.store&&r.push(Yr.Store),this.filter&&r.push(Yr.Filter),this.lightPush&&r.push(Yr.LightPush));const s=[];return r.includes(Yr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>s.push(e))):Jo.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.Store)&&(this.store?s.push(this.store.protocol.multicodec):Jo.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.LightPush)&&(this.lightPush?s.push(this.lightPush.protocol.multicodec):Jo.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Yr.Filter)&&(this.filter?s.push(this.filter.protocol.multicodec):Jo.error("Filter codec not included in dial codec: protocol not mounted locally")),Jo.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,s)}async start(){await this.libp2p.start()}async stop(){Uo.stopAll(),this.connectionManager.stop(),await this.libp2p.stop()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Yr.Relay),e.filter&&t.push(Yr.Filter),e.store&&t.push(Yr.Store),e.lightPush&&t.push(Yr.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");if(n.length>0&&!t.includes(Yr.Relay)){const r=await async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,s=function(e){const t=new Map,r={[Yr.Filter]:ms,[Yr.LightPush]:Ss,[Yr.Store]:Cs};for(const n of e)r[n]&&t.set(r[n],!1);return t}(t);if(!r.length||!n)return Go.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`),!1;for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>s.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{s.has(e)&&s.set(e,!0)})),Array.from(s.values()).every((e=>e))))return!0}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&Go.error("Connection closed. Some peers can be on different shard."),Go.error(`Error while iterating through peers: ${e}`);continue}return!1}(e,t);if(r)return}const s=[];if(t.includes(Yr.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");s.push(e.relay.waitForPeers())}if(t.includes(Yr.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");s.push(Wo(Cs,e.libp2p))}if(t.includes(Yr.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");s.push(Wo(Ss,e.libp2p))}if(t.includes(Yr.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");s.push(Wo(ms,e.libp2p))}r?await async function(e,t){await Promise.race([e,Yo(t,"Timed out waiting for a remote peer.")])}(Promise.all(s),r):await Promise.all(s)}(this,e,t)}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}mapToPeerIdOrMultiaddr(e){return js(e)?e:_o(e)}}class Qo extends Error{code;type;constructor(e="The operation was aborted"){super(e),this.name="AbortError",this.code=Qo.code,this.type=Qo.type}static code="ABORT_ERR";static type="aborted"}class Zo extends Error{code;props;constructor(e,t,r){super(e),this.code=t,this.name=r?.name??"CodeError",this.props=r??{}}}class ei extends AggregateError{code;props;constructor(e,t,r,n){super(e,t),this.code=r,this.name=n?.name??"AggregateCodeError",this.props=n??{}}}Error,Error,Error;const ti="ERR_TIMEOUT";function ri(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}const ni=BigInt(2**32-1),si=BigInt(32);function oi(e,t=!1){return t?{h:Number(e&ni),l:Number(e>>si&ni)}:{h:0|Number(e>>si&ni),l:0|Number(e&ni)}}const ii={fromBig:oi,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let s=0;sBigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<>>32-r,rotlSL:(e,t,r)=>t<>>32-r,rotlBH:(e,t,r)=>t<>>64-r,rotlBL:(e,t,r)=>e<>>64-r,add:function(e,t,r,n){const s=(t>>>0)+(n>>>0);return{h:e+r+(s/2**32|0)|0,l:0|s}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,s)=>t+r+n+s+(e/2**32|0)|0,add5H:(e,t,r,n,s,o)=>t+r+n+s+o+(e/2**32|0)|0,add5L:(e,t,r,n,s)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(s>>>0)},ai=ii,[ci,li]=(()=>ai.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),ui=new Uint32Array(80),hi=new Uint32Array(80);class di extends Vr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:t,Bh:r,Bl:n,Ch:s,Cl:o,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,s,o,i,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,s,o,i,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|s,this.Cl=0|o,this.Dh=0|i,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)ui[r]=e.getUint32(t),hi[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|ui[e-15],r=0|hi[e-15],n=ai.rotrSH(t,r,1)^ai.rotrSH(t,r,8)^ai.shrSH(t,r,7),s=ai.rotrSL(t,r,1)^ai.rotrSL(t,r,8)^ai.shrSL(t,r,7),o=0|ui[e-2],i=0|hi[e-2],a=ai.rotrSH(o,i,19)^ai.rotrBH(o,i,61)^ai.shrSH(o,i,6),c=ai.rotrSL(o,i,19)^ai.rotrBL(o,i,61)^ai.shrSL(o,i,6),l=ai.add4L(s,c,hi[e-7],hi[e-16]),u=ai.add4H(l,n,a,ui[e-7],ui[e-16]);ui[e]=0|u,hi[e]=0|l}let{Ah:r,Al:n,Bh:s,Bl:o,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:y,Hl:m}=this;for(let e=0;e<80;e++){const t=ai.rotrSH(u,h,14)^ai.rotrSH(u,h,18)^ai.rotrBH(u,h,41),b=ai.rotrSL(u,h,14)^ai.rotrSL(u,h,18)^ai.rotrBL(u,h,41),w=u&d^~u&f,v=h&p^~h&g,E=ai.add5L(m,b,v,li[e],hi[e]),S=ai.add5H(E,y,t,w,ci[e],ui[e]),A=0|E,_=ai.rotrSH(r,n,28)^ai.rotrBH(r,n,34)^ai.rotrBH(r,n,39),k=ai.rotrSL(r,n,28)^ai.rotrBL(r,n,34)^ai.rotrBL(r,n,39),I=r&s^r&i^s&i,R=n&o^n&a^o&a;y=0|f,m=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=ai.add(0|c,0|l,0|S,0|A)),c=0|i,l=0|a,i=0|s,a=0|o,s=0|r,o=0|n;const T=ai.add3L(A,k,R);r=ai.add3H(T,S,_,I),n=0|T}({h:r,l:n}=ai.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:s,l:o}=ai.add(0|this.Bh,0|this.Bl,0|s,0|o)),({h:i,l:a}=ai.add(0|this.Ch,0|this.Cl,0|i,0|a)),({h:c,l}=ai.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=ai.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=ai.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=ai.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:y,l:m}=ai.add(0|this.Hh,0|this.Hl,0|y,0|m)),this.set(r,n,s,o,i,a,c,l,u,h,d,p,f,g,y,m)}roundClean(){ui.fill(0),hi.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const pi=$r((()=>new di)),fi=BigInt(0),gi=BigInt(1),yi=BigInt(2);function mi(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function bi(e){if(!mi(e))throw new Error("Uint8Array expected")}function wi(e,t){if("boolean"!=typeof t)throw new Error(`${e} must be valid boolean, got "${t}".`)}const vi=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Ei(e){bi(e);let t="";for(let r=0;r=_i._0&&e<=_i._9?e-_i._0:e>=_i._A&&e<=_i._F?e-(_i._A-10):e>=_i._a&&e<=_i._f?e-(_i._a-10):void 0}function Ii(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);const t=e.length,r=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,s=0;t"bigint"==typeof e&&fi<=e;function Li(e,t,r){return Oi(e)&&Oi(t)&&Oi(r)&&t<=e&&efi;e>>=gi,t+=1);return t}const Ui=e=>(yi<new Uint8Array(e),Fi=e=>Uint8Array.from(e);function $i(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");let n=Mi(e),s=Mi(e),o=0;const i=()=>{n.fill(1),s.fill(0),o=0},a=(...e)=>r(s,n,...e),c=(e=Mi())=>{s=a(Fi([0]),e),n=a(),0!==e.length&&(s=a(Fi([1]),e),n=a())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(i(),c(e);!(r=t(l()));)c();return i(),r}}const Hi={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||mi(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function qi(e,t,r={}){const n=(t,r,n)=>{const s=Hi[r];if("function"!=typeof s)throw new Error(`Invalid validator "${r}", expected function`);const o=e[t];if(!(n&&void 0===o||s(o,e)))throw new Error(`Invalid param ${String(t)}=${o} (${typeof o}), expected ${r}`)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function Vi(e){const t=new WeakMap;return(r,...n)=>{const s=t.get(r);if(void 0!==s)return s;const o=e(r,...n);return t.set(r,o),o}}const ji=BigInt(0),Ki=BigInt(1),zi=BigInt(2),Gi=BigInt(3),Wi=BigInt(4),Yi=BigInt(5),Ji=BigInt(8);function Xi(e,t){const r=e%t;return r>=ji?r:t+r}function Qi(e,t,r){if(r<=ji||t 0");if(r===Ki)return ji;let n=Ki;for(;t>ji;)t&Ki&&(n=n*e%r),e=e*e%r,t>>=Ki;return n}function Zi(e,t,r){let n=e;for(;t-- >ji;)n*=n,n%=r;return n}function ea(e,t){if(e===ji||t<=ji)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Xi(e,t),n=t,s=ji,o=Ki,i=Ki,a=ji;for(;r!==ji;){const e=n/r,t=n%r,c=s-i*e,l=o-a*e;n=r,r=t,s=i,o=a,i=c,a=l}if(n!==Ki)throw new Error("invert: does not exist");return Xi(s,t)}BigInt(9),BigInt(16);const ta=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ra(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function na(e,t,r=!1,n={}){if(e<=ji)throw new Error(`Expected Field ORDER > 0, got ${e}`);const{nBitLength:s,nByteLength:o}=ra(e,t);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const i=function(e){if(e%Wi===Gi){const t=(e+Ki)/Wi;return function(e,r){const n=e.pow(r,t);if(!e.eql(e.sqr(n),r))throw new Error("Cannot find square root");return n}}if(e%Ji===Yi){const t=(e-Yi)/Ji;return function(e,r){const n=e.mul(r,zi),s=e.pow(n,t),o=e.mul(r,s),i=e.mul(e.mul(o,zi),s),a=e.mul(o,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-Ki)/zi;let r,n,s;for(r=e-Ki,n=0;r%zi===ji;r/=zi,n++);for(s=zi;sXi(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("Invalid field element: expected bigint, got "+typeof t);return ji<=t&&te===ji,isOdd:e=>(e&Ki)===Ki,neg:t=>Xi(-t,e),eql:(e,t)=>e===t,sqr:t=>Xi(t*t,e),add:(t,r)=>Xi(t+r,e),sub:(t,r)=>Xi(t-r,e),mul:(t,r)=>Xi(t*r,e),pow:(e,t)=>function(e,t,r){if(r 0");if(r===ji)return e.ONE;if(r===Ki)return t;let n=e.ONE,s=t;for(;r>ji;)r&Ki&&(n=e.mul(n,s)),s=e.sqr(s),r>>=Ki;return n}(a,e,t),div:(t,r)=>Xi(t*ea(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ea(t,e),sqrt:n.sqrt||(e=>i(a,e)),invertBatch:e=>function(e,t){const r=new Array(t.length),n=t.reduce(((t,n,s)=>e.is0(n)?t:(r[s]=t,e.mul(t,n))),e.ONE),s=e.inv(n);return t.reduceRight(((t,n,s)=>e.is0(n)?t:(r[s]=e.mul(t,r[s]),e.mul(t,n))),s),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?Ni(e,o):Ci(e,o),fromBytes:e=>{if(e.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${e.length}`);return r?Ti(e):Ri(e)}});return Object.freeze(a)}function sa(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function oa(e){const t=sa(e);return t+Math.ceil(t/2)}const ia=BigInt(0),aa=BigInt(1),ca=new WeakMap,la=new WeakMap;function ua(e,t){const r=(e,t)=>{const r=t.negate();return e?r:t},n=e=>{if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error(`Wrong window size=${e}, should be [1..${t}]`)},s=e=>(n(e),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)});return{constTimeNegate:r,unsafeLadder(t,r){let n=e.ZERO,s=t;for(;r>ia;)r&aa&&(n=n.add(s)),s=s.double(),r>>=aa;return n},precomputeWindow(e,t){const{windows:r,windowSize:n}=s(t),o=[];let i=e,a=i;for(let e=0;e>=d,s>a&&(s-=h,o+=aa);const i=t,p=t+Math.abs(s)-1,f=e%2!=0,g=s<0;0===s?l=l.add(r(f,n[i])):c=c.add(r(g,n[p]))}return{p:c,f:l}},wNAFCached(e,t,r){const n=la.get(e)||1;let s=ca.get(e);return s||(s=this.precomputeWindow(e,n),1!==n&&ca.set(e,r(s))),this.wNAF(n,s,t)},setWindowSize(e,t){n(t),la.set(e,t),ca.delete(e)}}}function ha(e,t,r,n){if(!Array.isArray(r)||!Array.isArray(n)||n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");n.forEach(((e,r)=>{if(!t.isValid(e))throw new Error(`wrong scalar at index ${r}`)})),r.forEach(((t,r)=>{if(!(t instanceof e))throw new Error(`wrong point at index ${r}`)}));const s=Bi(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,i=(1<=0;t-=o){a.fill(e.ZERO);for(let e=0;e>BigInt(t)&BigInt(i));a[o]=a[o].add(r[e])}let s=e.ZERO;for(let t=a.length-1,r=e.ZERO;t>0;t--)r=r.add(a[t]),s=s.add(r);if(l=l.add(s),0!==t)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});qi(e,t)}(e.Fp),qi(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ra(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const pa=BigInt(0),fa=BigInt(1),ga=BigInt(2),ya=BigInt(8),ma={zip215:!0};const ba=BigInt(0),wa=BigInt(1);const va=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ea=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Sa=(BigInt(0),BigInt(1)),Aa=BigInt(2),_a=BigInt(3),ka=BigInt(5),Ia=BigInt(8);function Ra(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),s=BigInt(80),o=va,i=e*e%o*e%o,a=Zi(i,Aa,o)*i%o,c=Zi(a,Sa,o)*e%o,l=Zi(c,ka,o)*c%o,u=Zi(l,t,o)*l%o,h=Zi(u,r,o)*u%o,d=Zi(h,n,o)*h%o,p=Zi(d,s,o)*d%o,f=Zi(p,s,o)*d%o,g=Zi(f,t,o)*l%o;return{pow_p_5_8:Zi(g,Aa,o)*e%o,b2:i}}function Ta(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Ca(e,t){const r=va,n=Xi(t*t*t,r),s=Xi(n*n*t,r);let o=Xi(e*n*Ra(e*s).pow_p_5_8,r);const i=Xi(t*o*o,r),a=o,c=Xi(o*Ea,r),l=i===e,u=i===Xi(-e,r),h=i===Xi(-e*Ea,r);return l&&(o=a),(u||h)&&(o=c),(Xi(o,r)&Ki)===Ki&&(o=Xi(-o,r)),{isValid:l||u,value:o}}const Na=(()=>na(va,void 0,!0))(),xa=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Na,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ia,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:pi,randomBytes:Hr,adjustScalarBytes:Ta,uvRatio:Ca}))(),Pa=(()=>function(e){const t=function(e){const t=da(e);return qi(e,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}(e),{Fp:r,n,prehash:s,hash:o,randomBytes:i,nByteLength:a,h:c}=t,l=ga<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:pa}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,r)=>{if(wi("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Di("coordinate "+e,t,pa,l)}function y(e){if(!(e instanceof w))throw new Error("ExtendedPoint expected")}const m=Vi(((e,t)=>{const{ex:n,ey:s,ez:o}=e,i=e.is0();null==t&&(t=i?ya:r.inv(o));const a=u(n*t),c=u(s*t),l=u(o*t);if(i)return{x:pa,y:fa};if(l!==fa)throw new Error("invZ was invalid");return{x:a,y:c}})),b=Vi((e=>{const{a:r,d:n}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:s,ey:o,ez:i,et:a}=e,c=u(s*s),l=u(o*o),h=u(i*i),d=u(h*h),p=u(c*r);if(u(h*u(p+l))!==u(d+u(n*u(c*l))))throw new Error("bad point: equation left != right (1)");if(u(s*o)!==u(i*a))throw new Error("bad point: equation left != right (2)");return!0}));class w{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,g("x",e),g("y",t),g("z",r),g("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof w)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return g("x",t),g("y",r),new w(t,r,fa,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(w.fromAffine)}static msm(e,t){return ha(w,h,e,t)}_setWindowSize(e){S.setWindowSize(this,e)}assertValidity(){b(this)}equals(e){y(e);const{ex:t,ey:r,ez:n}=this,{ex:s,ey:o,ez:i}=e,a=u(t*i),c=u(s*n),l=u(r*i),h=u(o*n);return a===c&&l===h}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:s}=this,o=u(r*r),i=u(n*n),a=u(ga*u(s*s)),c=u(e*o),l=r+n,h=u(u(l*l)-o-i),d=c+i,p=d-a,f=c-i,g=u(h*p),y=u(d*f),m=u(h*f),b=u(p*d);return new w(g,y,b,m)}add(e){y(e);const{a:r,d:n}=t,{ex:s,ey:o,ez:i,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((o-s)*(l+c)),t=u((o+s)*(l-c)),r=u(t-e);if(r===pa)return this.double();const n=u(i*ga*d),p=u(a*ga*h),f=p+n,g=t+e,y=p-n,m=u(f*r),b=u(g*y),v=u(f*y),E=u(r*g);return new w(m,b,E,v)}const p=u(s*c),f=u(o*l),g=u(a*n*d),m=u(i*h),b=u((s+o)*(c+l)-p-f),v=m-g,E=m+g,S=u(f-r*p),A=u(b*v),_=u(E*S),k=u(b*S),I=u(v*E);return new w(A,_,I,k)}subtract(e){return this.add(e.negate())}wNAF(e){return S.wNAFCached(this,e,w.normalizeZ)}multiply(e){const t=e;Di("scalar",t,fa,n);const{p:r,f:s}=this.wNAF(t);return w.normalizeZ([r,s])[0]}multiplyUnsafe(e){const t=e;return Di("scalar",t,pa,n),t===pa?E:this.equals(E)||t===fa?this:this.equals(v)?this.wNAF(t).p:S.unsafeLadder(this,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return S.unsafeLadder(this,n).is0()}toAffine(e){return m(this,e)}clearCofactor(){const{h:e}=t;return e===fa?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:s,a:o}=t,i=r.BYTES;e=xi("pointHex",e,i),wi("zip215",n);const a=e.slice(),c=e[i-1];a[i-1]=-129&c;const h=Ti(a),p=n?l:r.ORDER;Di("pointHex.y",h,pa,p);const f=u(h*h),g=u(f-fa),y=u(s*f-o);let{isValid:m,value:b}=d(g,y);if(!m)throw new Error("Point.fromHex: invalid y coordinate");const v=(b&fa)===fa,E=!!(128&c);if(!n&&b===pa&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(b=u(-b)),w.fromAffine({x:b,y:h})}static fromPrivateKey(e){return k(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=Ni(t,r.BYTES);return n[n.length-1]|=e&fa?128:0,n}toHex(){return Ei(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,fa,u(t.Gx*t.Gy)),w.ZERO=new w(pa,fa,fa,pa);const{BASE:v,ZERO:E}=w,S=ua(w,8*a);function A(e){return Xi(e,n)}function _(e){return A(Ti(e))}function k(e){const t=a;e=xi("private key",e,t);const r=xi("hashed private key",o(e),2*t),n=p(r.slice(0,t)),s=r.slice(t,2*t),i=_(n),c=v.multiply(i),l=c.toRawBytes();return{head:n,prefix:s,scalar:i,point:c,pointBytes:l}}function I(e=new Uint8Array,...t){const r=Pi(...t);return _(o(f(r,xi("context",e),!!s)))}const R=ma;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return k(e).pointBytes},sign:function(e,t,o={}){e=xi("message",e),s&&(e=s(e));const{prefix:i,scalar:c,pointBytes:l}=k(t),u=I(o.context,i,e),h=v.multiply(u).toRawBytes(),d=A(u+I(o.context,h,l,e)*c);return Di("signature.s",d,pa,n),xi("result",Pi(h,Ni(d,r.BYTES)),2*a)},verify:function(e,t,n,o=R){const{context:i,zip215:a}=o,c=r.BYTES;e=xi("signature",e,2*c),t=xi("message",t),void 0!==a&&wi("zip215",a),s&&(t=s(t));const l=Ti(e.slice(c,2*c));let u,h,d;try{u=w.fromHex(n,a),h=w.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=I(i,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(w.ZERO)},ExtendedPoint:w,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(r.BYTES),precompute:(e=8,t=w.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(xa))(),Oa=(()=>function(e){const t=(qi(r=e,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r}));var r;const{P:n}=t,s=e=>Xi(e,n),o=t.montgomeryBits,i=Math.ceil(o/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>Qi(e,n-BigInt(2),n));function u(e,t,r){const n=s(e*(t-r));return[t=s(t-n),r=s(r+n)]}const h=(t.a-BigInt(2))/BigInt(4);function d(e){return Ni(s(e),i)}function p(e,t){const r=function(e){const t=xi("u coordinate",e,i);return 32===a&&(t[31]&=127),Ti(t)}(t),p=function(e){const t=xi("scalar",e),r=t.length;if(r!==i&&r!==a)throw new Error(`Expected ${i} or ${a} bytes, got ${r}`);return Ti(c(t))}(e),f=function(e,t){Di("u",e,ba,n),Di("scalar",t,ba,n);const r=t,i=e;let a,c=wa,d=ba,p=e,f=wa,g=ba;for(let e=BigInt(o-1);e>=ba;e--){const t=r>>e&wa;g^=t,a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1],g=t;const n=c+d,o=s(n*n),l=c-d,y=s(l*l),m=o-y,b=p+f,w=s((p-f)*n),v=s(b*l),E=w+v,S=w-v;p=s(E*E),f=s(i*s(S*S)),c=s(o*y),d=s(m*(o+s(h*m)))}a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1];const y=l(d);return s(c*y)}(r,p);if(f===ba)throw new Error("Invalid private or public key received");return d(f)}const f=d(t.Gu);function g(e){return p(e,f)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:f}}({P:va,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=va,{pow_p_5_8:r,b2:n}=Ra(e);return Xi(Zi(r,_a,t)*n,t)},adjustScalarBytes:Ta,randomBytes:Hr}))(),La=32,Da=64,Ba=32;function Ua(e,t){const r=new Uint8Array(Da);for(let n=0;nSr(qa)}(Ha||(Ha={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ha.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Ha.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Va||(Va={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Ha.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.Type=Ha.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(ja||(ja={}));class Ka{_key;constructor(e){this._key=Xa(e,La)}verify(e,t){return function(e,t,r){return Pa.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this._key,t,e)}marshal(){return this._key}get bytes(){return Va.encode({Type:Ha.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}}class za{_key;_publicKey;constructor(e,t){this._key=Xa(e,Da),this._publicKey=Xa(t,La)}sign(e){return function(e,t){const r=e.subarray(0,Ba);return Pa.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this._key,e)}get public(){return new Ka(this._publicKey)}marshal(){return this._key}get bytes(){return ja.encode({Type:Ha.Ed25519,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}async hash(){const e=gt.digest(this.bytes);let t;return ri(e)?({bytes:t}=await e):t=e.bytes,t}async id(){const e=ht.digest(this.public.bytes);return ke.encode(e.bytes).substring(1)}async export(e,t="libp2p-key"){if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Ga(e){if(e.length>Da){const t=(e=Xa(e,Da+La)).subarray(0,Da),r=e.subarray(Da,e.length);return new za(t,r)}const t=(e=Xa(e,Da)).subarray(0,Da),r=e.subarray(La);return new za(t,r)}function Wa(e){return e=Xa(e,La),new Ka(e)}async function Ya(){const{privateKey:e,publicKey:t}=function(){const e=Pa.utils.randomPrivateKey(),t=Pa.getPublicKey(e);return{privateKey:Ua(e,t),publicKey:t}}();return new za(e,t)}async function Ja(e){const{privateKey:t,publicKey:r}=function(e){if(e.length!==Ba)throw new TypeError('"seed" must be 32 bytes in length.');if(!(e instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');const t=e,r=Pa.getPublicKey(t);return{privateKey:Ua(t,r),publicKey:r}}(e);return new za(t,r)}function Xa(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Zo(`Key must be a Uint8Array of length ${t}, got ${e.length}`,"ERR_INVALID_KEY_TYPE");return e}async function Qa(e){const t=[await Ma.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await ec(e)],r=await Za({privateKey:t[0],publicKey:t[1]});return{privateKey:r[0],publicKey:r[1]}}async function Za(e){if(null==e.privateKey||null==e.publicKey)throw new Zo("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Ma.get().subtle.exportKey("jwk",e.privateKey),Ma.get().subtle.exportKey("jwk",e.publicKey)])}async function ec(e){return Ma.get().subtle.importKey("jwk",{kty:e.kty,n:e.n,e:e.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function tc(e){if("RSA"!==e.kty)throw new Zo("invalid key type","ERR_INVALID_KEY_TYPE");if(null==e.n)throw new Zo("invalid key modulus","ERR_INVALID_KEY_MODULUS");return 8*Nt(e.n,"base64url").length}class rc extends Mr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Nr(e);const r=Ur(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew rc(e,t).update(r).digest();nc.create=(e,t)=>new rc(e,t);var sc=__webpack_require__(152);function oc(e,t){let r=0;if(1===e.length)return e[0];for(let n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function ic(e,t,r=-1){const n=r;let s=e,o=0,i=Math.pow(2,t);for(let r=1;r<8;r++){if(e=0;e--){const r=Math.pow(2,e*t);i[o-e-1]=Math.floor(s/r),s-=i[o-e-1]*r}return e}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function ac(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),s=new Uint8Array(n);for(const t of e)s.set(t,r),r+=t.length;return s}function cc(){const e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){const t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}const t=new ArrayBuffer(this.valueHex.byteLength),r=new Uint8Array(t);for(let e=0;e=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;r8)return this.error="Too big integer",-1;if(o+1>s.length)return this.error="End of input reached before message was fully decoded",-1;const i=t+1,a=n.subarray(i,i+o);return 0===a[o-1]&&this.warnings.push("Needlessly long encoded length"),this.length=oc(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(e=!1){let t,r;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return t=new ArrayBuffer(1),!1===e&&(r=new Uint8Array(t),r[0]=128),t;if(this.longFormUsed){const n=ic(this.length,8);if(n.byteLength>127)return this.error="Too big length",yc;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const s=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e=37&&!1===s.idBlock.isHexOnly)return s.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:s};switch(s.idBlock.tagNumber){case 0:if(s.idBlock.isConstructed&&s.lenBlock.length>0)return s.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:s};a=Ic.EndOfContent;break;case 1:a=Ic.Boolean;break;case 2:a=Ic.Integer;break;case 3:a=Ic.BitString;break;case 4:a=Ic.OctetString;break;case 5:a=Ic.Null;break;case 6:a=Ic.ObjectIdentifier;break;case 10:a=Ic.Enumerated;break;case 12:a=Ic.Utf8String;break;case 13:a=Ic.RelativeObjectIdentifier;break;case 14:a=Ic.TIME;break;case 15:return s.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:s};case 16:a=Ic.Sequence;break;case 17:a=Ic.Set;break;case 18:a=Ic.NumericString;break;case 19:a=Ic.PrintableString;break;case 20:a=Ic.TeletexString;break;case 21:a=Ic.VideotexString;break;case 22:a=Ic.IA5String;break;case 23:a=Ic.UTCTime;break;case 24:a=Ic.GeneralizedTime;break;case 25:a=Ic.GraphicString;break;case 26:a=Ic.VisibleString;break;case 27:a=Ic.GeneralString;break;case 28:a=Ic.UniversalString;break;case 29:a=Ic.CharacterString;break;case 30:a=Ic.BmpString;break;case 31:a=Ic.DATE;break;case 32:a=Ic.TimeOfDay;break;case 33:a=Ic.DateTime;break;case 34:a=Ic.Duration;break;default:{const e=s.idBlock.isConstructed?new Ic.Constructed:new Ic.Primitive;e.idBlock=s.idBlock,e.lenBlock=s.lenBlock,e.warnings=s.warnings,s=e}}}else a=s.idBlock.isConstructed?Ic.Constructed:Ic.Primitive;return s=function(e,t){if(e instanceof t)return e;const r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(s,a),i=s.fromBER(e,t,s.lenBlock.isIndefiniteForm?r:s.lenBlock.length),s.valueBeforeDecodeView=e.subarray(n,n+s.blockLength),{offset:i,result:s}}function dl(e){if(!e.byteLength){const e=new Rc({},Ac);return e.error="Input buffer has zero length",{offset:-1,result:e}}return hl(sc._H.toUint8Array(e).slice(),0,e.byteLength)}xc=ul,Ic.Primitive=xc,ul.NAME="PRIMITIVE";class pl extends Ac{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=sc._H.toUint8Array(e);if(!dc(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;let s=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=hl(n,s,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===bc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===bc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,t){const r=t||new pc;for(let t=0;t` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Pc=fl,Ic.Constructed=Pc,fl.NAME="CONSTRUCTED";class gl extends Ac{fromBER(e,t,r){return t}toBER(e){return yc}}gl.override="EndOfContentValueBlock";class yl extends Rc{constructor(e={}){super(e,gl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Oc=yl,Ic.EndOfContent=Oc,yl.NAME=bc;class ml extends Rc{constructor(e={}){super(e,Ac),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){const r=new ArrayBuffer(2);if(!e){const e=new Uint8Array(r);e[0]=5,e[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return`${this.constructor.NAME}`}}Lc=ml,Ic.Null=Lc,ml.NAME="NULL";class bl extends(Ec(Ac)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=sc._H.toUint8Array(t.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}get value(){for(const e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}fromBER(e,t,r){const n=sc._H.toUint8Array(e);return dc(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,cc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}bl.NAME="BooleanValueBlock";class wl extends Rc{constructor(e={}){super(e,bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}Dc=wl,Ic.Boolean=Dc,wl.NAME="BOOLEAN";class vl extends(Ec(pl)){constructor({isConstructed:e=!1,...t}={}){super(t),this.isConstructed=e}fromBER(e,t,r){let n=0;if(this.isConstructed){if(this.isHexOnly=!1,n=pl.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e0&&r.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=r.unusedBits}return n}const s=sc._H.toUint8Array(e);if(!dc(this,s,t,r))return-1;const o=s.subarray(t,t+r);if(this.unusedBits=o[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=o.subarray(1);try{if(e.byteLength){const t=hl(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=o.subarray(1),this.blockLength=o.length,t+r}toBER(e,t){if(this.isConstructed)return pl.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return yc;const r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Sl.NAME="BitStringValueBlock";class Al extends Rc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,s;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(s=r.value)||void 0===s?void 0:s.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Sl),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return fl.prototype.onAsciiEncoding.call(this);{const e=[],t=this.valueBlock.valueHexView;for(const r of t)e.push(r.toString(2).padStart(8,"0"));const r=e.join("");return`${this.constructor.NAME} : ${r.substring(0,r.length-this.valueBlock.unusedBits)}`}}}function _l(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),s=new Uint8Array(t);let o=n.slice(0);const i=o.length-1,a=s.slice(0),c=a.length-1;let l=0,u=0;for(let e=c=0;e--,u++)l=1==u=o.length?o=ac(new Uint8Array([l%10]),o):o[i-u]=l%10;return r[0]>0&&(o=ac(r,o)),o}function kl(e){if(e>=fc.length)for(let t=fc.length;t<=e;t++){const e=new Uint8Array([0]);let r=fc[t-1].slice(0);for(let t=r.length-1;t>=0;t--){const n=new Uint8Array([(r[t]<<1)+e[0]]);e[0]=n[0]/10,r[t]=n[0]%10}e[0]>0&&(r=ac(e,r)),fc.push(r)}return fc[e]}function Il(e,t){let r=0;const n=new Uint8Array(e),s=new Uint8Array(t),o=n.slice(0),i=o.length-1,a=s.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=o[i-u]-a[c-u]-r,1==l<0?(r=1,o[i-u]=l+10):(r=0,o[i-u]=l);if(r>0)for(let e=i-c+1;e>=0;e--,u++){if(l=o[i-u]-r,!(l<0)){r=0,o[i-u]=l;break}r=1,o[i-u]=l+10}return o.slice()}Uc=Al,Ic.BitString=Uc,Al.NAME=vc;class Rl extends(Ec(Ac)){constructor({value:e,...t}={}){super(t),this._valueDec=0,t.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=cc.call(this)))}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){const t=e<0?-1*e:e;let r=128;for(let n=1;n<8;n++){if(t<=r){if(e<0){const e=ic(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let s=ic(t,8,n),o=new Uint8Array(s);if(128&o[0]){const e=s.slice(0),t=new Uint8Array(e);s=new ArrayBuffer(s.byteLength+1),o=new Uint8Array(s);for(let r=0;r1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),s}toDER(e=!1){const t=this.valueHexView;switch(!0){case!!(128&t[0]):{const e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(t,1),this.valueHexView=e}break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){const n=super.fromBER(e,t,r);return-1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){const e=8*this.valueHexView.length-1;let t,r=new Uint8Array(8*this.valueHexView.length/3),n=0;const s=this.valueHexView;let o="",i=!1;for(let i=s.byteLength-1;i>=0;i--){t=s[i];for(let s=0;s<8;s++)1&~t||(n===e?(r=Il(kl(n),r),o="-"):r=_l(r,kl(n))),n++,t>>=1}for(let e=0;e0;){const t=new Nl;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;0===this.value.length&&(t.isFirstSid=!0),this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e){const t=[];for(let r=0;rNumber.MAX_SAFE_INTEGER){uc();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,s=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r0;){const t=new Ol;if(n=t.fromBER(e,n,r),-1===n)return this.blockLength=0,this.error=t.error,n;this.blockLength+=t.blockLength,r-=t.blockLength,this.value.push(t)}return n}toBER(e,t){const r=[];for(let t=0;t4)continue;const o=4-s.length;for(let e=s.length-1;e>=0;e--)r[4*n+e+o]=s[e]}this.valueBlock.value=e}}Kl.NAME="UniversalStringValueBlock";class zl extends Kl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Gc=zl,Ic.UniversalString=Gc,zl.NAME="UniversalString";class Gl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Wc=Gl,Ic.NumericString=Wc,Gl.NAME="NumericString";class Wl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Yc=Wl,Ic.PrintableString=Yc,Wl.NAME="PrintableString";class Yl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}Jc=Yl,Ic.TeletexString=Jc,Yl.NAME="TeletexString";class Jl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}Xc=Jl,Ic.VideotexString=Xc,Jl.NAME="VideotexString";class Xl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}Qc=Xl,Ic.IA5String=Qc,Xl.NAME="IA5String";class Ql extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}Zc=Ql,Ic.GraphicString=Zc,Ql.NAME="GraphicString";class Zl extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}el=Zl,Ic.VisibleString=el,Zl.NAME="VisibleString";class eu extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}tl=eu,Ic.GeneralString=tl,eu.NAME="GeneralString";class tu extends $l{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}rl=tu,Ic.CharacterString=rl,tu.NAME="CharacterString";class ru extends Zl{constructor({value:e,valueDate:t,...r}={}){if(super(r),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let t=0;t=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}toString(e="iso"){if("iso"===e){const e=new Array(7);return e[0]=lc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=lc(this.month,2),e[2]=lc(this.day,2),e[3]=lc(this.hour,2),e[4]=lc(this.minute,2),e[5]=lc(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}nl=ru,Ic.UTCTime=nl,ru.NAME="UTCTime";class nu extends ru{constructor(e={}){var t;super(e),null!==(t=this.millisecond)&&void 0!==t||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let t,r=!1,n="",s="",o=0,i=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=n.indexOf("+"),r="";if(-1===t&&(t=n.indexOf("-"),e=-1),-1!==t){if(r=n.substring(t+1),n=n.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let s=parseInt(r.substring(0,2),10);if(isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");if(i=e*s,4===r.length){if(s=parseInt(r.substring(2,4),10),isNaN(s.valueOf()))throw new Error("Wrong input string for conversion");a=e*s}}}let c=n.indexOf(".");if(-1===c&&(c=n.indexOf(",")),-1!==c){const e=new Number(`0${n.substring(c)}`);if(isNaN(e.valueOf()))throw new Error("Wrong input string for conversion");o=e.valueOf(),s=n.substring(0,c)}else s=n;switch(!0){case 8===s.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*o;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*o;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===s.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*o;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(s);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e0&&(t=`0${t}`);const r=t.length/2,n=new Uint8Array(r);let s=0,o=0;for(;s0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}ll=cu,Ic.TIME=ll,cu.NAME="TIME";async function du(e,t){const r=Ma.get(),n=new Bl({value:[new Tl({value:0}),new Bl({value:[new Pl({value:"1.2.840.113549.1.1.1"}),new ml]}),new El({valueHex:e.marshal()})]}).toBER(),s=new Uint8Array(n,0,n.byteLength),o=lu(16),i=await async function(e,t,r,n){const{c:s,dkLen:o,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=function(e,t,r,n){Nr(e);const s=function(e,t){if(void 0!==t&&"[object Object]"!==Fr.call(t))throw new Error("Options should be object or undefined");return Object.assign({dkLen:32,asyncTick:10},t)}(0,n),{c:o,dkLen:i,asyncTick:a}=s;if(Tr(o),Tr(i),Tr(a),o<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const c=Ur(t),l=Ur(r),u=new Uint8Array(i),h=nc.create(e,c),d=h._cloneInto().update(l);return{c:o,dkLen:i,asyncTick:a,DK:u,PRF:h,PRFSalt:d}}(e,t,r,n);let u;const h=new Uint8Array(4),d=Or(h),p=new Uint8Array(c.outputLen);for(let e=1,t=0;t{c._cloneInto(u).update(p).digestInto(p);for(let e=0;ee)):e.bytes}}class gu{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t}genSecret(){return lu(16)}sign(e){return async function(e,t){const r=await Ma.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ma.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}(this._key,e)}get public(){if(null==this._publicKey)throw new Zo("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new fu(this._publicKey)}marshal(){return function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new Zo("JWK was missing components","ERR_INVALID_PARAMETERS");const t=new Bl({value:[new Tl({value:0}),Tl.fromBigInt(hu(Nt(e.n,"base64url"))),Tl.fromBigInt(hu(Nt(e.e,"base64url"))),Tl.fromBigInt(hu(Nt(e.d,"base64url"))),Tl.fromBigInt(hu(Nt(e.p,"base64url"))),Tl.fromBigInt(hu(Nt(e.q,"base64url"))),Tl.fromBigInt(hu(Nt(e.dp,"base64url"))),Tl.fromBigInt(hu(Nt(e.dq,"base64url"))),Tl.fromBigInt(hu(Nt(e.qi,"base64url")))]}).toBER();return new Uint8Array(t,0,t.byteLength)}(this._key)}get bytes(){return ja.encode({Type:Ha.RSA,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return nn(await this.public.hash(),"base58btc")}async export(e,t="pkcs-8"){if("pkcs-8"===t)return du(this,e);if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}async function yu(e){const t=function(e){const{result:t}=dl(e),r=t.valueBlock.value;return{n:nn(uu(r[1].toBigInt()),"base64url"),e:nn(uu(r[2].toBigInt()),"base64url"),d:nn(uu(r[3].toBigInt()),"base64url"),p:nn(uu(r[4].toBigInt()),"base64url"),q:nn(uu(r[5].toBigInt()),"base64url"),dp:nn(uu(r[6].toBigInt()),"base64url"),dq:nn(uu(r[7].toBigInt()),"base64url"),qi:nn(uu(r[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}(e);if(tc(t)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const r=await Qa(t);return new gu(r.privateKey,r.publicKey)}function mu(e){const t=function(e){const{result:t}=dl(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:nn(uu(r[0].toBigInt()),"base64url"),e:nn(uu(r[1].toBigInt()),"base64url")}}(e);if(tc(t)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new fu(t)}async function bu(e){if(tc(e)>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await Qa(e);return new gu(t.privateKey,t.publicKey)}async function wu(e){if(e>pu)throw new Zo("key size is too large","ERR_KEY_SIZE_TOO_LARGE");const t=await async function(e){const t=await Ma.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=await Za(t);return{privateKey:r[0],publicKey:r[1]}}(e);return new gu(t.privateKey,t.publicKey)}function vu(e){void 0!==e.lowS&&wi("lowS",e.lowS),void 0!==e.prehash&&wi("prehash",e.prehash)}const{Ph:Eu,aT:Su}=f,Au={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(e,t)=>{const{Err:r}=Au;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,s=Si(n);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const o=n>127?Si(s.length/2|128):"";return`${Si(e)}${o}${s}${t}`},decode(e,t){const{Err:r}=Au;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const s=t[n++];let o=0;if(128&s){const e=127&s;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(n,n+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)o=o<<8|e;if(n+=e,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=s;const i=t.subarray(n,n+o);if(i.length!==o)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(n+o)}}},_int:{encode(e){const{Err:t}=Au;if(e<_u)throw new t("integer: negative integers are not allowed");let r=Si(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected assertion");return r},decode(e){const{Err:t}=Au;if(128&e[0])throw new t("Invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("Invalid signature integer: unnecessary leading zero");return Eu(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Au,s="string"==typeof e?Su(e):e;bi(s);const{v:o,l:i}=n.decode(48,s);if(i.length)throw new t("Invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Au,n=`${t.encode(2,r.encode(e.r))}${t.encode(2,r.encode(e.s))}`;return t.encode(48,n)}},_u=BigInt(0),ku=BigInt(1),Iu=(BigInt(2),BigInt(3));function Ru(e){const t=function(e){const t=da(e);return qi(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,s=r.BYTES+1,o=2*r.BYTES+1;function i(e){return Xi(e,n)}function a(e){return ea(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=da(e);qi(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:s}=t;if(r){if(!n.eql(s,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof r||"bigint"!=typeof r.beta||"function"!=typeof r.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=na(t.n,t.nBitLength),s=t.toBytes||((e,t,n)=>{const s=t.toAffine();return Pi(Uint8Array.from([4]),r.toBytes(s.x),r.toBytes(s.y))}),o=t.fromBytes||(e=>{const t=e.subarray(1);return{x:r.fromBytes(t.subarray(0,r.BYTES)),y:r.fromBytes(t.subarray(r.BYTES,2*r.BYTES))}});function i(e){const{a:n,b:s}=t,o=r.sqr(e),i=r.mul(o,e);return r.add(r.add(i,r.mul(e,n)),s)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:s,n:o}=t;if(r&&"bigint"!=typeof e){if(mi(e)&&(e=Ei(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("Invalid key");e=e.padStart(2*n,"0")}let i;try{i="bigint"==typeof e?e:Ri(xi("private key",e,n))}catch(t){throw new Error(`private key must be ${n} bytes, hex or bigint, not ${typeof e}`)}return s&&(i=Xi(i,o)),Di("private key",i,ku,o),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=Vi(((e,t)=>{const{px:n,py:s,pz:o}=e;if(r.eql(o,r.ONE))return{x:n,y:s};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(o));const a=r.mul(n,t),c=r.mul(s,t),l=r.mul(o,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),u=Vi((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:n,y:s}=e.toAffine();if(!r.isValid(n)||!r.isValid(s))throw new Error("bad point: x or y not FE");const o=r.sqr(s),a=i(n);if(!r.eql(o,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t))throw new Error("y required");if(null==n||!r.isValid(n))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const s=e=>r.eql(e,r.ZERO);return s(t)&&s(n)?h.ZERO:new h(t,n,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(h.fromAffine)}static fromHex(e){const t=h.fromAffine(o(xi("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return ha(h,n,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:s}=this,{px:o,py:i,pz:a}=e,l=r.eql(r.mul(t,a),r.mul(o,s)),u=r.eql(r.mul(n,a),r.mul(i,s));return l&&u}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,s=r.mul(n,Iu),{px:o,py:i,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(o,o),p=r.mul(i,i),f=r.mul(a,a),g=r.mul(o,i);return g=r.add(g,g),u=r.mul(o,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(s,f),l=r.add(c,l),c=r.sub(p,l),l=r.add(p,l),l=r.mul(c,l),c=r.mul(g,c),u=r.mul(s,u),f=r.mul(e,f),g=r.sub(d,f),g=r.mul(e,g),g=r.add(g,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,g),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){c(e);const{px:n,py:s,pz:o}=this,{px:i,py:a,pz:l}=e;let u=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Iu);let y=r.mul(n,i),m=r.mul(s,a),b=r.mul(o,l),w=r.add(n,s),v=r.add(i,a);w=r.mul(w,v),v=r.add(y,m),w=r.sub(w,v),v=r.add(n,o);let E=r.add(i,l);return v=r.mul(v,E),E=r.add(y,b),v=r.sub(v,E),E=r.add(s,o),u=r.add(a,l),E=r.mul(E,u),u=r.add(m,b),E=r.sub(E,u),p=r.mul(f,v),u=r.mul(g,b),p=r.add(u,p),u=r.sub(m,p),p=r.add(m,p),d=r.mul(u,p),m=r.add(y,y),m=r.add(m,y),b=r.mul(f,b),v=r.mul(g,v),m=r.add(m,b),b=r.sub(y,b),b=r.mul(f,b),v=r.add(v,b),y=r.mul(m,v),d=r.add(d,y),y=r.mul(E,v),u=r.mul(w,u),u=r.sub(u,y),y=r.mul(w,m),p=r.mul(E,p),p=r.add(p,y),new h(u,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){Di("scalar",e,_u,t.n);const n=h.ZERO;if(e===_u)return n;if(e===ku)return this;const{endo:s}=t;if(!s)return p.unsafeLadder(this,e);let{k1neg:o,k1:i,k2neg:a,k2:c}=s.splitScalar(e),l=n,u=n,d=this;for(;i>_u||c>_u;)i&ku&&(l=l.add(d)),c&ku&&(u=u.add(d)),d=d.double(),i>>=ku,c>>=ku;return o&&(l=l.negate()),a&&(u=u.negate()),u=new h(r.mul(u.px,s.beta),u.py,u.pz),l.add(u)}multiply(e){const{endo:n,n:s}=t;let o,i;if(Di("scalar",e,ku,s),n){const{k1neg:t,k1:s,k2neg:a,k2:c}=n.splitScalar(e);let{p:l,f:u}=this.wNAF(s),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(t,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,n.beta),d.py,d.pz),o=l.add(d),i=u.add(f)}else{const{p:t,f:r}=this.wNAF(e);o=t,i=r}return h.normalizeZ([o,i])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,s=(e,t)=>t!==_u&&t!==ku&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),o=s(this,t).add(s(e,r));return o.is0()?void 0:o}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===ku)return!0;if(r)return r(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:e,clearCofactor:r}=t;return e===ku?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return wi("isCompressed",e),this.assertValidity(),s(h,this,e)}toHex(e=!0){return wi("isCompressed",e),Ei(this.toRawBytes(e))}}h.BASE=new h(t.Gx,t.Gy,r.ONE),h.ZERO=new h(r.ZERO,r.ONE,r.ZERO);const d=t.nBitLength,p=ua(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:function(e){return Li(e,ku,t.n)}}}({...t,toBytes(e,t,n){const s=t.toAffine(),o=r.toBytes(s.x),i=Pi;return wi("isCompressed",n),n?i(Uint8Array.from([t.hasEvenY()?2:3]),o):i(Uint8Array.from([4]),o,r.toBytes(s.y))},fromBytes(e){const t=e.length,n=e[0],i=e.subarray(1);if(t!==s||2!==n&&3!==n){if(t===o&&4===n)return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))};throw new Error(`Point of length ${t} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}{const e=Ri(i);if(!Li(e,ku,r.ORDER))throw new Error("Point is not on curve");const t=u(e);let s;try{s=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~n)!=((s&ku)===ku)&&(s=r.neg(s)),{x:e,y:s}}}}),d=e=>Ei(Ci(e,t.nByteLength));function p(e){return e>n>>ku}const f=(e,t,r)=>Ri(e.slice(t,r));class g{constructor(e,t,r){this.r=e,this.s=t,this.recovery=r,this.assertValidity()}static fromCompact(e){const r=t.nByteLength;return e=xi("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Au.toSig(xi("DER",e));return new g(t,r)}assertValidity(){Di("r",this.r,ku,n),Di("s",this.s,ku,n)}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s,recovery:o}=this,l=w(xi("msgHash",e));if(null==o||![0,1,2,3].includes(o))throw new Error("recovery id invalid");const u=2===o||3===o?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&o?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=i(-l*f),y=i(s*f),m=c.BASE.multiplyAndAddUnsafe(p,g,y);if(!m)throw new Error("point at infinify");return m.assertValidity(),m}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ii(this.toDERHex())}toDERHex(){return Au.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ii(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const y={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=oa(t.n);return function(e,t,r=!1){const n=e.length,s=sa(t),o=oa(t);if(n<16||n1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);const i=Xi(r?Ri(e):Ti(e),t-Ki)+Ki;return r?Ni(i,s):Ci(i,s)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function m(e){const t=mi(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===s||n===o:r?n===2*s||n===2*o:e instanceof c}const b=t.bits2int||function(e){const r=Ri(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return i(b(e))},v=Ui(t.nBitLength);function E(e){return Di(`num < 2^${t.nBitLength}`,e,_u,v),Ci(e,t.nByteLength)}const S={lowS:t.lowS,prehash:!1},A={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(m(e))throw new Error("first arg must be private key");if(!m(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(r)},sign:function(e,n,s=S){const{seed:o,k2sig:u}=function(e,n,s=S){if(["recovered","canonical"].some((e=>e in s)))throw new Error("sign() legacy options not supported");const{hash:o,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:y}=s;null==d&&(d=!0),e=xi("msgHash",e),vu(s),f&&(e=xi("prehashed msgHash",o(e)));const m=w(e),v=l(n),A=[E(v),E(m)];if(null!=y&&!1!==y){const e=!0===y?u(r.BYTES):y;A.push(xi("extraEntropy",e))}const _=Pi(...A),k=m;return{seed:_,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),s=i(n.x);if(s===_u)return;const o=i(r*i(k+s*v));if(o===_u)return;let l=(n.x===s?0:2)|Number(n.y&ku),u=o;return d&&p(o)&&(u=function(e){return p(e)?i(-e):e}(o),l^=1),new g(s,u,l)}}}(e,n,s),d=t;return $i(d.hash.outputLen,d.nByteLength,d.hmac)(o,u)},verify:function(e,r,n,s=A){const o=e;if(r=xi("msgHash",r),n=xi("publicKey",n),"strict"in s)throw new Error("options.strict was renamed to lowS");vu(s);const{lowS:l,prehash:u}=s;let h,d;try{if("string"==typeof o||mi(o))try{h=g.fromDER(o)}catch(e){if(!(e instanceof Au.Err))throw e;h=g.fromCompact(o)}else{if("object"!=typeof o||"bigint"!=typeof o.r||"bigint"!=typeof o.s)throw new Error("PARSE");{const{r:e,s:t}=o;h=new g(e,t)}}d=c.fromHex(n)}catch(e){if("PARSE"===e.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(l&&h.hasHighS())return!1;u&&(r=t.hash(r));const{r:p,s:f}=h,y=w(r),m=a(f),b=i(y*m),v=i(p*m),E=c.BASE.multiplyAndAddUnsafe(d,b,v)?.toAffine();return!!E&&i(E.x)===p},ProjectivePoint:c,Signature:g,utils:y}}function Tu(e){return{hash:e,hmac:(t,...r)=>nc(e,t,function(...e){let t=0;for(let r=0;r(e+t/Pu)/t;const Lu=na(Cu,void 0,void 0,{sqrt:function(e){const t=Cu,r=BigInt(3),n=BigInt(6),s=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=Zi(u,r,t)*u%t,d=Zi(h,r,t)*u%t,p=Zi(d,Pu,t)*l%t,f=Zi(p,s,t)*p%t,g=Zi(f,o,t)*f%t,y=Zi(g,a,t)*g%t,m=Zi(y,c,t)*y%t,b=Zi(m,a,t)*g%t,w=Zi(b,r,t)*u%t,v=Zi(w,i,t)*f%t,E=Zi(v,n,t)*l%t,S=Zi(E,Pu,t);if(!Lu.eql(Lu.sqr(S),e))throw new Error("Cannot find square root");return S}}),Du=function(e,t){const r=t=>Ru({...e,...Tu(t)});return Object.freeze({...r(t),create:r})}({a:BigInt(0),b:BigInt(7),Fp:Lu,n:Nu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Nu,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-xu*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,i=BigInt("0x100000000000000000000000000000000"),a=Ou(o*e,t),c=Ou(-n*e,t);let l=Xi(e-a*r-c*s,t),u=Xi(-a*n-c*o,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},Wr);function Bu(e){try{Du.ProjectivePoint.fromHex(e)}catch(e){throw new Zo(String(e),"ERR_INVALID_PUBLIC_KEY")}}BigInt(0),Du.ProjectivePoint;class Uu{_key;constructor(e){Bu(e),this._key=e}verify(e,t){return function(e,t,r){const n=gt.digest(r instanceof Uint8Array?r:r.subarray());if(ri(n))return n.then((({digest:r})=>Du.verify(t,r,e))).catch((e=>{throw new Zo(String(e),"ERR_INVALID_INPUT")}));try{return Du.verify(t,n.digest,e)}catch(e){throw new Zo(String(e),"ERR_INVALID_INPUT")}}(this._key,t,e)}marshal(){return e=this._key,Du.ProjectivePoint.fromHex(e).toRawBytes(!0);var e}get bytes(){return Va.encode({Type:Ha.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}async hash(){const e=gt.digest(this.bytes);let t;return ri(e)?({bytes:t}=await e):t=e.bytes,t}}class Mu{_key;_publicKey;constructor(e,t){this._key=e,this._publicKey=t??function(e){try{return Du.getPublicKey(e,!0)}catch(e){throw new Zo(String(e),"ERR_INVALID_PRIVATE_KEY")}}(e),function(e){try{Du.getPublicKey(e,!0)}catch(e){throw new Zo(String(e),"ERR_INVALID_PRIVATE_KEY")}}(this._key),Bu(this._publicKey)}sign(e){return function(e,t){const r=gt.digest(t instanceof Uint8Array?t:t.subarray());if(ri(r))return r.then((({digest:t})=>Du.sign(t,e).toDERRawBytes())).catch((e=>{throw new Zo(String(e),"ERR_INVALID_INPUT")}));try{return Du.sign(r.digest,e).toDERRawBytes()}catch(e){throw new Zo(String(e),"ERR_INVALID_INPUT")}}(this._key,e)}get public(){return new Uu(this._publicKey)}marshal(){return this._key}get bytes(){return ja.encode({Type:Ha.Secp256k1,Data:this.marshal()}).subarray()}equals(e){return Nn(this.bytes,e.bytes)}hash(){const e=gt.digest(this.bytes);return ri(e)?e.then((({bytes:e})=>e)):e.bytes}async id(){return nn(await this.public.hash(),"base58btc")}async export(e,t="libp2p-key"){if("libp2p-key"===t)return $a(this.bytes,e);throw new Zo(`export format '${t}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}}function Fu(e){return new Mu(e)}function $u(e){return new Uu(e)}async function Hu(){const e=Du.utils.randomPrivateKey();return new Mu(e)}const qu={rsa:y,ed25519:g,secp256k1:m};function Vu(e){const t=Object.keys(qu).join(" / ");return new Zo(`invalid or unsupported key type ${e}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function ju(e){if("rsa"===(e=e.toLowerCase())||"ed25519"===e||"secp256k1"===e)return qu[e];throw Vu(e)}async function Ku(e,t,r){if("ed25519"!==e.toLowerCase())throw new Zo("Seed key derivation is unimplemented for RSA or secp256k1","ERR_UNSUPPORTED_KEY_DERIVATION_TYPE");return Ja(t)}function zu(e){const t=Va.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Ha.RSA:return qu.rsa.unmarshalRsaPublicKey(r);case Ha.Ed25519:return qu.ed25519.unmarshalEd25519PublicKey(r);case Ha.Secp256k1:return qu.secp256k1.unmarshalSecp256k1PublicKey(r);default:throw Vu(t.Type??"unknown")}}function Gu(e,t){return ju(t=(t??"rsa").toLowerCase()),e.bytes}async function Wu(e){const t=ja.decode(e),r=t.Data??new Uint8Array;switch(t.Type){case Ha.RSA:return qu.rsa.unmarshalRsaPrivateKey(r);case Ha.Ed25519:return qu.ed25519.unmarshalEd25519PrivateKey(r);case Ha.Secp256k1:return qu.secp256k1.unmarshalSecp256k1PrivateKey(r);default:throw Vu(t.Type??"RSA")}}const Yu=Symbol.for("@libp2p/service-capabilities"),Ju=Symbol.for("@libp2p/service-dependencies"),Xu=Symbol.for("nodejs.util.inspect.custom"),Qu=Object.values(kt).map((e=>e.decoder)).reduce(((e,t)=>e.or(t)),kt.identity.decoder);class Zu{type;multihash;privateKey;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,this.privateKey=e.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Vs]=!0;toString(){return null==this.string&&(this.string=ke.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return vt.createV1(114,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Nn(this.multihash.bytes,e);if("string"==typeof e)return oh(e).equals(this);if(null!=e?.multihash?.bytes)return Nn(this.multihash.bytes,e.multihash.bytes);throw new Error("not valid Id")}[Xu](){return`PeerId(${this.toString()})`}}class eh extends Zu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class th extends Zu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.multihash.digest}}class rh extends Zu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.multihash.digest}}const nh=2336;class sh{type="url";multihash;privateKey;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ht.digest(Nt(this.url))}[Xu](){return`PeerId(${this.url})`}[Vs]=!0;toString(){return this.toCID().toString()}toCID(){return vt.createV1(nh,this.multihash)}toBytes(){return this.toCID().bytes}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=nn(e)),e.toString()===this.toString())}}function oh(e,t){if(t=t??Qu,"1"===e.charAt(0)||"Q"===e.charAt(0)){const t=ct(ke.decode(`z${e}`));return e.startsWith("12D")?new th({multihash:t}):e.startsWith("16U")?new rh({multihash:t}):new eh({multihash:t})}return ih(Qu.decode(e))}function ih(e){try{const t=ct(e);if(t.code===ht.code){if(36===t.digest.length)return new th({multihash:t});if(37===t.digest.length)return new rh({multihash:t})}if(t.code===gt.code)return new eh({multihash:t})}catch{return function(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&e.code!==nh)throw new Error("Supplied PeerID CID is invalid");if(e.code===nh){const t=nn(e.multihash.digest);return new sh(new URL(t))}const t=e.multihash;if(t.code===gt.code)return new eh({multihash:e.multihash});if(t.code===ht.code){if(36===t.digest.length)return new th({multihash:e.multihash});if(37===t.digest.length)return new rh({multihash:e.multihash})}throw new Error("Supplied PeerID CID is invalid")}(vt.decode(e))}throw new Error("Supplied PeerID CID is invalid")}async function ah(e,t){return 36===e.length?new th({multihash:at(ht.code,e),privateKey:t}):37===e.length?new rh({multihash:at(ht.code,e),privateKey:t}):new eh({multihash:await gt.digest(e),publicKey:e,privateKey:t})}class ch extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}}async function lh(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new ch(r?.errorMessage,r?.errorCode,r?.errorName));let n;const s=new ch(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(s)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class uh{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=Kn(),this.haveNext=Kn()}[Symbol.asyncIterator](){return this}async next(){if(null==this.nextResult&&await this.haveNext.promise,null==this.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");const e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=Kn(),e}async throw(e){return this.ended=!0,null!=e&&(this.haveNext.promise.catch((()=>{})),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){return await this._push(void 0),{done:!0,value:void 0}}async push(e,t){await this._push(e,t)}async end(e,t){null!=e?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(null!=e&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=this.nextResult;)await this.readNext.promise;null!=e?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=Kn(),await lh(this.readNext.promise,t?.signal,t)}}class hh extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}class dh extends Error{code;constructor(e,t){super(e),this.code=t}}class ph extends dh{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}}function fh(e,t){const r=new uh;e.sink(r).catch((async e=>{await r.end(e)})),e.sink=async e=>{for await(const t of e)await r.push(t);await r.end()};let n=e.source;null!=e.source[Symbol.iterator]?n=e.source[Symbol.iterator]():null!=e.source[Symbol.asyncIterator]&&(n=e.source[Symbol.asyncIterator]());const s=new Ln,o={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const o=new Promise(((e,n)=>{r=()=>{n(new ph("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),o]);return!0===e?new Ln:t}for(;s.byteLength{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(s.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield s:yield*s,yield*r}()}return e}};return o}class gh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class yh extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mh extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function bh(e,t={}){const r=fh(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=C(t.maxDataLength));const n=t?.lengthDecoder??O,s=t?.lengthEncoder??P;return{read:async e=>{let s=-1;const o=new Ln;for(;;){o.append(await r.read(1,e));try{s=n(o)}catch(e){if(e instanceof RangeError)continue;throw e}if(s<0)throw new gh("Invalid message length");if(null!=t?.maxLengthLength&&o.byteLength>t.maxLengthLength)throw new mh("message length length too long");if(s>-1)break}if(null!=t?.maxDataLength&&s>t.maxDataLength)throw new yh("message length too long");return r.read(s,e)},write:async(e,t)=>{await r.write(new Ln(s(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new Ln(...e.flatMap((e=>[s(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function wh(){const e=Kn();let t=!1;return{sink:async r=>{if(t)throw new Error("already piped");t=!0,e.resolve(r)},source:async function*(){const t=await e.promise;yield*t}()}}const vh=65535,Eh=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Sh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Ah(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function _h(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function kh(e,...t){if(!_h(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ih(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}const Rh=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function Th(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!_h(e))throw new Error("Uint8Array expected, got "+typeof e);e=xh(e)}return e}const Ch=(e,t)=>(Object.assign(t,e),t);function Nh(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const s=BigInt(32),o=BigInt(4294967295),i=Number(r>>s&o),a=Number(r&o),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}function xh(e){return Uint8Array.from(e)}function Ph(...e){for(let t=0;tUint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Lh=Oh("expand 16-byte k"),Dh=Oh("expand 32-byte k"),Bh=Rh(Lh),Uh=Rh(Dh);function Mh(e,t){return e<>>32-t}function Fh(e){return e.byteOffset%4==0}Uh.slice();const $h=2**32-1,Hh=new Uint32Array;function qh(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:s,counterRight:o,rounds:i}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Sh(s),Sh(i),Ah(o),Ah(r),(t,a,c,l,u=0)=>{kh(t),kh(a),kh(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),kh(l),Sh(u),u<0||u>=$h)throw new Error("arx: counter overflow");if(l.length=$h)throw new Error("arx: 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;t255&e[t++]|(255&e[t++])<<8;class jh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,kh(e=Th(e),32);const t=Vh(e,0),r=Vh(e,2),n=Vh(e,4),s=Vh(e,6),o=Vh(e,8),i=Vh(e,10),a=Vh(e,12),c=Vh(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|s<<9),this.r[4]=255&(s>>>4|o<<12),this.r[5]=o>>>1&8190,this.r[6]=8191&(o>>>14|i<<2),this.r[7]=8065&(i>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Vh(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:s,r:o}=this,i=o[0],a=o[1],c=o[2],l=o[3],u=o[4],h=o[5],d=o[6],p=o[7],f=o[8],g=o[9],y=Vh(e,t+0),m=Vh(e,t+2),b=Vh(e,t+4),w=Vh(e,t+6),v=Vh(e,t+8),E=Vh(e,t+10),S=Vh(e,t+12),A=Vh(e,t+14);let _=s[0]+(8191&y),k=s[1]+(8191&(y>>>13|m<<3)),I=s[2]+(8191&(m>>>10|b<<6)),R=s[3]+(8191&(b>>>7|w<<9)),T=s[4]+(8191&(w>>>4|v<<12)),C=s[5]+(v>>>1&8191),N=s[6]+(8191&(v>>>14|E<<2)),x=s[7]+(8191&(E>>>11|S<<5)),P=s[8]+(8191&(S>>>8|A<<8)),O=s[9]+(A>>>5|n),L=0,D=L+_*i+k*(5*g)+I*(5*f)+R*(5*p)+T*(5*d);L=D>>>13,D&=8191,D+=C*(5*h)+N*(5*u)+x*(5*l)+P*(5*c)+O*(5*a),L+=D>>>13,D&=8191;let B=L+_*a+k*i+I*(5*g)+R*(5*f)+T*(5*p);L=B>>>13,B&=8191,B+=C*(5*d)+N*(5*h)+x*(5*u)+P*(5*l)+O*(5*c),L+=B>>>13,B&=8191;let U=L+_*c+k*a+I*i+R*(5*g)+T*(5*f);L=U>>>13,U&=8191,U+=C*(5*p)+N*(5*d)+x*(5*h)+P*(5*u)+O*(5*l),L+=U>>>13,U&=8191;let M=L+_*l+k*c+I*a+R*i+T*(5*g);L=M>>>13,M&=8191,M+=C*(5*f)+N*(5*p)+x*(5*d)+P*(5*h)+O*(5*u),L+=M>>>13,M&=8191;let F=L+_*u+k*l+I*c+R*a+T*i;L=F>>>13,F&=8191,F+=C*(5*g)+N*(5*f)+x*(5*p)+P*(5*d)+O*(5*h),L+=F>>>13,F&=8191;let $=L+_*h+k*u+I*l+R*c+T*a;L=$>>>13,$&=8191,$+=C*i+N*(5*g)+x*(5*f)+P*(5*p)+O*(5*d),L+=$>>>13,$&=8191;let H=L+_*d+k*h+I*u+R*l+T*c;L=H>>>13,H&=8191,H+=C*a+N*i+x*(5*g)+P*(5*f)+O*(5*p),L+=H>>>13,H&=8191;let q=L+_*p+k*d+I*h+R*u+T*l;L=q>>>13,q&=8191,q+=C*c+N*a+x*i+P*(5*g)+O*(5*f),L+=q>>>13,q&=8191;let V=L+_*f+k*p+I*d+R*h+T*u;L=V>>>13,V&=8191,V+=C*l+N*c+x*a+P*i+O*(5*g),L+=V>>>13,V&=8191;let j=L+_*g+k*f+I*p+R*d+T*h;L=j>>>13,j&=8191,j+=C*u+N*l+x*c+P*a+O*i,L+=j>>>13,j&=8191,L=(L<<2)+L|0,L=L+D|0,D=8191&L,L>>>=13,B+=L,s[0]=D,s[1]=B,s[2]=U,s[3]=M,s[4]=F,s[5]=$,s[6]=H,s[7]=q,s[8]=V,s[9]=j}finalize(){const{h:e,pad:t}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=n,n=e[t]>>>13,e[t]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let t=1;t<10;t++)r[t]=e[t]+n,n=r[t]>>>13,r[t]&=8191;r[9]-=8192;let s=(1^n)-1;for(let e=0;e<10;e++)r[e]&=s;s=~s;for(let t=0;t<10;t++)e[t]=e[t]&s|r[t];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);let o=e[0]+t[0];e[0]=65535&o;for(let r=1;r<8;r++)o=(e[r]+t[r]|0)+(o>>>16)|0,e[r]=65535&o;Ph(r)}update(e){Ih(this);const{buffer:t,blockLen:r}=this,n=(e=Th(e)).length;for(let s=0;s>>0,e[s++]=r[t]>>>8;return e}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}}const Kh=function(e){const t=(t,r)=>e(r).update(Th(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new jh(e)));function zh(e,t,r,n,s,o=20){let i=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],y=t[6],m=t[7],b=s,w=r[0],v=r[1],E=r[2],S=i,A=a,_=c,k=l,I=u,R=h,T=d,C=p,N=f,x=g,P=y,O=m,L=b,D=w,B=v,U=E;for(let e=0;e{e.update(t);const r=t.length%16;r&&e.update(Yh.subarray(r))},Xh=new Uint8Array(32);function Qh(e,t,r,n,s){const o=e(t,r,Xh),i=Kh.create(o);s&&Jh(i,s),Jh(i,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;Nh(c,0,BigInt(s?s.length:0),!0),Nh(c,8,BigInt(n.length),!0),i.update(a);const u=i.digest();return Ph(o,a),u}const Zh=e=>(t,r,n)=>(kh(t,32),kh(r),{encrypt(s,o){const i=s.length,a=i+16;o?kh(o,a):o=new Uint8Array(a),e(t,r,s,o,1);const c=Qh(e,t,r,o.subarray(0,-16),n);return o.set(c,i),Ph(c),o},decrypt(s,o){const i=s.length,a=i-16;if(i<16)throw new Error("encrypted data must be at least 16 bytes");o?kh(o,a):o=new Uint8Array(a);const c=s.subarray(0,-16),l=s.subarray(-16),u=Qh(e,t,r,c,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;nWr(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Nr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),nc(e,Ur(r),Ur(t))}(Wr,t,e),n=function(e,t,r,n=32){if(Nr(e),Tr(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/e.outputLen);void 0===r&&(r=rd);const o=new Uint8Array(s*e.outputLen),i=nc.create(e,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let t=0;t({publicKey:Oa.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Oa.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>ed(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,s)=>ed(n,t,r).decrypt(e.subarray(),s)},sd=e=>{const t=w(2);return t[0]=e>>8,t[1]=e,t};sd.bytes=2;const od=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function id(e,t){t.enabled&&Eh&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${nn(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${nn(e.privateKey,"hex")}`)):t("Missing local static keys."))}function ad(e,t){t.enabled&&Eh&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${nn(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${nn(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function cd(e,t){t.enabled&&Eh&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${nn(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function ld(e,t,r){r.enabled&&Eh&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&nn(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&nn(t.k,"hex")}`))}od.bytes=2;class ud extends Error{code;constructor(e="Unexpected Peer"){super(e),this.code=ud.code}static code="ERR_UNEXPECTED_PEER"}class hd extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=hd.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class dd{n;bytes;view;constructor(e=0){this.n=e,this.bytes=b(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const pd=b(0);class fd{k;n;crypto;constructor(e,t=void 0,r=0){this.crypto=e,this.k=t,this.n=new dd(r)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class gd{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=Nt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=b(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new fd(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new fd(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Ln(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,pd);return[new fd(this.crypto,e),new fd(this.crypto,t)]}}class yd{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:s,s:o,e:i,rs:a,re:c}=e;this.crypto=t,this.ss=new gd(t,r),this.ss.mixHash(n),this.initiator=s,this.s=o,this.e=i,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(const r of e.webtransportCerthashes)t.uint32(10),t.bytes(r);!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={webtransportCerthashes:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(bd||(bd={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),bd.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:b(0),identitySig:b(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=bd.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(wd||(wd={}));class Ad{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:s,prologueBytes:o}=t,{metrics:i}=e;this.components=e;const a=s??nd;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions=n,this.metrics=i?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(i):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=o??b(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Yu]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(...e){const{localPeer:t,connection:r,remotePeer:n,signal:s}=this.parseArgs(e),o=bh(r,{lengthEncoder:sd,lengthDecoder:od,maxDataLength:vh});if(!t.privateKey)throw new Zo("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");const i=await Wu(t.privateKey),a=n?.publicKey,c=await this.performHandshakeInitiator(o,i,a,{signal:s}),l=await this.createSecureConnection(o,c);return r.source=l.source,r.sink=l.sink,{conn:r,remoteExtensions:c.payload.extensions,remotePeer:await ah(c.payload.identityKey)}}async secureInbound(...e){const{localPeer:t,connection:r,remotePeer:n,signal:s}=this.parseArgs(e),o=bh(r,{lengthEncoder:sd,lengthDecoder:od,maxDataLength:vh});if(!t.privateKey)throw new Zo("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");const i=await Wu(t.privateKey),a=n?.publicKey,c=await this.performHandshakeResponder(o,i,a,{signal:s}),l=await this.createSecureConnection(o,c);return r.source=l.source,r.sink=l.sink,{conn:r,remoteExtensions:c.payload.extensions,remotePeer:await ah(c.payload.identityKey)}}async performHandshakeInitiator(e,t,r,n){let s;try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await vd(o,a.publicKey,l),h=new md({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});id(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(pd),t),r.trace("Stage 0 - Initiator finished sending first message."),ad(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),cd(h.re,r),p=h.rs,(f=r).enabled&&Eh&&f(p?`REMOTE_STATIC_PUBLIC_KEY ${nn(p.subarray(),"hex")}`:"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await Ed(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[y,m]=h.ss.split();return ld(y,m,r),{payload:g,encrypt:e=>y.encryptWithAd(pd,e),decrypt:(e,t)=>m.decryptWithAd(pd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async performHandshakeResponder(e,t,r,n){let s;try{s=await async function(e,t){const{log:r,connection:n,crypto:s,privateKey:o,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await vd(o,a.publicKey,l),h=new md({crypto:s,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});id(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),cd(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),ad(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await Ed(d,h.rs,c),[f,g]=h.ss.split();return ld(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(pd,e),decrypt:(e,t)=>f.decryptWithAd(pd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return s}async createSecureConnection(e,t){const[r,n]=function(){const e=wh(),t=wh();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),s=e.unwrap();return await Xn(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(o=n.length),s=n instanceof Uint8Array?e.encrypt(n.subarray(r,o)):e.encrypt(n.sublist(r,o)),t?.encryptedPackets.increment(),yield new Ln(sd(s.byteLength),s)}}}(t,this.metrics),s,(e=>jn(e,{lengthDecoder:od})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(s=n.length),s-16new Ad(t,e)}const kd=Symbol.for("@libp2p/peer-discovery"),Id=np("dns4"),Rd=np("dns6"),Td=np("dnsaddr"),Cd=rp(np("dns"),Td,Id,Rd),Nd=rp(np("ip4"),np("ip6")),xd=rp(tp(Nd,np("tcp")),tp(Cd,np("tcp"))),Pd=tp(Nd,np("udp")),Od=tp(Pd,np("utp")),Ld=tp(Pd,np("quic")),Dd=tp(Pd,np("quic-v1")),Bd=rp(tp(xd,np("ws")),tp(Cd,np("ws"))),Ud=rp(tp(Bd,np("p2p")),Bd),Md=rp(tp(xd,np("wss")),tp(Cd,np("wss")),tp(xd,np("tls"),np("ws")),tp(Cd,np("tls"),np("ws"))),Fd=rp(tp(Md,np("p2p")),Md),$d=rp(tp(xd,np("http")),tp(Nd,np("http")),tp(Cd,np("http"))),Hd=rp(tp(xd,np("https")),tp(Nd,np("https")),tp(Cd,np("https"))),qd=tp(Pd,np("webrtc-direct"),np("certhash")),Vd=rp(tp(qd,np("p2p")),qd),jd=tp(Dd,np("webtransport"),np("certhash"),np("certhash")),Kd=rp(tp(jd,np("p2p")),jd),zd=rp(tp(Ud,np("p2p-webrtc-star"),np("p2p")),tp(Fd,np("p2p-webrtc-star"),np("p2p")),tp(Ud,np("p2p-webrtc-star")),tp(Fd,np("p2p-webrtc-star"))),Gd=(rp(tp(Ud,np("p2p-websocket-star"),np("p2p")),tp(Fd,np("p2p-websocket-star"),np("p2p")),tp(Ud,np("p2p-websocket-star")),tp(Fd,np("p2p-websocket-star"))),rp(tp($d,np("p2p-webrtc-direct"),np("p2p")),tp(Hd,np("p2p-webrtc-direct"),np("p2p")),tp($d,np("p2p-webrtc-direct")),tp(Hd,np("p2p-webrtc-direct")))),Wd=rp(Bd,Md,$d,Hd,zd,Gd,xd,Od,Ld,Cd,Vd,Kd),Yd=(rp(tp(Wd,np("p2p-stardust"),np("p2p")),tp(Wd,np("p2p-stardust"))),rp(tp(Wd,np("p2p")),zd,Gd,Vd,Kd,np("p2p"))),Jd=rp(tp(Yd,np("p2p-circuit"),Yd),tp(Yd,np("p2p-circuit")),tp(np("p2p-circuit"),Yd),tp(Wd,np("p2p-circuit")),tp(np("p2p-circuit"),Wd),np("p2p-circuit")),Xd=()=>rp(tp(Jd,Xd),Jd),Qd=Xd(),Zd=rp(tp(Qd,Yd,Qd),tp(Yd,Qd),tp(Qd,Yd),Qd,Yd);function ep(e){return function(t){let r;try{r=_o(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function tp(...e){function t(t){if(t.length(r="function"==typeof e?e().partialMatch(t):e.partialMatch(t),Array.isArray(r)&&(t=r),null===r))),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ep(t),partialMatch:t}}function rp(...e){function t(t){let r=null;return e.some((e=>{const n="function"==typeof e?e().partialMatch(t):e.partialMatch(t);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+e.join(" ")+" }"},input:e,matches:ep(t),partialMatch:t}}function np(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=_o(e)}catch(e){return!1}const n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}rp(tp(Qd,np("webrtc"),np("p2p")),tp(Qd,np("webrtc")),tp(Wd,np("webrtc"),np("p2p")),tp(Wd,np("webrtc")),np("webrtc"));class sp extends xs{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(null==t.list||0===t.list.length)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??1e3,this.list=[];for(const e of t.list){if(!Zd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=_o(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:oh(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[kd]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Yu]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL??12e4}}}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e})}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const op=Uint8Array.from([3,1]);var ip;!function(e){let t,r;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3==1?r.multiaddr=e.bytes():e.skipType(7&t)}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(t=e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==r&&(r=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(const n of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(n,r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={peerId:new Uint8Array(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.peerId=t.bytes();break;case 2:n.seq=t.uint64();break;case 3:n.addresses.push(e.AddressInfo.codec().decode(t,t.uint32()));break;default:t.skipType(7&r)}}return n}))),r),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(ip||(ip={}));class ap{static createFromProtobuf=e=>{const t=ip.decode(e),r=ih(t.peerId),n=(t.addresses??[]).map((e=>_o(e.multiaddr))),s=t.seq;return new ap({peerId:r,multiaddrs:n,seqNumber:s})};static DOMAIN="libp2p-peer-record";static CODEC=op;peerId;multiaddrs;seqNumber;domain=ap.DOMAIN;codec=ap.CODEC;marshaled;constructor(e){const{peerId:t,multiaddrs:r,seqNumber:n}=e;this.peerId=t,this.multiaddrs=r??[],this.seqNumber=n??BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=ip.encode({peerId:this.peerId.toBytes(),seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof ap&&!!this.peerId.equals(e.peerId)&&this.seqNumber===e.seqNumber&&!!function(e,t){const r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)}}var cp;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={publicKey:new Uint8Array(0),payloadType:new Uint8Array(0),payload:new Uint8Array(0),signature:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(cp||(cp={}));class lp{static createFromProtobuf=async e=>{const t=cp.decode(e),r=await ah(t.publicKey);return new lp({peerId:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t.privateKey)throw new Error("Missing private key");const r=e.domain,n=e.codec,s=e.marshal(),o=up(r,n,s),i=await Wu(t.privateKey),a=await i.sign(o.subarray());return new lp({peerId:t,payloadType:n,payload:s,signature:a})};static openAndCertify=async(e,t)=>{const r=await lp.createFromProtobuf(e);if(!await r.validate(t))throw new Zo("envelope signature is not valid for the given domain","ERR_SIGNATURE_NOT_VALID");return r};peerId;payloadType;payload;signature;marshaled;constructor(e){const{peerId:t,payloadType:r,payload:n,signature:s}=e;this.peerId=t,this.payloadType=r,this.payload=n,this.signature=s}marshal(){if(null==this.peerId.publicKey)throw new Error("Missing public key");return null==this.marshaled&&(this.marshaled=cp.encode({publicKey:this.peerId.publicKey,payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Nn(this.marshal(),e.marshal())}async validate(e){const t=up(e,this.payloadType,this.payload);if(null==this.peerId.publicKey)throw new Error("Missing public key");return zu(this.peerId.publicKey).verify(t.subarray(),this.signature)}}const up=(e,t,r)=>{const n=Nt(e),s=P(n.byteLength),o=P(t.length),i=P(r.length);return new Ln(s,n,o,t,i,r)},hp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),dp=e=>({match:t=>hp((t=>t===e)).match(t),pattern:e}),pp=()=>({match:e=>hp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),fp=()=>({match:e=>hp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),gp=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{ke.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),yp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ce.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),mp=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),bp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.lengthe.pattern)).join(", ")})`}),wp=(...e)=>({match:t=>{for(const r of e){const e=r.match(t);if(!1===e)return!1;t=e}return t},pattern:`and(${e.map((e=>e.pattern)).join(", ")})`});function vp(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const Ep=wp(dp("dns4"),pp()),Sp=wp(dp("dns6"),pp()),Ap=wp(dp("dnsaddr"),pp()),_p=wp(dp("dns"),pp()),kp=(vp(Ep,mp(gp())),vp(Sp,mp(gp())),vp(Ap,mp(gp())),vp(bp(_p,Ap,Ep,Sp),mp(gp())),wp(dp("ip4"),hp(zs))),Ip=wp(dp("ip6"),hp(Gs)),Rp=bp(kp,Ip),Tp=bp(Rp,_p,Ep,Sp,Ap),Cp=vp(bp(Rp,wp(bp(_p,Ap,Ep,Sp),mp(gp())))),Np=(vp(kp),vp(Ip),vp(Rp),wp(Tp,dp("tcp"),fp())),xp=wp(Tp,dp("udp"),fp()),Pp=(vp(wp(Np,mp(gp()))),vp(xp),wp(xp,dp("quic"))),Op=wp(xp,dp("quic-v1")),Lp=bp(Pp,Op),Dp=(vp(Pp),vp(Op),bp(Tp,Np,xp,Pp,Op)),Bp=bp(wp(Dp,dp("ws"),mp(gp()))),Up=(vp(Bp),bp(wp(Dp,dp("wss"),mp(gp())),wp(Dp,dp("tls"),dp("ws"),mp(gp())))),Mp=(vp(Up),wp(xp,dp("webrtc-direct"),mp(yp()),mp(yp()),mp(gp()))),Fp=(vp(Mp),wp(Op,dp("webtransport"),mp(yp()),mp(yp()),mp(gp()))),$p=(vp(Fp),bp(Bp,Up,wp(Np,mp(gp())),wp(Lp,mp(gp())),wp(Tp,mp(gp())),Mp,Fp,gp())),Hp=(vp($p),vp(wp($p,dp("p2p-circuit"),gp())));function qp(e,t){const r=bh(e,t),n={read:async(e,t)=>{const n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Vp;vp(bp(wp($p,dp("p2p-circuit"),dp("webrtc"),mp(gp())),wp($p,dp("webrtc"),mp(gp())),dp("webrtc"))),vp(bp(wp(Tp,dp("tcp"),fp(),dp("http"),mp(gp())),wp(Tp,dp("http"),mp(gp())))),vp(bp(wp(Tp,dp("tcp"),bp(wp(dp("443"),dp("http")),wp(fp(),dp("https"))),mp(gp())),wp(Tp,dp("tls"),dp("http"),mp(gp())),wp(Tp,dp("https"),mp(gp())))),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(const r of e.listenAddrs)t.uint32(18),t.bytes(r);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(const r of e.protocols)t.uint32(26),t.string(r);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={listenAddrs:[],protocols:[]},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 5:r.protocolVersion=e.string();break;case 6:r.agentVersion=e.string();break;case 1:r.publicKey=e.bytes();break;case 2:r.listenAddrs.push(e.bytes());break;case 4:r.observedAddr=e.bytes();break;case 3:r.protocols.push(e.string());break;case 8:r.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Vp||(Vp={}));var jp=__webpack_require__(4866);const Kp="object"==typeof window&&"object"==typeof document&&9===document.nodeType,zp=jp(),Gp=Kp&&!zp,Wp=zp&&!Kp,Yp=zp&&Kp,Jp=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!zp,Xp="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Qp=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product),Zp="ipfs",ef=5e3,tf=1,rf=1,nf=10,sf=8192,of=!0,af=!0;class cf{host;protocol;started;timeout;peerId;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnTransientConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??ef,this.maxInboundStreams=t.maxInboundStreams??tf,this.maxOutboundStreams=t.maxOutboundStreams??rf,this.maxMessageSize=t.maxMessageSize??sf,this.maxObservedAddresses=t.maxObservedAddresses??nf,this.runOnTransientConnection=t.runOnTransientConnection??af,this.host={protocolVersion:`${t.protocolPrefix??Zp}/0.1.0`,agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n||(n=`${r.name}/${r.version}`,Jp||Wp?n+=` UserAgent=${globalThis.process.version}`:(Gp||Xp||Yp||Qp)&&(n+=` UserAgent=${globalThis.navigator.userAgent}`)),n)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:Nt(this.host.agentVersion),ProtocolVersion:Nt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class lf extends cf{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??Zp}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??of)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{this.log.error("error during identify trigged by connection:open",e)}))}))}[Yu]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection});const n=qp(r,{maxDataLength:this.maxMessageSize}).pb(Vp),s=await n.read(t);return await r.close(t),s}catch(e){throw this.log.error("error while reading identify message",e),r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:s,observedAddr:o}=r;if(null==n)throw new Zo("public key was missing from identify message","ERR_MISSING_PUBLIC_KEY");const i=await ah(n);if(!e.remotePeer.equals(i))throw new Zo("identified peer does not match the expected peer","ERR_INVALID_PEER");if(this.peerId.equals(i))throw new Zo("identified peer is our own peer id?","ERR_INVALID_PEER");const a=function(e){if(null!=e&&e.length>0)try{return _o(e)}catch{}}(o);return this.log("identify completed for peer %p and protocols %o",i,s),this.log("our observed address is %a",a),null!=a&&this.addressManager.getObservedAddrs().length<(this.maxObservedAddresses??1/0)&&(this.log("storing our observed address %a",a),this.addressManager.addObservedAddr(a)),async function(e,t,r,n,s){if(r("received identify from %p",n.remotePeer),null==s)throw new Zo("message was null or undefined","ERR_INVALID_MESSAGE");const o={};if(s.listenAddrs.length>0&&(o.addresses=s.listenAddrs.map((e=>({isCertified:!1,multiaddr:_o(e)})))),s.protocols.length>0&&(o.protocols=s.protocols),null!=s.publicKey&&(o.publicKey=s.publicKey,!(await ah(s.publicKey)).equals(n.remotePeer)))throw new Zo("public key did not match remote PeerId","ERR_INVALID_PUBLIC_KEY");let i;if(null!=s.signedPeerRecord){r("received signedPeerRecord from %p",n.remotePeer);let t=s.signedPeerRecord;const a=await lp.openAndCertify(t,ap.DOMAIN);let c,l=ap.createFromProtobuf(a.payload);if(!l.peerId.equals(a.peerId))throw new Zo("signing key does not match PeerId in the PeerRecord","ERR_INVALID_SIGNING_KEY");if(!n.remotePeer.equals(l.peerId))throw new Zo("signing key does not match remote PeerId","ERR_INVALID_PEER_RECORD_KEY");try{c=await e.get(l.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=c&&(o.metadata=c.metadata,null!=c.peerRecordEnvelope)){const e=await lp.createFromProtobuf(c.peerRecordEnvelope),n=ap.createFromProtobuf(e.payload);n.seqNumber>=l.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,l.seqNumber),l=n,t=c.peerRecordEnvelope)}o.peerRecordEnvelope=t,o.addresses=l.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),i={seq:l.seqNumber,addresses:l.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r("patching %p with",n.remotePeer,o),await e.patch(n.remotePeer,o),null!=s.agentVersion||null!=s.protocolVersion){const t={};null!=s.agentVersion&&(t.AgentVersion=Nt(s.agentVersion)),null!=s.protocolVersion&&(t.ProtocolVersion=Nt(s.protocolVersion)),r("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:s.protocolVersion,agentVersion:s.agentVersion,publicKey:s.publicKey,listenAddrs:s.listenAddrs.map((e=>_o(e))),observedAddr:null==s.observedAddr?void 0:_o(s.observedAddr),protocols:s.protocols,signedPeerRecord:i,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=this.peerId.publicKey??new Uint8Array(0),s=await this.peerStore.get(this.peerId),o=this.addressManager.getAddresses().map((e=>e.decapsulateCode(to("p2p").code)));let i=s.peerRecordEnvelope;if(o.length>0&&null==i){const e=new ap({peerId:this.peerId,multiaddrs:o});i=(await lp.seal(e,this.peerId)).marshal().subarray()}let a=t.remoteAddr.bytes;Cp.matches(t.remoteAddr)||(a=void 0);const c=qp(r).pb(Vp);await c.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:e,listenAddrs:o.map((e=>e.bytes)),signedPeerRecord:i,observedAddr:a,protocols:s.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function uf(e={}){return t=>new lf(t,e)}function hf(e,t){const r=function(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw new Error("argument is not an iterator or iterable")}(e).return?.();var n;null!=(n=r)&&"function"==typeof n.then&&"function"==typeof n.catch&&"function"==typeof n.finally&&r.catch((e=>{t.error("could not cause iterator to return",e)}))}const df=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},pf=new WeakMap,ff=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:s}={})=>{if(s?.aborted)return Promise.reject(df());let o,i,a;const c=e??clearTimeout,l=()=>{c(o),a(df())},u=new Promise(((e,c)=>{i=()=>{s&&s.removeEventListener("abort",l),e(n)},a=c,o=(t??setTimeout)(i,r)}));return s&&s.addEventListener("abort",l,{once:!0}),pf.set(u,(()=>{c(o),o=null,i()})),u}}();class gf{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??1e3*this.duration/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new yf}async consume(e,t=1,r={}){const n=this.getKey(e),s=this._getKeySecDuration(r);let o=this.memoryStorage.incrby(n,t,s);if(o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.consumedPoints>this.points)throw this.blockDuration>0&&o.consumedPoints<=this.points+t&&(o=this.memoryStorage.set(n,o.consumedPoints,this.blockDuration)),new Zo("Rate limit exceeded","ERR_RATE_LIMIT_EXCEEDED",o);if(this.execEvenly&&o.msBeforeNext>0&&!o.isFirstInDuration){let e=Math.ceil(o.msBeforeNext/(o.remainingPoints+2));e=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){const t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=e?.customDuration&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}}class yf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const s=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||s>0?(n.value+=t,{remainingPoints:0,msBeforeNext:s,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,s=this.storage.get(e);null!=s&&clearTimeout(s.timeoutId);const o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=o.timeoutId.unref&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){const t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){const t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}var mf;!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(mf||(mf={}));const bf=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),wf=Object.freeze({NEW_STREAM:mf.NEW_STREAM,MESSAGE:mf.MESSAGE_INITIATOR,CLOSE:mf.CLOSE_INITIATOR,RESET:mf.RESET_INITIATOR}),vf=Object.freeze({MESSAGE:mf.MESSAGE_RECEIVER,CLOSE:mf.CLOSE_RECEIVER,RESET:mf.RESET_RECEIVER}),Ef=1<<20;class Sf{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Ef,t=4194304){this._buffer=new Ln,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw Object.assign(new Error("unprocessed message queue size too large!"),{code:"ERR_MSG_QUEUE_TOO_BIG"});const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("ERR_MSG_TOO_BIG"===e.code)throw e;break}const{id:e,type:r,length:n,offset:s}=this._headerInfo;if(this._buffer.length-sthis._maxMessageSize)throw Object.assign(new Error("message size too large!"),{code:"ERR_MSG_TOO_BIG"});return{id:t>>3,type:o,offset:r+s,length:n}}}const Af=128,_f=127;function kf(e,t=0){let r,n=0,s=0,o=t;const i=e.length;do{if(o>=i||s>49)throw t=0,new RangeError("Could not decode varint");r=e.get(o++),n+=s<28?(r&_f)<=Af);return{value:n,offset:t=o-t}}const If=10240,Rf=new class{_pool;_poolOffset;constructor(){this._pool=w(If),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;P(e.id<<3|e.type,r,n),n+=C(e.id<<3|e.type),e.type!==mf.NEW_STREAM&&e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||null==e.data?(P(0,r,n),n+=C(0)):(P(e.data.length,r,n),n+=C(e.data.length));const s=r.subarray(this._poolOffset,n);If-n<100?(this._pool=w(If),this._poolOffset=0):this._poolOffset=n,t.append(s),e.type!==mf.NEW_STREAM&&e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function Tf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Cf{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(e){this.sinkController=new AbortController,this.sinkEnd=Kn(),this.closed=Kn(),this.log=e.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=e.id,this.metadata=e.metadata??{},this.direction=e.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=e.sendCloseWriteTimeout??5e3,this.onEnd=e.onEnd,this.onCloseRead=e?.onCloseRead,this.onCloseWrite=e?.onCloseWrite,this.onReset=e?.onReset,this.onAbort=e?.onAbort,this.source=this.streamSource=Yn({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(e){if("ready"!==this.writeStatus)throw new Zo(`writable end state is "${this.writeStatus}" not "ready"`,"ERR_SINK_INVALID_STATE");try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);Tf(e)&&await e}const r=()=>{hf(e,this.log)};try{this.sinkController.signal.addEventListener("abort",r),this.log.trace("sink reading from source");for await(let r of e){r=r instanceof Uint8Array?new Ln(r):r;const e=this.sendData(r,t);Tf(e)&&(this.sendingData=Kn(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){this.log.trace("closing gracefully"),this.status="closing",await lh(Promise.all([this.closeWrite(e),this.closeRead(e),this.closed.promise]),e?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(e={}){if("closing"===this.readStatus||"closed"===this.readStatus)return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);const t=this.readStatus;this.readStatus="closing","reset"!==this.status&&"aborted"!==this.status&&null==this.timeline.closeRead&&(this.log.trace("send close read to remote"),await this.sendCloseRead(e)),"ready"===t&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(e={}){"closing"!==this.writeStatus&&"closed"!==this.writeStatus&&(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),"ready"===this.writeStatus&&(this.log.trace("sink was never sunk, sink an empty array"),await lh(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await lh(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await lh(this.sinkEnd.promise,e.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(e){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;this.log("abort with error",e),this.log("try to send reset to remote");const t=this.sendReset();Tf(t)&&t.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),this.onAbort?.(e)}reset(){if("closed"===this.status||"aborted"===this.status||"reset"===this.status)return;const e=new Zo("stream reset","ERR_STREAM_RESET");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(e),this.onReset?.()}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}class Nf extends Cf{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?wf:vf,this.send=e.send,this.name=e.name,this.streamId=e.streamId,this.maxDataSize=e.maxDataSize}async sendNewStream(){await this.send({id:this.streamId,type:wf.NEW_STREAM,data:new Ln(Nt(this.name))})}async sendData(e){for(e=e.sublist();e.byteLength>0;){const t=Math.min(e.byteLength,this.maxDataSize);await this.send({id:this.streamId,type:this.types.MESSAGE,data:e.sublist(0,t)}),e.consume(t)}}async sendReset(){await this.send({id:this.streamId,type:this.types.RESET})}async sendCloseWrite(){await this.send({id:this.streamId,type:this.types.CLOSE})}async sendCloseRead(){}}function xf(e){const t={...e,type:`${bf[e.type]} (${e.type})`};return e.type===mf.NEW_STREAM&&(t.data=nn(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==mf.MESSAGE_INITIATOR&&e.type!==mf.MESSAGE_RECEIVER||(t.data=nn(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class Pf{protocol="/mplex/6.7.0";sink;source;log;_streamId;_streams;_init;_source;closeController;rateLimiter;closeTimeout;logger;constructor(e,t){t=t??{},this.log=e.logger.forComponent("libp2p:mplex"),this.logger=e.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=t,this.closeTimeout=t.closeTimeout??500,this.sink=this._createSink(),this._source=Yn({objectMode:!0,onEnd:()=>{for(const e of this._streams.initiators.values())e.destroy();for(const e of this._streams.receivers.values())e.destroy()}}),this.source=Xn(this._source,(e=>async function*(e){for await(const t of e){const e=new Ln;Rf.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new gf({points:t.disconnectThreshold??5,duration:1})}get streams(){const e=[];for(const t of this._streams.initiators.values())e.push(t);for(const t of this._streams.receivers.values())e.push(t);return e}newStream(e){if(this.closeController.signal.aborted)throw new Error("Muxer already closed");const t=this._streamId++;e=null==e?t.toString():e.toString();const r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}async close(e){if(this.closeController.signal.aborted)return;const t=e?.signal??AbortSignal.timeout(this.closeTimeout);try{await Promise.all(this.streams.map((async e=>e.close({signal:t})))),this._source.end(),await this._source.onEmpty({signal:t}),this.closeController.abort()}catch(e){this.abort(e)}}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){const{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(e){const{id:t,name:r,type:n,registry:s}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new Zo("Too many outbound streams open","ERR_TOO_MANY_OUTBOUND_STREAMS");if(s.has(t))throw new Error(`${n} stream ${t} already exists!`);const o=function(e){const{id:t,name:r,send:n,onEnd:s,type:o="initiator",maxMsgSize:i=Ef}=e;return new Nf({id:"initiator"===o?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:"initiator"===o?"outbound":"inbound",maxDataSize:i,onEnd:s,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${o}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,xf(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,o.protocol),s.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(o)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(t,o),o}_createSink(){return async e=>{const t=()=>{hf(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Sf(this._init.maxMsgSize,this._init.maxUnprocessedMessageQueueSize);for await(const r of e)for(const e of t.write(r))await this._handleIncoming(e);this._source.end()}catch(e){this.log("error in sink",e),this._source.end(e)}finally{this.closeController.signal.removeEventListener("abort",t)}}}async _handleIncoming(e){const{id:t,type:r}=e;if(this.log.enabled&&this.log.trace("incoming message",xf(e)),e.type===mf.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:mf.RESET_RECEIVER});try{await this.rateLimiter.consume("new-stream",1)}catch{return this.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void this.abort(new Error("Too many open streams"))}return}const r=this._newReceiverStream({id:t,name:nn(e.data instanceof Uint8Array?e.data:e.data.subarray())});return void(null!=this._init.onIncomingStream&&this._init.onIncomingStream(r))}const n=(1&~r?this._streams.receivers:this._streams.initiators).get(t);if(null==n){this.log("missing stream %s for message type %s",t,bf[r]);try{await this.rateLimiter.consume("missing-stream",1)}catch{return this.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void this.abort(new Error("Too many messages for missing streams"))}return}const s=this._init.maxStreamBufferSize??4194304;try{switch(r){case mf.MESSAGE_INITIATOR:case mf.MESSAGE_RECEIVER:if(n.sourceReadableLength()>s)throw this._source.push({id:e.id,type:r===mf.MESSAGE_INITIATOR?mf.RESET_RECEIVER:mf.RESET_INITIATOR}),new Zo("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers","ERR_STREAM_INPUT_BUFFER_FULL");n.sourcePush(e.data);break;case mf.CLOSE_INITIATOR:case mf.CLOSE_RECEIVER:n.remoteCloseWrite();break;case mf.RESET_INITIATOR:case mf.RESET_RECEIVER:n.reset();break;default:this.log("unknown message type %s",r)}}catch(e){this.log.error("error while processing message",e),n.abort(e)}}}class Of{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[Yu]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new Pf(this.components,{...e,...this._init})}}function Lf(e={}){return t=>new Of(t,e)}const Df="ERR_WRONG_PING_ACK";class Bf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnTransientConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnTransientConnection=t.runOnTransientConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnTransientConnection:this.runOnTransientConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now();AbortSignal.timeout(this.timeout).addEventListener("abort",(()=>{t?.abort(new Zo("ping timeout",ti))})),Xn(t,(async function*(e){let r=0;for await(const n of e){if(r+=n.byteLength,r>32)return void t?.abort(new Zo("Too much data received","ERR_INVALID_MESSAGE"));yield n}}),t).catch((r=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,r),t?.abort(r)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=lu(32),s=await this.components.connectionManager.openConnection(e,t);let o,i=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{o=await s.newStream(this.protocol,{...t,runOnTransientConnection:this.runOnTransientConnection}),i=()=>{o?.abort(new Zo("ping timeout",ti))},t.signal?.addEventListener("abort",i,{once:!0});const e=await Xn([n],o,(async e=>function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e)return t})();for(const t of e)return t}(e))),a=Date.now()-r;if(null==e)throw new Zo(`Did not receive a ping ack after ${a}ms`,Df);if(!Nn(n,e.subarray()))throw new Zo(`Received wrong ping ack after ${a}ms`,Df);return this.log("ping %p complete in %dms",s.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",s.remotePeer,e),o?.abort(e),e}finally{t.signal?.removeEventListener("abort",i),null!=o&&await o.close()}}}function Uf(e={}){return t=>new Bf(t,e)}const Mf=Symbol.for("@libp2p/transport");var Ff;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Ff||(Ff={}));const $f=[to("tcp").code,to("dns").code,to("dnsaddr").code,to("dns4").code,to("dns6").code];function Hf(e){let t;try{t=to("sni").code}catch(e){return null}for(const[r,n]of e)if(r===t&&void 0!==n)return n;return null}function qf(e){return e.some((([e,t])=>e===to("tls").code))}function Vf(e,t,r){const n=jf[to(e).name];if(void 0===n)throw new Error(`Can't interpret protocol ${to(e).name}`);const s=n(t,r);return e===to("ip6").code?`[${s}]`:s}const jf={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`tcp://${Vf(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`udp://${Vf(r[0],r[1]??"",t)}:${e}`},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/ipfs/${e}`},p2p:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p/${e}`},http:(e,t)=>{const r=qf(t),n=Hf(t);if(r&&null!==n)return`https://${n}`;const s=r?"https://":"http://",o=t.pop();if(void 0===o)throw new Error("Unexpected end of multiaddr");let i=Vf(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},"http-path":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return Vf(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return Vf(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=Vf(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=qf(t),n=Hf(t);if(r&&null!==n)return`wss://${n}`;const s=r?"wss://":"ws://",o=t.pop();if(void 0===o)throw new Error("Unexpected end of multiaddr");let i=Vf(o[0],o[1]??"",t);return i=i.replace("tcp://",""),`${s}${i}`},wss:(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");let n=Vf(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`},"p2p-websocket-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-websocket-star`},"p2p-webrtc-star":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-webrtc-star`},"p2p-webrtc-direct":(e,t)=>{const r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");return`${Vf(r[0],r[1]??"",t)}/p2p-webrtc-direct`}},Kf=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",s),e.removeEventListener("error",o)}function s(){n(),t()}function o(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",s),e.addEventListener("error",o)}))},zf=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await Kf(e)}catch(e){if("socket closed"===e.message)break;throw e}if(e.readyState===e.CLOSING||e.readyState===e.CLOSED)break;e.send(t)}null!=t.closeOnEnd&&e.readyState<=1&&await new Promise(((t,r)=>{e.addEventListener("close",(e=>{if(e.wasClean||1006===e.code)t();else{const t=Object.assign(new Error("ws error"),{event:e});r(t)}})),setTimeout((()=>{e.close()}))}))});var Gf=__webpack_require__(544);function Wf(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const Yf=WebSocket,Jf={"http:":"ws:","https:":"wss:"};function Xf(e,t){t=t??{};const r=((e,t)=>{if(e.startsWith("//")&&(e=`${t?.protocol??"ws:"}${e}`),e.startsWith("/")&&null!=t){const r=t.protocol??"ws:",n=t.host,s=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${s}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(Jf))r.protocol===e&&(r.protocol=t);return r})(e,"undefined"==typeof window?void 0:window.location);return((e,t)=>{t=t??{};const r=(e=>{e.binaryType="arraybuffer";const t=async()=>{await new Promise(((t,r)=>{if(s)return void t();if(null!=n)return void r(n);const o=t=>{e.removeEventListener("open",i),e.removeEventListener("error",a),t()},i=()=>{o(t)},a=t=>{o((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",i),e.addEventListener("error",a)}))},r=async function*(){const r=new Gf.PP((({push:t,stop:r,fail:n})=>{const s=e=>{let r=null;"string"==typeof e.data&&(r=Nt(e.data)),Wf(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},o=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",s),e.addEventListener("error",o),e.addEventListener("close",r),()=>{e.removeEventListener("message",s),e.removeEventListener("error",o),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield Wf(e)?new Uint8Array(e):e}();let n,s=1===e.readyState;return e.addEventListener("open",(()=>{s=!0,n=null})),e.addEventListener("close",(()=>{s=!1,n=null})),e.addEventListener("error",(t=>{s||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,s=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,s=parseInt(t.port,10)}catch{}if(null==n||null==s)throw new Error("Remote connection did not have address and/or port");return{sink:zf(e,t),source:r,connected:async()=>{await r.connected()},close:async()=>{e.readyState!==e.CONNECTING&&e.readyState!==e.OPEN||await new Promise((t=>{e.addEventListener("close",(()=>{t()})),e.close()}))},destroy:()=>{null!=e.terminate?e.terminate():e.close()},remoteAddress:n,remotePort:s,socket:e}})(new Yf(r.toString(),t.websocket),t)}class Qf extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function Zf(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Ud.matches(t)||Fd.matches(t)}))}function eg(e){return e.filter((e=>{if(e.protoCodes().includes(290))return!1;const t=e.decapsulateCode(421);return Fd.matches(t)}))}class tg{log;init;logger;metrics;components;constructor(e,t){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Mf]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Yu]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),s=r.metrics,o=r.metricPrefix??"",i={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const s=()=>{const{host:e,port:t}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Zo("Socket close timeout","ERR_SOCKET_CLOSE_TIMEOUT"))};t.signal?.addEventListener("abort",s);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",s),i.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),i.timeline.close=Date.now(),s?.increment({[`${o}error`]:!0})}};return e.socket.addEventListener("close",(()=>{s?.increment({[`${o}close`]:!0}),null==i.timeline.close&&(i.timeline.close=Date.now())}),{once:!0}),i}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=Kn(),s=Xf(function(e){const t=_o(e).stringTuples(),r=t.pop();if(void 0===r)throw new Error("Unexpected end of multiaddr");const n=to(r[0]),s=jf[n.name];if(null==s)throw new Error(`No interpreter found for ${n.name}`);let o=s(r[1]??"",t);return $f.includes(r[0])&&(o=o.replace(/^.*:\/\//,""),o="443"===r[1]?`https://${o}`:`http://${o}`),(o.startsWith("http://")||o.startsWith("https://"))&&(o=new URL(o).toString(),o.endsWith("/")&&(o=o.substring(0,o.length-1))),o}(e),this.init);s.socket.addEventListener("error",(()=>{const t=new Zo(`Could not connect to ${e.toString()}`,"ERR_CONNECTION_FAILED");this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new Qf("websockets:open-connection")),await lh(Promise.race([s.connected(),n.promise]),t.signal)}catch(e){throw!0===t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),s.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),s}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):Gp||Xp?eg(e):Zf(e)}dialFilter(e){return this.listenFilter(e)}}function rg(e={}){return t=>new tg(t,e)}const ng=Symbol.for("@libp2p/content-routing"),sg=Symbol.for("@libp2p/peer-routing"),og=1e3,ig=60*og,ag=60*ig,cg=24*ag,lg=7*cg,ug=function(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*lg;case"days":case"day":case"d":return r*cg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*ag;case"minutes":case"minute":case"mins":case"min":case"m":return r*ig;case"seconds":case"second":case"secs":case"sec":case"s":return r*og;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=cg?hg(e,t,cg,"day"):t>=ag?hg(e,t,ag,"hour"):t>=ig?hg(e,t,ig,"minute"):t>=og?hg(e,t,og,"second"):`${e} ms`}(e):function(e){const t=Math.abs(e);return t>=cg?`${Math.round(e/cg)}d`:t>=ag?`${Math.round(e/ag)}h`:t>=ig?`${Math.round(e/ig)}m`:t>=og?`${Math.round(e/og)}s`:`${e}ms`}(e);throw new Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw new Error(r)}};function hg(e,t,r,n){const s=t>=1.5*r;return`${Math.round(e/r)} ${n}${s?"s":""}`}const dg=function(){try{return localStorage}catch(e){}}(),pg=console.debug??console.log??(()=>{}),fg=function(e){function t(e){let n,s,o,i=null;function a(...e){if(!a.enabled)return;const r=a,s=Number(new Date),o=s-(n||s);r.diff=o,r.prev=n,r.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";i++;const o=t.formatters[s];if("function"==typeof o){const t=e[i];n=o.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(s!==t.namespaces&&(s=t.namespaces,o=t.enabled(e)),o),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save:function(e){try{e?dg?.setItem("debug",e):dg?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=dg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:dg,log:pg}),gg=fg;function yg(){return{forComponent:e=>function(e){let t=function(e){const t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}(`${e}:trace`);return gg.enabled(`${e}:trace`)&&null!=gg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=gg(`${e}:trace`)),Object.assign(gg(e),{error:gg(`${e}:error`),trace:t})}(e)}}function mg(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}gg.formatters.b=e=>null==e?"undefined":ke.baseEncode(e),gg.formatters.t=e=>null==e?"undefined":fe.baseEncode(e),gg.formatters.m=e=>null==e?"undefined":Re.baseEncode(e),gg.formatters.p=e=>null==e?"undefined":e.toString(),gg.formatters.c=e=>null==e?"undefined":e.toString(),gg.formatters.k=e=>null==e?"undefined":e.toString(),gg.formatters.a=e=>null==e?"undefined":e.toString();class bg{set;constructor(e){if(this.set=new Set,null!=e)for(const t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return mg(this.set.entries(),(e=>{const t=oh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=oh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return mg(this.set.values(),(e=>oh(e)))}intersection(e){const t=new bg;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new bg;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new bg;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}async function wg(e){return ah(Gu(e.public),(t=e,ju(r=(r??"rsa").toLowerCase()),t.bytes));var t,r}async function vg(e){return async function(e,t,r){if(null!=t)return wg(await Wu(t));if(null!=r)return async function(e){return ah(Gu(e))}(zu(r));const n=ih(e);if("Ed25519"!==n.type&&"secp256k1"!==n.type&&"RSA"!==n.type)throw new Error("Supplied PeerID is invalid");return n}(Nt(e.id,"base58btc"),null!=e.privKey?Nt(e.privKey,"base64pad"):void 0,null!=e.pubKey?Nt(e.pubKey,"base64pad"):void 0)}class Eg{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),r)}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return mg(this.map.entries(),(e=>[oh(e[0]),e[1]]))}forEach(e){this.map.forEach(((t,r)=>{e(t,oh(r),this)}))}get(e){return this.map.get(e.toString())}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),t)}keys(){return mg(this.map.keys(),(e=>oh(e)))}values(){return this.map.values()}get size(){return this.map.size}}var Sg=__webpack_require__(228);class Ag extends Error{constructor(e){super(e),this.name="TimeoutError"}}class _g extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const kg=e=>void 0===globalThis.DOMException?new _g(e):new DOMException(e),Ig=e=>{const t=void 0===e.reason?kg("This operation was aborted."):e.reason;return t instanceof Error?t:kg(t)};function Rg(e,t){const{milliseconds:r,fallback:n,message:s,customTimers:o={setTimeout,clearTimeout}}=t;let i;const a=new Promise(((a,c)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&c(Ig(e)),e.addEventListener("abort",(()=>{c(Ig(e))}))}if(r===Number.POSITIVE_INFINITY)return void e.then(a,c);const l=new Ag;i=o.setTimeout.call(void 0,(()=>{if(n)try{a(n())}catch(e){c(e)}else"function"==typeof e.cancel&&e.cancel(),!1===s?a():s instanceof Error?c(s):(l.message=s??`Promise timed out after ${r} milliseconds`,c(l))}),r),(async()=>{try{a(await e)}catch(e){c(e)}})()})).finally((()=>{a.clear()}));return a.clear=()=>{o.clearTimeout.call(void 0,i),i=void 0},a}class Tg{#o=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,run:e};if(this.size&&this.#o[this.size-1].priority>=t.priority)return void this.#o.push(r);const n=function(e,t){let r=0,n=e.length;for(;n>0;){const o=Math.trunc(n/2);let i=r+o;s=e[i],t.priority-s.priority<=0?(r=++i,n-=o+1):n=o}var s;return r}(this.#o,r);this.#o.splice(n,0,r)}dequeue(){const e=this.#o.shift();return e?.run}filter(e){return this.#o.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#o.length}}class Cg extends Sg{#i;#a;#c=0;#l;#u;#h=0;#d;#p;#o;#f;#g=0;#y;#m;#b;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Tg,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#a=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#l=e.intervalCap,this.#u=e.interval,this.#o=new e.queueClass,this.#f=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#b=!0===e.throwOnTimeout,this.#m=!1===e.autoStart}get#w(){return this.#a||this.#c{this.#A()}),t)),!0;this.#c=this.#i?this.#g:0}return!1}#S(){if(0===this.#o.size)return this.#d&&clearInterval(this.#d),this.#d=void 0,this.emit("empty"),0===this.#g&&this.emit("idle"),!1;if(!this.#m){const e=!this.#I;if(this.#w&&this.#v){const t=this.#o.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#k(),!0)}}return!1}#k(){this.#a||void 0!==this.#d||(this.#d=setInterval((()=>{this.#_()}),this.#u),this.#h=Date.now()+this.#u)}#_(){0===this.#c&&0===this.#g&&this.#d&&(clearInterval(this.#d),this.#d=void 0),this.#c=this.#i?this.#g:0,this.#R()}#R(){for(;this.#S(););}get concurrency(){return this.#y}set concurrency(e){if(!("number"==typeof e&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#y=e,this.#R()}async#T(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:this.#b,...t},new Promise(((r,n)=>{this.#o.enqueue((async()=>{this.#g++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Rg(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#T(t.signal)]));const s=await n;r(s),this.emit("completed",s)}catch(e){if(e instanceof Ag&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#E()}}),t),this.emit("add"),this.#S()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#m?(this.#m=!1,this.#R(),this):this}pause(){this.#m=!0}clear(){this.#o=new this.#f}async onEmpty(){0!==this.#o.size&&await this.#C("empty")}async onSizeLessThan(e){this.#o.sizethis.#o.size{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#o.size}sizeBy(e){return this.#o.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#m}}const Ng={},xg=e=>{e.addEventListener("message",(t=>{xg.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{xg.dispatchEvent("message",e,t)}))};xg.addEventListener=(e,t)=>{null==Ng[e]&&(Ng[e]=[]),Ng[e].push(t)},xg.removeEventListener=(e,t)=>{null!=Ng[e]&&(Ng[e]=Ng[e].filter((e=>e===t)))},xg.dispatchEvent=function(e,t,r){null!=Ng[e]&&Ng[e].forEach((e=>e(t,r)))};const Pg=xg,Og="lock:worker:request-read",Lg="lock:worker:release-read",Dg="lock:master:grant-read",Bg="lock:worker:request-write",Ug="lock:worker:release-write",Mg="lock:master:grant-write",Fg=(e,t,r,n,s)=>(o,i)=>{if(i.data.type!==r)return;const a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{o.postMessage({type:s,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r||null==r.data)return;const s=r.data.type,i=(r.data.name,r.data.identifier);s===n&&i===a.identifier&&(o.removeEventListener("message",t),e())};o.addEventListener("message",t)}))}}}))},$g=(e,t,r,n)=>async()=>{const s=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:s,name:e}),new Promise((t=>{const o=i=>{if(null==i||null==i.data)return;const a=i.data.type,c=i.data.identifier;a===r&&c===s&&(globalThis.removeEventListener("message",o),t((()=>{globalThis.postMessage({type:n,identifier:s,name:e})})))};globalThis.addEventListener("message",o)}))},Hg={singleProcess:!1},qg={};let Vg;async function jg(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Rg((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const Kg={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};const zg="ERR_INVALID_PARAMETERS";var Gg,Wg,Yg;function Jg(e,t){const r=Gg.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=function(e){if("RSA"===e.type)return new eh(e);if("Ed25519"===e.type)return new th(e);if("secp256k1"===e.type)return new rh(e);throw new Zo("Not a PeerId","ERR_INVALID_PARAMETERS")}({...e,publicKey:e.publicKey}));const n=new Map,s=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry({multiaddr:_o(e),isCertified:t??!1}))),metadata:r.metadata,peerRecordEnvelope:r.peerRecordEnvelope??void 0,tags:n}}!function(e){let t,r,n;!function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:"",value:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(t=e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),Yg.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={key:""},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.key=e.string();break;case 2:r.value=Yg.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(r=e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==n&&(n=Ar(((t,r,n={})=>{if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(const e of t.addresses)r.uint32(10),Wg.codec().encode(e,r);if(null!=t.protocols)for(const e of t.protocols)r.uint32(18),r.string(e);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(const[n,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,s]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:s},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{const n={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:n.addresses.push(Wg.codec().decode(t,t.uint32()));break;case 2:n.protocols.push(t.string());break;case 4:n.publicKey=t.bytes();break;case 5:n.peerRecordEnvelope=t.bytes();break;case 6:{const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());n.metadata.set(r.key,r.value);break}case 7:{const r=e.Peer$tagsEntry.codec().decode(t,t.uint32());n.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return n}))),n),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Gg||(Gg={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={multiaddr:new Uint8Array(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Wg||(Wg={})),function(e){let t;e.codec=()=>(null==t&&(t=Ar(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={value:0},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>jt(t,e.codec()),e.decode=t=>Y(t,e.codec())}(Yg||(Yg={}));const Xg="/",Qg=(new TextEncoder).encode(Xg),Zg=Qg[0];class ey{_buf;constructor(e,t){if("string"==typeof e)this._buf=Nt(e);else{if(!(e instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=e}if(null==t&&(t=!0),t&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Zg)throw new Error("Invalid key")}toString(e="utf8"){return nn(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new ey(e.join(Xg))}static random(){return new ey(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new ey(e):"function"==typeof e.uint8Array?new ey(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Qg),this._buf[0]!==Zg){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Zg,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Zg;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;es)return!1}return t.lengthe.namespaces())),[].concat(...t))]);var t}}const ty="/peers/";function ry(e){if(!js(e)||null==e.type)throw new Zo("Invalid PeerId",zg);const t=e.toCID().toString();return new ey(`${ty}${t}`)}async function ny(e,t,r){const n=new Map;for(const s of r){if(null==s)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=_o(s.multiaddr)),!Ao(s.multiaddr))throw new Zo("Multiaddr was invalid",zg);if(!await t(e,s.multiaddr))continue;const r=s.isCertified??!1,o=s.multiaddr.toString(),i=n.get(o);null!=i?s.isCertified=i.isCertified||r:n.set(o,{multiaddr:s.multiaddr,isCertified:r})}return[...n.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((({isCertified:e,multiaddr:t})=>({isCertified:e,multiaddr:t.bytes})))}async function sy(e,t,r,n){if(null==t)throw new Zo("Invalid PeerData",zg);if(null!=t.publicKey&&null!=e.publicKey&&!Nn(t.publicKey,e.publicKey))throw new Zo("publicKey bytes do not match peer id publicKey bytes",zg);const s=n.existingPeer;if(null!=s&&!e.equals(s.id))throw new Zo("peer id did not match existing peer id",zg);let o=s?.addresses??[],i=new Set(s?.protocols??[]),a=s?.metadata??new Map,c=s?.tags??new Map,l=s?.peerRecordEnvelope;if("patch"===r&&(null==t.multiaddrs&&null==t.addresses||(o=[],null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses)),null!=t.protocols&&(i=new Set(t.protocols)),null!=t.metadata&&(a=oy(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:iy})),null!=t.tags&&(c=oy(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:ay,map:cy})),null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)),"merge"===r){if(null!=t.multiaddrs&&o.push(...t.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=t.addresses&&o.push(...t.addresses),null!=t.protocols&&(i=new Set([...i,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?a.delete(t):a.set(t,r);a=oy([...a.entries()],{validate:iy})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(c);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);c=oy([...r.entries()],{validate:ay,map:cy})}null!=t.peerRecordEnvelope&&(l=t.peerRecordEnvelope)}const u={addresses:await ny(e,n.addressFilter??(async()=>!0),o),protocols:[...i.values()].sort(((e,t)=>e.localeCompare(t))),metadata:a,tags:c,publicKey:s?.id.publicKey??t.publicKey??e.publicKey,peerRecordEnvelope:l};return"RSA"!==e.type&&delete u.publicKey,u}function oy(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,s]of e.sort((([e],[t])=>e.localeCompare(t))))null!=s&&r.set(n,t.map?.(n,s)??s);return r}function iy(e,t){if("string"!=typeof e)throw new Zo("Metadata key must be a string",zg);if(!(t instanceof Uint8Array))throw new Zo("Metadata value must be a Uint8Array",zg)}function ay(e,t){if("string"!=typeof e)throw new Zo("Tag name must be a string",zg);if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Zo("Tag value must be an integer",zg);if(t.value<0||t.value>100)throw new Zo("Tag value must be between 0-100",zg)}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Zo("Tag ttl must be an integer",zg);if(t.ttl<0)throw new Zo("Tag ttl must be between greater than 0",zg)}}function cy(e,t){let r;return null!=t.expiry&&(r=t.expiry),null!=t.ttl&&(r=BigInt(Date.now()+Number(t.ttl))),{value:t.value??0,expiry:r}}function ly(e,t,r){const n=e.toString().split("/")[2],s=ih(fe.decode(n)),o=r.get(s);if(null!=o)return o;const i=Jg(s,t);return r.set(s,i),i}class uy{peerId;datastore;lock;addressFilter;constructor(e,t={}){this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},Kg,e);return null==Vg&&(Vg=(e=>{if(e=Object.assign({},Hg,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return Pg.addEventListener("message",Fg(e,"requestReadLock",Og,Lg,Dg)),Pg.addEventListener("message",Fg(e,"requestWriteLock",Bg,Ug,Mg)),e}return{isWorker:!0,readLock:e=>$g(e,Og,Dg,Lg),writeLock:e=>$g(e,Bg,Mg,Ug)}})(t),!0!==Vg.isWorker&&(Vg.addEventListener("requestReadLock",(e=>{null!=qg[e.data.name]&&qg[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),Vg.addEventListener("requestWriteLock",(async e=>{null!=qg[e.data.name]&&qg[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==qg[t.name]&&(qg[t.name]=((e,t)=>{if(!0===Vg.isWorker)return{readLock:Vg.readLock(e,t),writeLock:Vg.writeLock(e,t)};const r=new Cg({concurrency:1});let n;return{async readLock(){if(null!=n)return jg(n,t);n=new Cg({concurrency:t.concurrency,autoStart:!1});const e=n,s=jg(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),s},writeLock:async()=>(n=null,jg(r,t))}})(t.name,t)),qg[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(ry(e))}async delete(e){if(this.peerId.equals(e))throw new Zo("Cannot delete self peer",zg);await this.datastore.delete(ry(e))}async load(e){return Jg(e,await this.datastore.get(ry(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"patch",{addressFilter:this.addressFilter});return this.#x(e,s,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#x(e,s,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#N(e),s=await sy(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#x(e,s,r,n)}async*all(e){const t=new Eg;for await(const{key:r,value:n}of this.datastore.query(function(e,t){return null==e?{}:{prefix:ty,filters:(e.filters??[]).map((e=>({key:r,value:n})=>e(ly(r,n,t)))),orders:(e.orders??[]).map((e=>(r,n)=>e(ly(r.key,r.value,t),ly(n.key,n.value,t))))}}(e??{},t))){const e=ly(r,n,t);e.id.equals(this.peerId)||(yield e)}}async#N(e){try{const t=await this.datastore.get(ry(e));return{existingBuf:t,existingPeer:Jg(e,t)}}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}return{}}async#x(e,t,r,n){const s=Gg.encode(t);return null!=r&&Nn(s,r)?{peer:Jg(e,s),previous:n,updated:!1}:(await this.datastore.put(ry(e),s),{peer:Jg(e,s),previous:n,updated:!0})}}class hy{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new uy(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const r of this.store.all(t))e(r)}finally{this.log.trace("forEach release read lock"),r()}}async all(e){this.log.trace("all await read lock");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await Tn(this.store.all(e))}finally{this.log.trace("all release read lock"),t()}}async delete(e){this.log.trace("delete await write lock");const t=await this.store.lock.writeLock();this.log.trace("delete got write lock");try{await this.store.delete(e)}finally{this.log.trace("delete release write lock"),t()}}async has(e){this.log.trace("has await read lock");const t=await this.store.lock.readLock();this.log.trace("has got read lock");try{return await this.store.has(e)}finally{this.log.trace("has release read lock"),t()}}async get(e){this.log.trace("get await read lock");const t=await this.store.lock.readLock();this.log.trace("get got read lock");try{return await this.store.load(e)}finally{this.log.trace("get release read lock"),t()}}async save(e,t){this.log.trace("save await write lock");const r=await this.store.lock.writeLock();this.log.trace("save got write lock");try{const r=await this.store.save(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("save release write lock"),r()}}async patch(e,t){this.log.trace("patch await write lock");const r=await this.store.lock.writeLock();this.log.trace("patch got write lock");try{const r=await this.store.patch(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("patch release write lock"),r()}}async merge(e,t){this.log.trace("merge await write lock");const r=await this.store.lock.writeLock();this.log.trace("merge got write lock");try{const r=await this.store.merge(e,t);return this.#P(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){const r=await lp.openAndCertify(e,ap.DOMAIN);if(!1===t?.equals(r.peerId))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,r.peerId),!1;const n=ap.createFromProtobuf(r.payload);let s;try{s=await this.get(r.peerId)}catch(e){if("ERR_NOT_FOUND"!==e.code)throw e}if(null!=s?.peerRecordEnvelope){const e=await lp.createFromProtobuf(s.peerRecordEnvelope),t=ap.createFromProtobuf(e.payload);if(t.seqNumber>=n.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,n.seqNumber),!1}return await this.patch(n.peerId,{peerRecordEnvelope:e,addresses:n.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}#P(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}const dy=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},py=function(e,t){let r=0;if(null!=e[Symbol.asyncIterator])return async function*(){for await(const n of e)await t(n,r++)&&(yield n)}();const n=function(e){const[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}(e),{value:s,done:o}=n.next();if(!0===o)return function*(){}();const i=t(s,r++);if("function"==typeof i.then)return async function*(){await i&&(yield s);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===i&&(yield s);for(const e of n)a(e,r++)&&(yield e)}()},fy=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await Tn(e);yield*r.sort(t)}():function*(){const r=Tn(e);yield*r.sort(t)}()},gy=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){let r=0;if(!(t<1))for await(const n of e)if(yield n,r++,r===t)return}():function*(){let r=0;if(!(t<1))for(const n of e)if(yield n,r++,r===t)return}()};class yy{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(const{key:r,value:n}of e)await this.put(r,n,t),yield r}async*getMany(e,t={}){for await(const r of e)yield{key:r,value:await this.get(r,t)}}async*deleteMany(e,t={}){for await(const r of e)await this.delete(r,t),yield r}batch(){let e=[],t=[];return{put(t,r){e.push({key:t,value:r})},delete(e){t.push(e)},commit:async r=>{await dy(this.putMany(e,r)),e=[],await dy(this.deleteMany(t,r)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let r=this._all(e,t);if(null!=e.prefix){const t=e.prefix;r=py(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>py(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>fy(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=py(r,(()=>t++>=n))}return null!=e.limit&&(r=gy(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=py(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>py(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>fy(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=py(r,(()=>n++>=t))}return null!=e.limit&&(r=gy(r,e.limit)),r}}var my=__webpack_require__(6310);class by extends yy{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw r=r??new Error("Not Found"),my(r,"ERR_NOT_FOUND");var r;return t}has(e){return this.data.has(e.toString())}delete(e){this.data.delete(e.toString())}*_all(){for(const[e,t]of this.data.entries())yield{key:new ey(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new ey(e)}}const wy=e=>e;function vy(e,t){const r=e.getPeerId();return null!=r&&oh(r).equals(t)&&(e=e.decapsulate(_o(`/p2p/${t.toString()}`))),e}class Ey{log;components;listen;announce;observed;announceFilter;constructor(e,t={}){const{listen:r=[],announce:n=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=r.map((e=>e.toString())),this.announce=new Set(n.map((e=>e.toString()))),this.observed=new Map,this.announceFilter=t.announceFilter??wy,this._updatePeerStoreAddresses=function(e){let t;return function(){clearTimeout(t),t=setTimeout((function(){t=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>_o(e)))).map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate(`/p2p/${this.components.peerId.toString()}`):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>_o(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>_o(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>_o(e)))}addObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString(),r=(this.observed.get(t)??{confident:!1}).confident;this.observed.set(t,{confident:!0}),r||this._updatePeerStoreAddresses()}removeObservedAddr(e){const t=(e=vy(e,this.components.peerId)).toString();this.observed.delete(t)}getAddresses(){let e=this.getAnnounceAddrs().map((e=>e.toString()));0===e.length&&(e=this.components.transportManager.getAddrs().map((e=>e.toString()))),e=e.concat(Array.from(this.observed).filter((([e,t])=>t.confident)).map((([e])=>e)));const t=new Set(e);return this.announceFilter(Array.from(t).map((e=>_o(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}class Sy{components={};_started=!1;constructor(e={}){this.components={};for(const[t,r]of Object.entries(e))this.components[t]=r;null==this.components.logger&&(this.components.logger=yg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>function(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}(e))).map((async t=>{await(t[e]?.())})))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}}const Ay=["metrics","connectionProtector","dns"],_y=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function ky(e){return Array.isArray(e?.[Yu])?e[Yu]:[]}function Iy(e){return Array.isArray(e?.[Ju])?e[Ju]:[]}function Ry(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}var Ty=__webpack_require__(5507);const Cy=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new Ty.Netmask(e)));function Ny(e){for(const t of Cy)if(t.contains(e))return!0;return!1}function xy(e){return zs(e)?Ny(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return Ny(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return Ny(t[t.length-1])}(e):Gs(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function Py(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(xy(`${t[0][1]}`))},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...e}}function Oy(e){try{const{address:t}=e.nodeAddress();return Boolean(xy(t))}catch{return!0}}function Ly(e,t){const r=function(e,t){const r=Oy(e.multiaddr),n=Oy(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==r)return r;const n=function(e,t){const r=Hp.exactMatch(e.multiaddr),n=Hp.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}(e,t);if(0!==n)return n;const s=function(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}(e,t);return s}function Dy(e){const t=[My.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function By(e){return{Status:e.Status??0,TC:e.TC??e.flag_tc??!1,RD:e.RD??e.flag_rd??!1,RA:e.RA??e.flag_ra??!1,AD:e.AD??e.flag_ad??!1,CD:e.CD??e.flag_cd??!1,Question:(e.Question??e.questions??[]).map((e=>({name:e.name,type:My[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:My[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?nn(e.data):e.data})))}}function Uy(e,t={}){const r=new Cg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const s=new URLSearchParams;s.set("name",t),Dy(n.types).forEach((e=>{s.append("type",My[e])})),n.onProgress?.(new Qf("dns:query",{detail:t}));const o=await r.add((async()=>{const t=await fetch(`${e}?${s}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=By(await t.json());return n.onProgress?.(new Qf("dns:response",{detail:r})),r}),{signal:n.signal});if(null==o)throw new Error("No DNS response received");return o}}var My,Fy=__webpack_require__(194);class $y{lru;constructor(e){this.lru=Fy(e)}get(e,t){let r=!0;const n=[];for(const s of t){const t=this.getAnswers(e,s);if(0===t.length){r=!1;break}n.push(...t)}if(r)return By({answers:n})}getAnswers(e,t){const r=`${e.toLowerCase()}-${t}`,n=this.lru.get(r);if(null!=n){const e=n.filter((e=>e.expires>Date.now())).map((({expires:e,value:t})=>({...t,TTL:Math.round((e-Date.now())/1e3),type:My[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Hy{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new $y(t)),Object.entries(e.resolvers??{}).forEach((([e,t])=>{Array.isArray(t)||(t=[t]),e.endsWith(".")||(e=`${e}.`),this.resolvers[e]=t})),null==this.resolvers["."]&&(this.resolvers["."]=[Uy("https://cloudflare-dns.com/dns-query"),Uy("https://dns.google/resolve")])}async query(e,t={}){const r=Dy(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new Qf("dns:cache",{detail:n})),n;const s=`${e.split(".").pop()}.`,o=(this.resolvers[s]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),i=[];for(const n of o){if(!0===t.signal?.aborted)break;try{const s=await n(e,{...t,types:r});for(const t of s.Answer)this.cache.add(e,t);return s}catch(e){i.push(e),t.onProgress?.(new Qf("dns:error",{detail:e}))}}if(1===i.length)throw i[0];throw new AggregateError(i,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(My||(My={}));const{code:qy}=to("dnsaddr");class Vy extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const jy=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Vy("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===qy))??[],s=t?.dns??function(e={}){return new Hy(e)}(),o=await s.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[My.TXT]}),i=e.getPeerId(),a=[];for(const e of o.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=i&&!n.includes(i))continue;const s=_o(n);if(n.startsWith("/dnsaddr")){const e=await s.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(s.toString())}return a},Ky=__webpack_require__(6864);var zy,Gy;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.ERR_PROTECTOR_REQUIRED="Private network is enforced, but no protector was provided",e.NOT_FOUND="Not found"}(zy||(zy={})),function(e){e.ERR_PROTECTOR_REQUIRED="ERR_PROTECTOR_REQUIRED",e.ERR_PEER_DIAL_INTERCEPTED="ERR_PEER_DIAL_INTERCEPTED",e.ERR_CONNECTION_INTERCEPTED="ERR_CONNECTION_INTERCEPTED",e.ERR_INVALID_PROTOCOLS_FOR_STREAM="ERR_INVALID_PROTOCOLS_FOR_STREAM",e.ERR_CONNECTION_ENDED="ERR_CONNECTION_ENDED",e.ERR_CONNECTION_FAILED="ERR_CONNECTION_FAILED",e.ERR_NODE_NOT_STARTED="ERR_NODE_NOT_STARTED",e.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",e.ERR_TOO_MANY_ADDRESSES="ERR_TOO_MANY_ADDRESSES",e.ERR_NO_VALID_ADDRESSES="ERR_NO_VALID_ADDRESSES",e.ERR_RELAYED_DIAL="ERR_RELAYED_DIAL",e.ERR_DIALED_SELF="ERR_DIALED_SELF",e.ERR_DISCOVERED_SELF="ERR_DISCOVERED_SELF",e.ERR_DUPLICATE_TRANSPORT="ERR_DUPLICATE_TRANSPORT",e.ERR_ENCRYPTION_FAILED="ERR_ENCRYPTION_FAILED",e.ERR_HOP_REQUEST_FAILED="ERR_HOP_REQUEST_FAILED",e.ERR_INVALID_KEY="ERR_INVALID_KEY",e.ERR_INVALID_MESSAGE="ERR_INVALID_MESSAGE",e.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",e.ERR_INVALID_PEER="ERR_INVALID_PEER",e.ERR_MUXER_UNAVAILABLE="ERR_MUXER_UNAVAILABLE",e.ERR_NOT_FOUND="ERR_NOT_FOUND",e.ERR_TRANSPORT_UNAVAILABLE="ERR_TRANSPORT_UNAVAILABLE",e.ERR_TRANSPORT_DIAL_FAILED="ERR_TRANSPORT_DIAL_FAILED",e.ERR_UNSUPPORTED_PROTOCOL="ERR_UNSUPPORTED_PROTOCOL",e.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED="ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED",e.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",e.ERR_SIGNATURE_NOT_VALID="ERR_SIGNATURE_NOT_VALID",e.ERR_FIND_SELF="ERR_FIND_SELF",e.ERR_NO_ROUTERS_AVAILABLE="ERR_NO_ROUTERS_AVAILABLE",e.ERR_CONNECTION_NOT_MULTIPLEXED="ERR_CONNECTION_NOT_MULTIPLEXED",e.ERR_NO_DIAL_TOKENS="ERR_NO_DIAL_TOKENS",e.ERR_INVALID_CMS="ERR_INVALID_CMS",e.ERR_MISSING_KEYS="ERR_MISSING_KEYS",e.ERR_NO_KEY="ERR_NO_KEY",e.ERR_INVALID_KEY_NAME="ERR_INVALID_KEY_NAME",e.ERR_INVALID_KEY_TYPE="ERR_INVALID_KEY_TYPE",e.ERR_KEY_ALREADY_EXISTS="ERR_KEY_ALREADY_EXISTS",e.ERR_INVALID_KEY_SIZE="ERR_INVALID_KEY_SIZE",e.ERR_KEY_NOT_FOUND="ERR_KEY_NOT_FOUND",e.ERR_OLD_KEY_NAME_INVALID="ERR_OLD_KEY_NAME_INVALID",e.ERR_NEW_KEY_NAME_INVALID="ERR_NEW_KEY_NAME_INVALID",e.ERR_PASSWORD_REQUIRED="ERR_PASSWORD_REQUIRED",e.ERR_PEM_REQUIRED="ERR_PEM_REQUIRED",e.ERR_CANNOT_READ_KEY="ERR_CANNOT_READ_KEY",e.ERR_MISSING_PRIVATE_KEY="ERR_MISSING_PRIVATE_KEY",e.ERR_MISSING_PUBLIC_KEY="ERR_MISSING_PUBLIC_KEY",e.ERR_INVALID_OLD_PASS_TYPE="ERR_INVALID_OLD_PASS_TYPE",e.ERR_INVALID_NEW_PASS_TYPE="ERR_INVALID_NEW_PASS_TYPE",e.ERR_INVALID_PASS_LENGTH="ERR_INVALID_PASS_LENGTH",e.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",e.ERR_WRONG_PING_ACK="ERR_WRONG_PING_ACK",e.ERR_INVALID_RECORD="ERR_INVALID_RECORD",e.ERR_ALREADY_SUCCEEDED="ERR_ALREADY_SUCCEEDED",e.ERR_NO_HANDLER_FOR_PROTOCOL="ERR_NO_HANDLER_FOR_PROTOCOL",e.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS",e.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",e.ERR_CONNECTION_DENIED="ERR_CONNECTION_DENIED",e.ERR_TRANSFER_LIMIT_EXCEEDED="ERR_TRANSFER_LIMIT_EXCEEDED"}(Gy||(Gy={}));const Wy={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:jy},addressSorter:Ly},transportManager:{faultTolerance:Ff.FATAL_ALL}};function Yy(e){if(js(e))return{peerId:e,multiaddrs:[]};let t;if(Array.isArray(e)||(e=[e]),e.length>0){const r=e[0].getPeerId();t=null==r?void 0:oh(r),e.forEach((e=>{if(!Ao(e))throw new Zo("Invalid Multiaddr",Gy.ERR_INVALID_MULTIADDR);const r=e.getPeerId();if(null==r){if(null!=t)throw new Zo("Multiaddrs must all have the same peer id or have no peer id",Gy.ERR_INVALID_PARAMETERS)}else{const e=oh(r);if(!0!==t?.equals(e))throw new Zo("Multiaddrs must all have the same peer id or have no peer id",Gy.ERR_INVALID_PARAMETERS)}}))}return{peerId:t,multiaddrs:e}}class Jy extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.name="AbortError",this.code=t??"ABORT_ERR"}}async function Xy(e,t,r,n){const s=new Jy(n?.errorMessage,n?.errorCode);return!0===r?.aborted?Promise.reject(s):new Promise(((o,i)=>{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void i(e)}a(),o(e)},l=e=>{a(),i(e.detail)},u=()=>{a(),i(s)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Qy{deferred;signal;constructor(e){this.signal=e,this.deferred=Kn(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Qo)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class Zy{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=`${parseInt(String(1e9*Math.random()),10).toString()}${Date.now()}`,this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce(((e,t)=>e&&!0===t.signal?.aborted),!0)&&(this.controller.abort(new Qo),this.cleanup())}async join(e={}){const t=new Qy(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();const e=await lh(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach((t=>{t.deferred.resolve(e)})),this.status="complete"}catch(e){this.recipients.forEach((t=>{t.deferred.reject(e)})),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach((e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)}))}}class em extends xs{concurrency;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.pending=0,null!=e.metricName&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[]}tryToStartAnother(){if(0===this.size)return queueMicrotask((()=>{this.safeDispatchEvent("empty")})),0===this.running&&queueMicrotask((()=>{this.safeDispatchEvent("idle")})),!1;if(this.pending{for(let t=0;t(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{e.abort(new Qo)})),this.clear()}async onEmpty(e){0!==this.size&&await Xy(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.sizethis.size{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},s=e=>{r(e.detail)},o=()=>{r()},i=()=>{r(new Zo("Queue aborted","ERR_QUEUE_ABORTED"))};this.addEventListener("completed",n),this.addEventListener("error",s),this.addEventListener("idle",o),e?.signal?.addEventListener("abort",i);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",s),this.removeEventListener("idle",o),e?.signal?.removeEventListener("abort",i),r()}}}class tm extends em{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}const rm=42e4,nm="last-dial-failure",sm=5,om=100,im=25,am=0,cm=5e3,lm=rm,um=10;class hm{connectionManager;peerStore;queue;minConnections;autoDialPriority;autoDialIntervalMs;autoDialMaxQueueLength;autoDialPeerRetryThresholdMs;autoDialDiscoveredPeersDebounce;autoDialInterval;started;running;log;constructor(e,t){let r;this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.minConnections=t.minConnections??sm,this.autoDialPriority=t.autoDialPriority??am,this.autoDialIntervalMs=t.autoDialInterval??cm,this.autoDialMaxQueueLength=t.maxQueueLength??om,this.autoDialPeerRetryThresholdMs=t.autoDialPeerRetryThreshold??lm,this.autoDialDiscoveredPeersDebounce=t.autoDialDiscoveredPeersDebounce??um,this.log=e.logger.forComponent("libp2p:connection-manager:auto-dial"),this.started=!1,this.running=!1,this.queue=new tm({concurrency:t.autoDialConcurrency??im,metricName:"libp2p_autodial_queue",metrics:e.metrics}),this.queue.addEventListener("error",(e=>{this.log.error("error during auto-dial",e.detail)})),e.events.addEventListener("connection:close",(()=>{this.autoDial().catch((e=>{this.log.error(e)}))})),e.events.addEventListener("peer:discovery",(()=>{clearTimeout(r),r=setTimeout((()=>{this.autoDial().catch((e=>{this.log.error(e)}))}),this.autoDialDiscoveredPeersDebounce)}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){this.autoDial().catch((e=>{this.log.error("error while autodialing",e)}))}stop(){this.queue.clear(),clearTimeout(this.autoDialInterval),this.started=!1,this.running=!1}async autoDial(){if(!this.started||this.running)return;const e=this.connectionManager.getConnectionsMap(),t=e.size;if(t>=this.minConnections)return void(this.minConnections>0&&this.log.trace("have enough connections %d/%d",t,this.minConnections));if(this.queue.size>this.autoDialMaxQueueLength)return this.log("not enough connections %d/%d but auto dial queue is full",t,this.minConnections),void this.sheduleNextAutodial();this.running=!0,this.log("not enough connections %d/%d - will dial peers to increase the number of connections",t,this.minConnections);const r=new bg(this.connectionManager.getDialQueue().map((e=>e.peerId)).filter(Boolean)),n=await this.peerStore.all({filters:[t=>0===t.addresses.length?(this.log.trace("not autodialing %p because they have no addresses",t.id),!1):e.has(t.id)?(this.log.trace("not autodialing %p because they are already connected",t.id),!1):r.has(t.id)?(this.log.trace("not autodialing %p because they are already being dialed",t.id),!1):!this.queue.has(t.id)||(this.log.trace("not autodialing %p because they are already being autodialed",t.id),!1)]}),s=n.sort((()=>Math.random()>.5?1:-1)),o=new Eg;for(const e of s)o.has(e.id)||o.set(e.id,[...e.tags.values()].reduce(((e,t)=>e+t.value),0));const i=s.sort(((e,t)=>{const r=o.get(e.id)??0,n=o.get(t.id)??0;return r>n?-1:r{const t=e.metadata.get(nm);if(null==t)return!0;const r=parseInt(nn(t));return!!isNaN(r)||Date.now()-r>this.autoDialPeerRetryThresholdMs}));this.log("selected %d/%d peers to dial",i.length,n.length);for(const e of i)this.queue.add((async()=>{const t=this.connectionManager.getConnectionsMap().size;if(t>=this.minConnections)return this.log("got enough connections now %d/%d",t,this.minConnections),void this.queue.clear();this.log("connecting to a peerStore stored peer %p",e.id),await this.connectionManager.openConnection(e.id,{priority:this.autoDialPriority})}),{peerId:e.id}).catch((e=>{this.log.error("could not connect to peerStore stored peer",e)}));this.running=!1,this.sheduleNextAutodial()}sheduleNextAutodial(){this.started&&(this.autoDialInterval=setTimeout((()=>{this.autoDial().catch((e=>{this.log.error("error while autodialing",e)}))}),this.autoDialIntervalMs))}}const dm=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],pm={maxConnections:100,allow:[]};class fm{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??pm.maxConnections,this.allow=t.allow??pm.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),e.events.addEventListener("connection:open",(()=>{this.maybePruneConnections().catch((e=>{this.log.error(e)}))}))}async maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new Eg;for(const t of e){const e=t.remotePeer;if(!r.has(e)){r.set(e,0);try{const t=await this.peerStore.get(e);r.set(e,[...t.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"ERR_NOT_FOUND"!==e.code&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),s=Math.max(t-this.maxConnections,0),o=[];for(const e of n)if(this.log("too many connections open - closing a connection to %p",e.remotePeer),this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString())))||o.push(e),o.length===s)break;await Promise.all(o.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??dm;if(!(r.filter((e=>null!=e&&!n.includes(e))).length>0))try{await(e?.close(t))}catch(t){e?.abort(t)}}(e,{signal:AbortSignal.timeout(1e3)})}))),this.events.safeDispatchEvent("connection:prune",{detail:o})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return rn?-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{const n=t.get(e.remotePeer)??0,s=t.get(r.remotePeer)??0;return n>s?1:ne.options.priority>t.options.priority?-1:e.options.priority{this.log.error("error in dial queue",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=Yy(e),s=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if(null!=s)return this.log("already connected to %a",s.remoteAddr),t.onProgress?.(new Qf("dial-queue:already-connected")),s;const o=this.queue.queue.find((e=>{if(!0===r?.equals(e.options.peerId))return!0;const t=e.options.multiaddrs;if(null==t)return!1;for(const e of n)if(t.has(e.toString()))return!0;return!1}));if(null!=o){this.log("joining existing dial target for %p",r);for(const e of n)o.options.multiaddrs.add(e.toString());return t.onProgress?.(new Qf("dial-queue:already-in-dial-queue")),o.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Zo("Dial queue is full","ERR_DIAL_QUEUE_FULL");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new Qf("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e?.onProgress?.(new Qf("dial-queue:start-dial"));const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),e?.onProgress?.(new Qf("dial-queue:calculated-addresses",n)),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let s=0;const o=[];for(const i of n){if(s===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",s,r),new Zo("Peer had more than maxPeerAddrsToDial",Gy.ERR_TOO_MANY_ADDRESSES);s++;try{const r=await this.components.transportManager.dial(i.multiaddr,{...e,signal:t});return this.log("dial to %a succeeded",i.multiaddr),r}catch(e){if(this.log.error("dial failed to %a",i.multiaddr,e),null!=r)try{await this.components.peerStore.patch(r,{metadata:{[nm]:Nt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new Zo(e.message,ti);o.push(e)}}if(1===o.length)throw o[0];throw new ei(o,"All multiaddr dials failed",Gy.ERR_TRANSPORT_DIAL_FAILED)}finally{t.clear()}}),{peerId:r,priority:t.priority??wm,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){return ym([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:_o(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new Zo("Tried to dial self",Gy.ERR_DIALED_SELF);if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new Zo("The dial request is blocked by gater.allowDialPeer",Gy.ERR_PEER_DIAL_INTERCEPTED);if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if(e.code!==Gy.ERR_NOT_FOUND)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){t.code!==Gy.ERR_NO_ROUTERS_AVAILABLE&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let s=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of So.keys())if(r=e.protoNames().includes(t),r)break;if(!r)return[e];const n=await e.resolve(t);return t.log("resolved %s to",e,n.map((e=>e.toString()))),n}(e.multiaddr,{dns:this.components.dns,...r,log:this.log});return 1===t.length&&t[0].equals(e.multiaddr)?e:t.map((e=>({multiaddr:e,isCertified:!1})))})))).flat();if(null!=e){const t=`/p2p/${e.toString()}`;s=s.map((e=>{const r=e.multiaddr.protos().pop();return!0===r?.path?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(t),isCertified:e.isCertified}:e}))}const o=s.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),i=new Map;for(const e of o){const t=e.multiaddr.toString(),r=i.get(t);null==r?i.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...i.values()];if(0===a.length)throw new Zo("The dial request has no valid addresses",Gy.ERR_NO_VALID_ADDRESSES);const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=c.sort(this.addressSorter);if(0===l.length)throw new Zo("The connection gater denied all addresses in the dial request",Gy.ERR_NO_VALID_ADDRESSES);return this.log.trace("addresses for %p before filtering",e??"unknown peer",s.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnTransientConnection||null!=r.find((e=>!Hp.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const wm=50,vm=5,Em=100,Sm=5,Am=10,_m=25,km=0,Im=100,Rm=rm,Tm=10;class Cm{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;maxConnections;dialQueue;autoDial;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??Em;const r=t.minConnections??vm;if(this.maxConnections_o(e))),this.deny=(t.deny??[]).map((e=>_o(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??Am,this.inboundConnectionRateLimiter=new gf({points:t.inboundConnectionThreshold??Sm,duration:1}),this.autoDial=new hm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{minConnections:r,autoDialConcurrency:t.autoDialConcurrency??_m,autoDialPriority:t.autoDialPriority??km,autoDialPeerRetryThreshold:t.autoDialPeerRetryThreshold??Rm,autoDialDiscoveredPeersDebounce:t.autoDialDiscoveredPeersDebounce??Tm,maxQueueLength:t.autoDialMaxQueueLength??Im}),this.connectionPruner=new fm({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new bm(e,{addressSorter:t.addressSorter??Ly,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:jy},connections:this.connections})}[Symbol.toStringTag]="@libp2p/connection-manager";isStarted(){return this.started}async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,outbound:0};for(const t of this.connections.values())for(const r of t)"inbound"===r.direction?e.inbound++:e.outbound++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.dialQueue.start(),this.autoDial.start(),this.started=!0,this.log("started")}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>e.tags.has("keep-alive")]});await Promise.all(e.map((async e=>{await this.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)})),this.autoDial.afterStart()}async stop(){this.dialQueue.stop(),this.autoDial.stop();const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();const r=t.remotePeer,n=this.connections.get(r);let s=!1;null!=n?n.push(t):(s=!0,this.connections.set(r,[t])),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),s&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e;if(!this.started)return;const r=t.remotePeer;let n=this.connections.get(r);null!=n&&n.length>1?(n=n.filter((e=>e.id!==t.id)),this.connections.set(r,n)):null!=n&&(this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.isStarted())throw new Zo("Not started",Gy.ERR_NODE_NOT_STARTED);t.signal?.throwIfAborted();const{peerId:r}=Yy(e);if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>!e.transient));if(null!=e)return this.log("had an existing non-transient connection to %p",r),t.onProgress?.(new Qf("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??wm});let s=this.connections.get(n.remotePeer);null==s&&(s=[],this.connections.set(n.remotePeer,s));let o=!1;for(const e of s)e.id===n.id&&(o=!0);return o||s.push(n),n}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some((t=>e.remoteAddr.toString().startsWith(t.toString()))))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){const t=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(t,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,t),!1}}return this.getConnections().length({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>_o(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Nm{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,s=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*s),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class xm{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Nm(e.interval??5e3),this.failure=new Nm(e.interval??5e3),this.next=new Nm(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??2e3,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){const t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),r=AbortSignal.timeout(t),n=ym([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Pm{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.timeout=new xm({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Yu]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=fh(await e.newStream(this.protocol,{signal:r,runOnTransientConnection:!0}));t=Date.now(),await Promise.all([n.write(lu(32),{signal:r}),n.read(32,{signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("ERR_UNSUPPORTED_PROTOCOL"!==r.code)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat, aborting connection",t),e.abort(t)}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Om{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Zo("No content routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=new bg;for await(const s of Jn(...r.routers.map((r=>r.findProviders(e,t)))))null!=s&&(s.multiaddrs.length>0&&await this.components.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id)||(n.add(s.id),yield s))}async provide(e,t={}){if(0===this.routers.length)throw new Zo("No content routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);await Promise.all(this.routers.map((async r=>{await r.provide(e,t)})))}async put(e,t,r){if(!this.isStarted())throw new Zo(zy.NOT_STARTED_YET,Gy.ERR_NODE_NOT_STARTED);await Promise.all(this.routers.map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new Zo(zy.NOT_STARTED_YET,Gy.ERR_NODE_NOT_STARTED);return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class Lm{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const s=t.hashV(e,r),o=b(n);for(let e=0;ee.equals(t)))}add(e){if(!(e instanceof Lm))throw new TypeError("Invalid Fingerprint");for(let t=0;te.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const Um={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},Mm={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},Fm=new globalThis.TextEncoder;__webpack_require__(8437);const $m={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!Um[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");const n=Um[t];let s=Mm[t],o=e;for(;o.length>0;){const e=Fm.encodeInto(o,r);o=o.slice(e.read);for(let o=0;ofunction(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),Nt(t,"base16")}($m.hash(e,t))};class Hm{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??$m,this.seed=e.seed??Dm(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new Bm(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Bm(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const s=[r,n];let o=s[Dm(0,s.length-1)];null==this.buckets[o]&&(this.buckets[o]=new Bm(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[o].swap(t);if(null!=e&&(o=(o^e.hash())%this.filterSize,null==this.buckets[o]&&(this.buckets[o]=new Bm(this.bucketSize)),this.buckets[o].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.has(t)??!1;if(n)return n;const s=(r^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){"string"==typeof e&&(e=Nt(e));const t=new Lm(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=this.buckets[r]?.remove(t)??!1;if(n)return this.count--,n;const s=(r^t.hash())%this.filterSize,o=this.buckets[s]?.remove(t)??!1;return o&&this.count--,o}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const qm={1:.5,2:.84,4:.95,8:.98};function Vm(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=qm[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class jm{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??$m,this.seed=e.seed??Dm(0,Math.pow(2,10)),this.filterSeries=[new Hm({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=Nt(e)),this.has(e))return!0;let t=this.filterSeries.find((e=>e.reliable));if(null==t){const e=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Hm({filterSize:e,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=Nt(e));for(let t=0;te+t.count),0)}}const Km=globalThis.CustomEvent??Event;class zm{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Zo("No peer routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);if(e.toString()===this.peerId.toString())throw new Zo("Should not try to find self",Gy.ERR_FIND_SELF);const r=this,n=Jn(...this.routers.map((n=>async function*(){try{yield await n.findPeer(e,t)}catch(e){r.log.error(e)}}())));for await(const e of n)if(null!=e)return e.multiaddrs.length>0&&await this.peerStore.merge(e.id,{multiaddrs:e.multiaddrs}),e;throw new Zo(zy.NOT_FOUND,Gy.ERR_NOT_FOUND)}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Zo("No peer routers available",Gy.ERR_NO_ROUTERS_AVAILABLE);const r=this,n=function(e,t=.001,r){return new jm({...Vm(1024,t),...r??{}})}();for await(const s of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,s=new EventTarget,o=[];let i,a=Kn(),c=Kn(),l=!1,u=!1;function h(){return n?o[0]?.done:Boolean(o.find((e=>e.done)))}function*d(){for(;o.length>0&&o[0].done;){const e=o[0];if(o.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(o.length===r&&(a=Kn(),await a.promise),u)break;const e={done:!1};o.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,s.dispatchEvent(new Km("task-complete"))}),(t=>{e.done=!0,e.err=t,s.dispatchEvent(new Km("task-complete"))}))}l=!0,s.dispatchEvent(new Km("task-complete"))}catch(e){i=e,s.dispatchEvent(new Km("task-complete"))}}));;){if(h()||(c=Kn(),await c.promise),null!=i)throw i;if(n?yield*d():yield*p(),l&&0===o.length)break}}(async function*(){const n=Jn(...r.routers.map((r=>r.getClosestPeers(e,t))));for await(let e of n)yield async()=>{if(0===e.multiaddrs.length)try{e=await r.findPeer(e.id,{...t,useCache:!1})}catch(e){return void r.log.error("could not find peer multiaddrs",e)}return e}}()))null!=s&&(s.multiaddrs.length>0&&await this.peerStore.merge(s.id,{multiaddrs:s.multiaddrs}),n.has(s.id.toBytes())||(n.add(s.id.toBytes()),yield s))}}class Gm extends xs{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=ym([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=Kn();const e=await Xy(this,"walk:peer",t,{errorEvent:"walk:error"});yield e.detail}}finally{t.clear(),this.walkers--,0===this.walkers&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;const e=ym([this.walkController.signal,this.shutdownController.signal]),t=Date.now();let r=0;Promise.resolve().then((async()=>{for(this.log("start walk");this.walkers>0;)try{const t=lu(32);let n=Date.now();for await(const s of this.peerRouting.getClosestPeers(t,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:s}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await lh(this.needNext.promise,e)),n=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",t,this.walkers,r)}catch(e){this.log.error("randomwalk errored",e),this.safeDispatchEvent("walk:error",{detail:e})}this.log("no walkers left, ended walk")})).catch((e=>{this.log.error("randomwalk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",r,Date.now()-t),this.walking=!1}))}}class Wm{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new Zo(`No handler registered for protocol ${e}`,Gy.ERR_NO_HANDLER_FOR_PROTOCOL);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new Zo(`Handler already registered for protocol ${e}`,Gy.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);const n=Ky.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},r);this.handlers.set(e,{handler:t,options:n}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]})}async unhandle(e){(Array.isArray(e)?e:[e]).forEach((e=>{this.handlers.delete(e)})),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()})}async register(e,t){if(null==t)throw new Zo("invalid topology",Gy.ERR_INVALID_PARAMETERS);const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;this.components.peerStore.get(t).then((e=>{for(const r of e.protocols){const e=this.topologies.get(r);if(null!=e)for(const r of e.values())!1!==r.filter?.has(t)&&(r.filter?.remove(t),r.onDisconnect?.(t))}})).catch((e=>{e.code!==Gy.ERR_NOT_FOUND&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())r.transient&&!0!==e.notifyOnTransient||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class Ym extends Map{metric;constructor(e){super();const{name:t,metrics:r}=e;this.metric=r.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){const t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}class Jm{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=new Map,this.listeners=function(e){const{name:t,metrics:r}=e;let n;return n=null!=r?new Ym({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Ff.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Zo("Transport must have a valid tag",Gy.ERR_INVALID_KEY);if(this.transports.has(t))throw new Zo(`There is already a transport with the tag ${t}`,Gy.ERR_DUPLICATE_TRANSPORT);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new Zo(`No transport available for address ${String(e)}`,Gy.ERR_TRANSPORT_UNAVAILABLE);t?.onProgress?.(new Qf("transport-manager:selected-transport",r[Symbol.toStringTag]));try{return await r.dial(e,{...t,upgrader:this.components.upgrader})}catch(e){throw null==e.code&&(e.code=Gy.ERR_TRANSPORT_DIAL_FAILED),e}}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Zo("Not started",Gy.ERR_NODE_NOT_STARTED);if(null==e||0===e.length)return void this.log("no addresses were provided for listening, this node is dial only");const t=[];for(const[r,n]of this.transports.entries()){const s=n.listenFilter(e),o=[];for(const e of s){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let s=this.listeners.get(r)??[];null==s&&(s=[],this.listeners.set(r,s)),s.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=s.findIndex((e=>e===t));s.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),o.push(t.listen(e))}if(0!==o.length){if(null==(await Promise.allSettled(o)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==Ff.NO_FATAL)throw new Zo(`Transport (${r}) could not listen on any available address`,Gy.ERR_NO_VALID_ADDRESSES)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Ff.FATAL_ALL)throw new Zo(e,Gy.ERR_NO_VALID_ADDRESSES);this.log(`libp2p in dial mode only: ${e}`)}}async remove(e){const t=this.listeners.get(e)??[];this.log.trace("removing transport %s",e);const r=[];for(this.log.trace("closing listeners for %s",e);t.length>0;){const e=t.pop();null!=e&&r.push(e.close())}await Promise.all(r),this.transports.delete(e),this.listeners.delete(e)}async removeAll(){const e=[];for(const t of this.transports.keys())e.push(this.remove(t));await Promise.all(e)}}const Xm="/multistream/1.0.0",Qm=1024,Zm=Nt("\n");async function eb(e,t,r){await e.write(t,r)}async function tb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==Zm[0])throw t.log.error("Invalid mss message - missing newline",r),new Zo("missing newline","ERR_INVALID_MULTISTREAM_SELECT_MESSAGE");return r.sublist(0,-1)}(e,t);return nn(r.subarray())}async function rb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=bh(e,{...r,maxDataLength:Qm,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await tb(n,r);if(r.log.trace('handle: read "%s"',e),e!==Xm){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await eb(n,Nt(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log('handle: respond with "na" for "%s"',e),await eb(n,Nt("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const s=new Ln(...t.map((e=>Un.single(Nt(`${e}\n`)))),Nt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await eb(n,s,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',Xm,e),await eb(n,Nt(`${Xm}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',Xm,e)}}async function nb(e,t,r){if(1===(t=Array.isArray(t)?[...t]:[t]).length&&!1===r.negotiateFully)return function(e,t,r){const n=e.sink.bind(e),s=e.source;let o=!1,i=!1;const a=Kn();let c=!1,l=!1;const u=Kn();let h=!1,d=!1;const p=Kn(),f=bh({sink:n,source:s},{...r,maxDataLength:Qm});async function g(){if(i)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;i=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',Xm,t),await f.writeV([Nt(`${Xm}\n`),Nt(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',Xm,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await tb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===Xm&&(e=await tb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new Zo("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}finally{h=!0,d=!1,p.resolve()}}}())}finally{i=!1,o=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const s of e){if(l&&await u.promise,c)yield s;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',Xm,t,s.byteLength);const e=`${t}\n`;yield new Ln(Uint8Array.from([19]),Nt(`${Xm}\n`),P(e.length),Nt(e),s).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',Xm,t,s.byteLength),c=!0,l=!1,u.resolve(),g().catch((e=>{r.log.error("could not finish optimistic protocol negotiation of %s",t,e)}))}n=!0}n||await g()}())},e.source=async function*(){await g(),r.log.trace('optimistic: reading data from "%s" stream',t),yield*f.unwrap().source}(),null!=e.closeRead){const t=e.closeRead.bind(e);e.closeRead=async e=>{o||await g().catch((e=>{r.log.error("could not negotiate protocol before close read",e)})),await t(e)}}if(null!=e.closeWrite){const t=e.closeWrite.bind(e);e.closeWrite=async e=>{o||await g().catch((e=>{r.log.error("could not negotiate protocol before close write",e)})),await t(e)}}if(null!=e.close){const t=e.close.bind(e);e.close=async e=>{const r=[];l&&r.push(u.promise),d&&r.push(p.promise),r.length>0?await lh(Promise.all(r),e?.signal):(o=!0,i=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=bh(e,{...r,maxDataLength:Qm}),s=t.shift();if(null==s)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',Xm,s);const o=Nt(`${Xm}\n`),i=Nt(`${s}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[o,i],r),r.log.trace("select: reading multistream-select header");let a=await tb(n,r);if(r.log.trace('select: read "%s"',a),a===Xm&&(r.log.trace("select: reading protocol response"),a=await tb(n,r),r.log.trace('select: read "%s"',a)),a===s)return{stream:n.unwrap(),protocol:s};for(const e of t){r.log.trace('select: write "%s"',e),await eb(n,Nt(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await tb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new Zo("protocol selection failed","ERR_UNSUPPORTED_PROTOCOL")}const sb=Symbol.for("@libp2p/connection");class ob{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;transient;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:s,abort:o,getStreams:i}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.transient=e.transient??!1,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=s,this._abort=o,this._getStreams=i,this.tags=[]}[Symbol.toStringTag]="Connection";[sb]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Zo("the connection is being closed","ERR_CONNECTION_BEING_CLOSED");if("closed"===this.status)throw new Zo("the connection is closed","ERR_CONNECTION_CLOSED");if(Array.isArray(e)||(e=[e]),this.transient&&!0!==t?.runOnTransientConnection)throw new Zo("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing all streams"),await Promise.all(this.streams.map((async t=>t.close(e)))),this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this.streams.forEach((t=>{t.abort(e)})),this.log.error("all streams aborted",this.streams.length),this._abort(e),this.timeline.close=Date.now(),this.status="closed"}}function ib(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class ab{components;connectionEncryption;muxers;inboundUpgradeTimeout;events;constructor(e,t){this.components=e,this.connectionEncryption=new Map,t.connectionEncryption.forEach((e=>{this.connectionEncryption.set(e.protocol,e)})),this.muxers=new Map,t.muxers.forEach((e=>{this.muxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??2e3,this.events=e.events}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,t,r){const n=this.components.connectionGater[r];if(void 0!==n&&await n(e,t))throw new Zo(`The multiaddr connection is blocked by gater.${r}`,Gy.ERR_CONNECTION_INTERCEPTED)}async upgradeInbound(e,t){if(!await this.components.connectionManager.acceptIncomingConnection(e))throw new Zo("connection denied",Gy.ERR_CONNECTION_DENIED);let r,n,s,o,i;const a=AbortSignal.timeout(this.inboundUpgradeTimeout),c=()=>{e.abort(new Zo("inbound upgrade timeout",ti))};a.addEventListener("abort",c,{once:!0});try{if(!0===await(this.components.connectionGater.denyInboundConnection?.(e)))throw new Zo("The multiaddr connection is blocked by gater.acceptConnection",Gy.ERR_CONNECTION_INTERCEPTED);this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the inbound connection upgrade");let a=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(e.log("protecting the inbound connection"),a=await t.protect(e))}try{if(r=a,!0!==t?.skipEncryption){t?.onProgress?.(new Qf("upgrader:encrypt-inbound-connection")),({conn:r,remotePeer:n,protocol:i}=await this._encryptInbound(a));const e={...a,...r};await this.shouldBlockConnection(n,e,"denyInboundEncryptedConnection")}else{const t=e.remoteAddr.getPeerId();if(null==t)throw new Zo("inbound connection that skipped encryption must have a peer id",Gy.ERR_INVALID_MULTIADDR);const r=oh(t);i="native",n=r}if(s=r,null!=t?.muxerFactory)o=t.muxerFactory;else if(this.muxers.size>0){t?.onProgress?.(new Qf("upgrader:multiplex-inbound-connection"));const e=await this._multiplexInbound({...a,...r},this.muxers);o=e.muxerFactory,s=e.stream}}catch(t){throw e.log.error("failed to upgrade inbound connection",t),t}return await this.shouldBlockConnection(n,e,"denyInboundUpgradedConnection"),e.log("successfully upgraded inbound connection"),this._createConnection({cryptoProtocol:i,direction:"inbound",maConn:e,upgradedConn:s,muxerFactory:o,remotePeer:n,transient:t?.transient})}finally{a.removeEventListener("abort",c),this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){const r=e.remoteAddr.getPeerId();let n,s,o,i,a,c;null!=r&&(n=oh(r),await this.shouldBlockConnection(n,e,"denyOutboundConnection")),this.components.metrics?.trackMultiaddrConnection(e),e.log("starting the outbound connection upgrade");let l=e;if(!0!==t?.skipProtection){const t=this.components.connectionProtector;null!=t&&(l=await t.protect(e))}try{if(s=l,!0!==t?.skipEncryption){({conn:s,remotePeer:o,protocol:a}=await this._encryptOutbound(l,n));const e={...l,...s};await this.shouldBlockConnection(o,e,"denyOutboundEncryptedConnection")}else{if(null==n)throw new Zo("Encryption was skipped but no peer id was passed",Gy.ERR_INVALID_PEER);a="native",o=n}if(i=s,null!=t?.muxerFactory)c=t.muxerFactory;else if(this.muxers.size>0){const e=await this._multiplexOutbound({...l,...s},this.muxers);c=e.muxerFactory,i=e.stream}}catch(t){throw e.log.error("failed to upgrade outbound connection",t),await e.close(t),t}return await this.shouldBlockConnection(o,e,"denyOutboundUpgradedConnection"),e.log("successfully upgraded outbound connection"),this._createConnection({cryptoProtocol:a,direction:"outbound",maConn:e,upgradedConn:i,muxerFactory:c,remotePeer:o,transient:t?.transient})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:s,remotePeer:o,muxerFactory:i,transient:a}=e;let c,l,u;null!=i&&(c=i.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),{stream:r,protocol:n}=await rb(e,t,{log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",n);const s=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if(e.code!==Gy.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return 32}(n,this.components.registrar);if(ib(n,"inbound",u)===s){const t=new Zo(`Too many inbound protocol streams for protocol "${n}" - limit ${s}`,Gy.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);throw e.abort(t),t}e.source=r.source,e.sink=r.sink,e.protocol=n,null!=r.closeWrite&&(e.closeWrite=r.closeWrite),null!=r.closeRead&&(e.closeRead=r.closeRead),null!=r.close&&(e.close=r.close),await this.components.peerStore.merge(o,{protocols:[n]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:n})})).catch((async t=>{u.log.error("error handling incoming stream id %s",e.id,t.message,t.code,t.stack),null==e.timeline.close&&await e.close()}))}}),l=async(e,t={})=>{if(null==c)throw new Zo("Stream is not multiplexed",Gy.ERR_MUXER_UNAVAILABLE);u.log("starting new stream for protocols %s",e);const r=await c.newStream();u.log.trace("started new stream %s for protocols %s",r.id,e);try{if(null==t.signal){r.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);const n=AbortSignal.timeout(3e4);t={...t,signal:n}}r.log.trace("selecting protocol from protocols %s",e);const{stream:n,protocol:s}=await nb(r,e,{...t,log:r.log,yieldBytes:!0});r.log("selected protocol %s",s);const i=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if(e.code!==Gy.ERR_NO_HANDLER_FOR_PROTOCOL)throw e}return r.maxOutboundStreams??64}(s,this.components.registrar,t),a=ib(s,"outbound",u);if(a>=i){const e=new Zo(`Too many outbound protocol streams for protocol "${s}" - ${a}/${i}`,Gy.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);throw r.abort(e),e}return await this.components.peerStore.merge(o,{protocols:[s]}),r.source=n.source,r.sink=n.sink,r.protocol=s,null!=n.closeWrite&&(r.closeWrite=n.closeWrite),null!=n.closeRead&&(r.closeRead=n.closeRead),null!=n.close&&(r.close=n.close),this.components.metrics?.trackProtocolStream(r,u),r}catch(t){if(u.log.error("could not create new stream for protocols %s",e,t),null==r.timeline.close&&r.abort(t),null!=t.code)throw t;throw new Zo(String(t),Gy.ERR_UNSUPPORTED_PROTOCOL)}},Promise.all([c.sink(s.source),s.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>(null!=u&&"close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:o,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,transient:a,logger:this.components.logger,newStream:l??(()=>{throw new Zo("connection is not multiplexed",Gy.ERR_CONNECTION_NOT_MULTIPLEXED)}),getStreams:()=>null!=c?c.streams:[],close:async e=>{null!=c&&(u.log.trace("close muxer"),await c.close(e)),u.log.trace("close maconn"),await n.close(e),u.log.trace("closed maconn")},abort:e=>{n.abort(e),null!=c&&c.abort(e)}},u=new ob(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:s,options:o}=this.components.registrar.getHandler(n);if(t.transient&&!0!==o.runOnTransientConnection)throw new Zo("Cannot open protocol stream on transient connection","ERR_TRANSIENT_CONNECTION");s({connection:t,stream:r})}async _encryptInbound(e){const t=Array.from(this.connectionEncryption.keys());e.log("handling inbound crypto protocol selection",t);try{const{stream:r,protocol:n}=await rb(e,t,{log:e.log}),s=this.connectionEncryption.get(n);if(null==s)throw new Error(`no crypto module found for ${n}`);return e.log("encrypting inbound connection using",n),{...await s.secureInbound(this.components.peerId,r),protocol:n}}catch(t){throw e.log.error("encrypting inbound connection failed",t),new Zo(t.message,Gy.ERR_ENCRYPTION_FAILED)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncryption.keys());e.log("selecting outbound crypto protocol",r);try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:s}=await nb(e,r,{log:e.log,yieldBytes:!0}),o=this.connectionEncryption.get(s);if(null==o)throw new Error(`no crypto module found for ${s}`);return e.log("encrypting outbound connection to %p using %s",t,o),{...await o.secureOutbound(this.components.peerId,n,t),protocol:s}}catch(r){throw e.log.error("encrypting outbound connection to %p failed",t,r),new Zo(r.message,Gy.ERR_ENCRYPTION_FAILED)}}async _multiplexOutbound(e,t){const r=Array.from(t.keys());e.log("outbound selecting muxer %s",r);try{e.log.trace("selecting stream muxer from %s",r);const{stream:n,protocol:s}=await nb(e,r,{log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new Zo(String(t),Gy.ERR_MUXER_UNAVAILABLE)}}async _multiplexInbound(e,t){const r=Array.from(t.keys());e.log("inbound handling muxers %s",r);try{const{stream:n,protocol:s}=await rb(e,r,{log:e.log});return{stream:n,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new Zo(String(t),Gy.ERR_MUXER_UNAVAILABLE)}}}class cb extends xs{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new xs,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new Ps(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??yg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new Sy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!_y.includes(r)){const e=t.components[r];if(null==e&&!Ay.includes(r))throw new Zo(`${r} not set`,"ERR_SERVICE_MISSING");return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"1.9.4"},logger:this.logger,events:t,datastore:e.datastore??new by,connectionGater:Py(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",new hy(n,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),null!=e.metrics&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),n.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){const t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};n.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=e.connectionProtector&&this.configureComponent("connectionProtector",e.connectionProtector(n)),this.components.upgrader=new ab(this.components,{connectionEncryption:(e.connectionEncryption??[]).map(((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components)))),muxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout}),this.configureComponent("transportManager",new Jm(this.components,e.transportManager)),this.configureComponent("connectionManager",new Cm(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Pm(this.components,e.connectionMonitor)),this.configureComponent("registrar",new Wm(this.components)),this.configureComponent("addressManager",new Ey(this.components,e.addresses));const s=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new zm(this.components,{routers:s}));const o=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Om(this.components,{routers:o})),this.configureComponent("randomWalk",new Gm(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#O(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[ng]&&(this.log("registering service %s for content routing",t),o.push(r[ng])),null!=r[sg]&&(this.log("registering service %s for peer routing",t),s.push(r[sg])),null!=r[kd]&&(this.log("registering service %s for peer discovery",t),r[kd].addEventListener?.("peer",(e=>{this.#O(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of ky(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of Iy(r))if(!0!==t[e])throw new Zo(`Service "${Ry(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`,"ERR_UNMET_SERVICE_DEPENDENCIES")}(n)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new bg;for(const t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,r={}){if(null==t)throw new Zo("no protocols were provided to open a stream",Gy.ERR_INVALID_PROTOCOLS_FOR_STREAM);if(0===(t=Array.isArray(t)?t:[t]).length)throw new Zo("no protocols were provided to open a stream",Gy.ERR_INVALID_PROTOCOLS_FOR_STREAM);return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Ao(e)&&(e=oh(e.getPeerId()??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),null!=e.publicKey)return e.publicKey;try{const t=await this.peerStore.get(e);if(null!=t.id.publicKey)return t.id.publicKey}catch(e){if(e.code!==Gy.ERR_NOT_FOUND)throw e}const r=Cn([Nt("/pk/"),e.multihash.digest]),n=await this.contentRouting.get(r,t);return zu(n),await this.peerStore.patch(e,{publicKey:n}),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e)})))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#O(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error(new Error(Gy.ERR_DISCOVERED_SELF))}}async function lb(e={}){const t=e.peerId??=await(async()=>{const e=await async function(){return ju("Ed25519").generateKeyPair(2048)}(),t=await wg(e);if("Ed25519"===t.type)return t;throw new Error(`Generated unexpected PeerId type "${t.type}"`)})();if(null==t.privateKey)throw new Zo("peer id was missing private key","ERR_MISSING_PRIVATE_KEY");return e.privateKey??=await Wu(t.privateKey),new cb(await async function(e){const t=Ky(Wy,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Zo(zy.ERR_PROTECTOR_REQUIRED,Gy.ERR_PROTECTOR_REQUIRED);if(null!=t.privateKey&&!(await ah(t.privateKey.public.bytes,t.privateKey.bytes)).equals(t.peerId))throw new Zo("Private key doesn't match peer id",Gy.ERR_INVALID_KEY);return t}(e))}const ub="bootstrap",hb={store:1,filter:2,lightPush:2};var db=__webpack_require__(495),pb=__webpack_require__.t(db,2);const fb=BigInt(0),gb=BigInt(1),yb=BigInt(2),mb=BigInt(3),bb=BigInt(8),wb=Object.freeze({a:fb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:gb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),vb=(e,t)=>(e+t/yb)/t,Eb={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=wb,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-gb*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,i=BigInt("0x100000000000000000000000000000000"),a=vb(o*e,t),c=vb(-n*e,t);let l=Kb(e-a*r-c*s,t),u=Kb(-a*n-c*o,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function Sb(e){const{a:t,b:r}=wb,n=Kb(e*e),s=Kb(n*e);return Kb(s+t*e+r)}const Ab=wb.a===fb;class _b extends Error{constructor(e){super(e)}}function kb(e){if(!(e instanceof Ib))throw new TypeError("JacobianPoint expected")}class Ib{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof Cb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(Cb.ZERO)?Ib.ZERO:new Ib(e.x,e.y,gb)}static toAffineBatch(e){const t=function(e,t=wb.P){const r=new Array(e.length),n=Gb(e.reduce(((e,n,s)=>n===fb?e:(r[s]=e,Kb(e*n,t))),gb),t);return e.reduceRight(((e,n,s)=>n===fb?e:(r[s]=Kb(e*r[s],t),Kb(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Ib.toAffineBatch(e).map(Ib.fromAffine)}equals(e){kb(e);const{x:t,y:r,z:n}=this,{x:s,y:o,z:i}=e,a=Kb(n*n),c=Kb(i*i),l=Kb(t*c),u=Kb(s*a),h=Kb(Kb(r*i)*c),d=Kb(Kb(o*n)*a);return l===u&&h===d}negate(){return new Ib(this.x,Kb(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=Kb(e*e),s=Kb(t*t),o=Kb(s*s),i=e+s,a=Kb(yb*(Kb(i*i)-n-o)),c=Kb(mb*n),l=Kb(c*c),u=Kb(l-yb*a),h=Kb(c*(a-u)-bb*o),d=Kb(yb*t*r);return new Ib(u,h,d)}add(e){kb(e);const{x:t,y:r,z:n}=this,{x:s,y:o,z:i}=e;if(s===fb||o===fb)return this;if(t===fb||r===fb)return e;const a=Kb(n*n),c=Kb(i*i),l=Kb(t*c),u=Kb(s*a),h=Kb(Kb(r*i)*c),d=Kb(Kb(o*n)*a),p=Kb(u-l),f=Kb(d-h);if(p===fb)return f===fb?this.double():Ib.ZERO;const g=Kb(p*p),y=Kb(p*g),m=Kb(l*g),b=Kb(f*f-y-yb*m),w=Kb(f*(m-b)-h*y),v=Kb(n*i*p);return new Ib(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Ib.ZERO;if("bigint"==typeof e&&e===fb)return t;let r=jb(e);if(r===gb)return this;if(!Ab){let e=t,n=this;for(;r>fb;)r&gb&&(e=e.add(n)),n=n.double(),r>>=gb;return e}let{k1neg:n,k1:s,k2neg:o,k2:i}=Eb.splitScalar(r),a=t,c=t,l=this;for(;s>fb||i>fb;)s&gb&&(a=a.add(l)),i&gb&&(c=c.add(l)),l=l.double(),s>>=gb,i>>=gb;return n&&(a=a.negate()),o&&(c=c.negate()),c=new Ib(Kb(c.x*Eb.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=Ab?128/e+1:256/e+1,r=[];let n=this,s=n;for(let o=0;o>=u,i>a&&(i-=l,e+=gb);const h=r,d=r+Math.abs(i)-1,p=t%2!=0,f=i<0;0===i?o=o.add(Rb(p,n[h])):s=s.add(Rb(f,n[d]))}return{p:s,f:o}}multiply(e,t){let r,n,s=jb(e);if(Ab){const{k1neg:e,k1:o,k2neg:i,k2:a}=Eb.splitScalar(s);let{p:c,f:l}=this.wNAF(o,t),{p:u,f:h}=this.wNAF(a,t);c=Rb(e,c),u=Rb(i,u),u=new Ib(Kb(u.x*Eb.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:o}=this.wNAF(s,t);r=e,n=o}return Ib.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,s=this.equals(Ib.ZERO);null==e&&(e=s?bb:Gb(n));const o=e,i=Kb(o*o),a=Kb(i*o),c=Kb(t*i),l=Kb(r*a),u=Kb(n*o);if(s)return Cb.ZERO;if(u!==gb)throw new Error("invZ was invalid");return new Cb(c,l)}}function Rb(e,t){const r=t.negate();return e?r:t}Ib.BASE=new Ib(wb.Gx,wb.Gy,gb),Ib.ZERO=new Ib(fb,gb,fb);const Tb=new WeakMap;class Cb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Tb.delete(this)}hasEvenY(){return this.y%yb===fb}static fromCompressedHex(e){const t=32===e.length,r=qb(t?e:e.subarray(1));if(!Zb(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=wb,r=BigInt(6),n=BigInt(11),s=BigInt(22),o=BigInt(23),i=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=zb(l,mb)*l%t,h=zb(u,mb)*l%t,d=zb(h,yb)*c%t,p=zb(d,n)*d%t,f=zb(p,s)*p%t,g=zb(f,i)*f%t,y=zb(g,a)*g%t,m=zb(y,i)*f%t,b=zb(m,mb)*l%t,w=zb(b,o)*p%t,v=zb(w,r)*c%t,E=zb(v,yb);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(Sb(r));const s=(n&gb)===gb;t?s&&(n=Kb(-n)):!(1&~e[0])!==s&&(n=Kb(-n));const o=new Cb(r,n);return o.assertValidity(),o}static fromUncompressedHex(e){const t=qb(e.subarray(1,33)),r=qb(e.subarray(33,65)),n=new Cb(t,r);return n.assertValidity(),n}static fromHex(e){const t=Vb(e),r=t.length,n=t[0];if(32===r)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return Cb.BASE.multiply(tw(e))}static fromSignature(e,t,r){const{r:n,s}=rw(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const o=Wb(Vb(e)),{n:i}=wb,a=2===r||3===r?n+i:n,c=Gb(a,i),l=Kb(-o*c,i),u=Kb(s*c,i),h=1&r?"03":"02",d=Cb.fromHex(h+Ub(a)),p=Cb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return Hb(this.toHex(e))}toHex(e=!1){const t=Ub(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Ub(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const e="Point is not on elliptic curve",{x:t,y:r}=this;if(!Zb(t)||!Zb(r))throw new Error(e);const n=Kb(r*r);if(Kb(n-Sb(t))!==fb)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new Cb(this.x,Kb(-this.y))}double(){return Ib.fromAffine(this).double().toAffine()}add(e){return Ib.fromAffine(this).add(Ib.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Ib.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Ib.fromAffine(this),s=t===fb||t===gb||this!==Cb.BASE?n.multiplyUnsafe(t):n.multiply(t),o=Ib.fromAffine(e).multiplyUnsafe(r),i=s.add(o);return i.equals(Ib.ZERO)?void 0:i.toAffine()}}function Nb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function xb(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${Db(e)}`);const t=e[1],r=e.subarray(2,t+2);if(!t||r.length!==t)throw new Error("Invalid signature integer: wrong length");if(0===r[0]&&r[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:qb(r),left:e.subarray(t+2)}}Cb.BASE=new Cb(wb.Gx,wb.Gy),Cb.ZERO=new Cb(fb,fb);class Pb{constructor(e,t){this.r=e,this.s=t,this.assertValidity()}static fromCompact(e){const t=e instanceof Uint8Array,r="Signature.fromCompact";if("string"!=typeof e&&!t)throw new TypeError(`${r}: Expected string or Uint8Array`);const n=t?Db(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Pb($b(n.slice(0,64)),$b(n.slice(64,128)))}static fromDER(e){const t=e instanceof Uint8Array;if("string"!=typeof e&&!t)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r,s:n}=function(e){if(e.length<2||48!=e[0])throw new Error(`Invalid signature tag: ${Db(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=xb(e.subarray(2)),{data:n,left:s}=xb(r);if(s.length)throw new Error(`Invalid signature: left bytes after parsing: ${Db(s)}`);return{r:t,s:n}}(t?e:Hb(e));return new Pb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!Qb(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!Qb(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=wb.n>>gb;return this.s>e}normalizeS(){return this.hasHighS()?new Pb(this.r,Kb(-this.s,wb.n)):this}toDERRawBytes(){return Hb(this.toDERHex())}toDERHex(){const e=Nb(Fb(this.s)),t=Nb(Fb(this.r)),r=e.length/2,n=t.length/2,s=Fb(r),o=Fb(n);return`30${Fb(n+r+4)}02${o}${t}02${s}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return Hb(this.toCompactHex())}toCompactHex(){return Ub(this.r)+Ub(this.s)}}function Ob(...e){if(!e.every((e=>e instanceof Uint8Array)))throw new Error("Uint8Array list expected");if(1===e.length)return e[0];const t=e.reduce(((e,t)=>e+t.length),0),r=new Uint8Array(t);for(let t=0,n=0;tt.toString(16).padStart(2,"0")));function Db(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r0)return BigInt(e);if("bigint"==typeof e&&Qb(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function Kb(e,t=wb.P){const r=e%t;return r>=fb?r:t+r}function zb(e,t){const{P:r}=wb;let n=e;for(;t-- >fb;)n*=n,n%=r;return n}function Gb(e,t=wb.P){if(e===fb||t<=fb)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=Kb(e,t),n=t,s=fb,o=gb,i=gb,a=fb;for(;r!==fb;){const e=n/r,t=n%r,c=s-i*e,l=o-a*e;n=r,r=t,s=i,o=a,i=c,a=l}if(n!==gb)throw new Error("invert: does not exist");return Kb(s,t)}function Wb(e,t=!1){const r=function(e){const t=8*e.length-256,r=qb(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=wb;return r>=n?r-n:r}let Yb,Jb;class Xb{constructor(e,t){if(this.hashLen=e,this.qByteLen=t,"number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");this.v=new Uint8Array(e).fill(1),this.k=new Uint8Array(e).fill(0),this.counter=0}hmac(...e){return lw.hmacSha256(this.k,...e)}hmacSync(...e){return Jb(this.k,...e)}checkSync(){if("function"!=typeof Jb)throw new _b("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw new Error("Expected 32 bytes of private key");t=$b(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(32!==e.length)throw new Error("Expected 32 bytes of private key");t=qb(e)}if(!Qb(t))throw new Error("Expected private key: 0 < key < n");return t}function rw(e){if(e instanceof Pb)return e.assertValidity(),e;try{return Pb.fromDER(e)}catch(t){return Pb.fromCompact(e)}}function nw(e){return qb(e.length>32?e.slice(0,32):e)}function sw(e){const t=nw(e),r=Kb(t,wb.n);return ow(r{if((e=Vb(e)).length<40||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return Mb(Kb(qb(e),wb.n-gb)+gb)},randomBytes:(e=32)=>{if(aw.web)return aw.web.getRandomValues(new Uint8Array(e));if(aw.node){const{randomBytes:t}=aw.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>lw.hashToPrivateKey(lw.randomBytes(40)),precompute(e=8,t=Cb.BASE){const r=t===Cb.BASE?t:new Cb(t.x,t.y);return r._setWindowSize(e),r.multiply(mb),r},sha256:async(...e)=>{if(aw.web){const t=await aw.web.subtle.digest("SHA-256",Ob(...e));return new Uint8Array(t)}if(aw.node){const{createHash:t}=aw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(aw.web){const r=await aw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Ob(...t),s=await aw.web.subtle.sign("HMAC",r,n);return new Uint8Array(s)}if(aw.node){const{createHmac:r}=aw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=cw[e];if(void 0===r){const t=await lw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Ob(t,t),cw[e]=r}return lw.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof Yb)throw new _b("sha256Sync is undefined, you need to set it");let r=cw[e];if(void 0===r){const t=Yb(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Ob(t,t),cw[e]=r}return Yb(r,...t)},_JacobianPoint:Ib};Object.defineProperties(lw,{sha256Sync:{configurable:!1,get:()=>Yb,set(e){Yb||(Yb=e)}},hmacSha256Sync:{configurable:!1,get:()=>Jb,set(e){Jb||(Jb=e)}}});var uw=__webpack_require__(1176);function hw(e){return new Uint8Array(uw.keccak256.arrayBuffer(e))}function dw(e,t,r){try{return function(e,t,r,n=iw){let s;try{s=rw(e),t=Vb(t)}catch(e){return!1}const{r:o,s:i}=s;if(n.strict&&s.hasHighS())return!1;const a=Wb(t);let c;try{c=function(e){return e instanceof Cb?(e.assertValidity(),e):Cb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=wb,u=Gb(i,l),h=Kb(a*u,l),d=Kb(o*u,l),p=Cb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&Kb(p.x,l)===o}(Pb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const pw="Invalid record id";function fw(e,t){switch(t){case"udp":return fw(e,"udp4")||fw(e,"udp6");case"tcp":return fw(e,"tcp4")||fw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const s=t.slice(0,3);let o;switch(s){case"udp":o=r?e.get("udp6"):e.get("udp");break;case"tcp":o=r?e.get("tcp6"):e.get("tcp");break;default:return}return o?function(e,t,r,n){let s=_o("/"+e+"/"+ro(e,r));return s=s.encapsulate(_o("/"+t+"/"+ro(t,n))),s}(r?"ip6":"ip4",s,n,o):void 0}function gw(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let s=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(s,e.bytes.length),s+=2,r.set(e.bytes,s),s+=e.bytes.length})),r}function yw(e){let t=0;return e.lightPush&&(t+=1),t<<=1,e.filter&&(t+=1),t<<=1,e.store&&(t+=1),t<<=1,e.relay&&(t+=1),t}class mw extends Map{seq;signature;constructor(e={},t=BigInt(1),r){super(Object.entries(e)),this.seq=t,this.signature=r}set(e,t){return this.signature=void 0,this.seq++,super.set(e,t)}get id(){const e=this.get("id");if(!e)throw new Error("id not found.");return an(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(pw)}get rs(){const e=this.get("rs");if(e)return yn(e)}get rsv(){const e=this.get("rsv");if(e)return yn(e)}get ip(){return bw(this,"ip","ip4")}set ip(e){vw(this,"ip","ip4",e)}get tcp(){return ww(this,"tcp","tcp")}set tcp(e){Ew(this,"tcp","tcp",e)}get udp(){return ww(this,"udp","udp")}set udp(e){Ew(this,"udp","udp",e)}get ip6(){return bw(this,"ip6","ip6")}set ip6(e){vw(this,"ip6","ip6",e)}get tcp6(){return ww(this,"tcp6","tcp")}set tcp6(e){Ew(this,"tcp6","tcp",e)}get udp6(){return ww(this,"udp6","udp")}set udp6(e){Ew(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Sw(this,"waku2",e,(e=>new Uint8Array([yw(e)])))}}function bw(e,t,r){const n=e.get(t);if(n)return ro(r,n)}function ww(e,t,r){const n=e.get(t);if(n)return Number(ro(r,n))}function vw(e,t,r,n){Sw(e,t,n,no.bind({},r))}function Ew(e,t,r,n){vw(e,t,r,n?.toString(10))}function Sw(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function Aw(e,t){return async function(e,t,r={}){const{seed:n,m:s,d:o}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=Vb(e),s=tw(t),o=[ow(s),sw(n)];if(null!=r){!0===r&&(r=lw.randomBytes(32));const e=Vb(r);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");o.push(e)}return{seed:Ob(...o),m:nw(n),d:s}}(e,t,r.extraEntropy),i=new Xb(32,32);let a;for(await i.reseed(n);!(a=ew(await i.generate(),s,o,r.canonical));)await i.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:s,recovered:o}=Object.assign({canonical:!0,der:!0},t),i=s?r.toDERRawBytes():r.toCompactRawBytes();return o?[i,n]:i}(a,r)}(hw(t),e,{der:!1})}const _w=new vn("enr");var kw,Iw;!function(e){e.TCP="tcp",e.UDP="udp"}(kw||(kw={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(Iw||(Iw={}));class Rw extends mw{static RECORD_PREFIX="enr:";peerId;static async create(e={},t=BigInt(1),r){const n=new Rw(e,t,r);try{const e=n.publicKey;e&&(n.peerId=await function(e){return ah(new qu.secp256k1.Secp256k1PublicKey(e).bytes,void 0)}(e))}catch(e){_w.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=Cb.fromHex(e).toRawBytes(!1);return on(hw(t.slice(1)))}(this.publicKey):void 0;throw new Error(pw)}getLocationMultiaddr=fw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&_w.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(Iw)){const r=this.getLocationMultiaddr(t);r&&e.push(r)}const t=this.multiaddrs??[];return e.concat(t).map((e=>this.peerId?e.encapsulate(`/p2p/${this.peerId.toString()}`):e))}get peerInfo(){const e=this.peerId;if(e)return{id:e,multiaddrs:this.getAllLocationMultiaddrs()}}getFullMultiaddr(e){if(this.peerId){const t=this.getLocationMultiaddr(e);if(t)return t.encapsulate(`/p2p/${this.peerId.toString()}`)}}getFullMultiaddrs(){if(this.peerId&&this.multiaddrs){const e=this.peerId;return this.multiaddrs.map((t=>t.encapsulate(`/p2p/${e.toString()}`)))}return[]}verify(e,t){if(!this.get("id")||"v4"!==this.id)throw new Error(pw);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return dw(t,hw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(pw);return this.signature=await Aw(t,e),this.signature}}let Tw=!1,Cw=!1;const Nw={debug:1,default:2,info:2,warning:3,error:4,off:5};let xw=Nw.default,Pw=null;const Ow=function(){try{const e=[];if(["NFD","NFC","NFKD","NFKC"].forEach((t=>{try{if("test"!=="test".normalize(t))throw new Error("bad normalize")}catch(r){e.push(t)}})),e.length)throw new Error("missing "+e.join(", "));if(String.fromCharCode(233).normalize("NFD")!==String.fromCharCode(101,769))throw new Error("broken implementation")}catch(e){return e.message}return null}();var Lw,Dw;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Lw||(Lw={})),function(e){e.UNKNOWN_ERROR="UNKNOWN_ERROR",e.NOT_IMPLEMENTED="NOT_IMPLEMENTED",e.UNSUPPORTED_OPERATION="UNSUPPORTED_OPERATION",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.TIMEOUT="TIMEOUT",e.BUFFER_OVERRUN="BUFFER_OVERRUN",e.NUMERIC_FAULT="NUMERIC_FAULT",e.MISSING_NEW="MISSING_NEW",e.INVALID_ARGUMENT="INVALID_ARGUMENT",e.MISSING_ARGUMENT="MISSING_ARGUMENT",e.UNEXPECTED_ARGUMENT="UNEXPECTED_ARGUMENT",e.CALL_EXCEPTION="CALL_EXCEPTION",e.INSUFFICIENT_FUNDS="INSUFFICIENT_FUNDS",e.NONCE_EXPIRED="NONCE_EXPIRED",e.REPLACEMENT_UNDERPRICED="REPLACEMENT_UNDERPRICED",e.UNPREDICTABLE_GAS_LIMIT="UNPREDICTABLE_GAS_LIMIT",e.TRANSACTION_REPLACED="TRANSACTION_REPLACED",e.ACTION_REJECTED="ACTION_REJECTED"}(Dw||(Dw={}));const Bw="0123456789abcdef";class Uw{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Nw[r]&&this.throwArgumentError("invalid log level name","logLevel",e),xw>Nw[r]||console.log.apply(console,t)}debug(...e){this._log(Uw.levels.DEBUG,e)}info(...e){this._log(Uw.levels.INFO,e)}warn(...e){this._log(Uw.levels.WARNING,e)}makeError(e,t,r){if(Cw)return this.makeError("censored error",t,{});t||(t=Uw.errors.UNKNOWN_ERROR),r||(r={});const n=[];Object.keys(r).forEach((e=>{const t=r[e];try{if(t instanceof Uint8Array){let r="";for(let e=0;e>4],r+=Bw[15&t[e]];n.push(e+"=Uint8Array(0x"+r+")")}else n.push(e+"="+JSON.stringify(t))}catch(t){n.push(e+"="+JSON.stringify(r[e].toString()))}})),n.push(`code=${t}`),n.push(`version=${this.version}`);const s=e;let o="";switch(t){case Dw.NUMERIC_FAULT:{o="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":o+="-"+t;break;case"negative-power":case"negative-width":o+="-unsupported";break;case"unbound-bitwise-result":o+="-unbound-result"}break}case Dw.CALL_EXCEPTION:case Dw.INSUFFICIENT_FUNDS:case Dw.MISSING_NEW:case Dw.NONCE_EXPIRED:case Dw.REPLACEMENT_UNDERPRICED:case Dw.TRANSACTION_REPLACED:case Dw.UNPREDICTABLE_GAS_LIMIT:o=t}o&&(e+=" [ See: https://links.ethers.org/v5-errors-"+o+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const i=new Error(e);return i.reason=s,i.code=t,Object.keys(r).forEach((function(e){i[e]=r[e]})),i}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Uw.errors.INVALID_ARGUMENT,{argument:t,value:r})}assert(e,t,r,n){e||this.throwError(t,r,n)}assertArgument(e,t,r,n){e||this.throwArgumentError(t,r,n)}checkNormalize(e){null==e&&(e="platform missing String.prototype.normalize"),Ow&&this.throwError("platform missing String.prototype.normalize",Uw.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Ow})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Uw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Uw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,Uw.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Uw.errors.MISSING_NEW,{name:t.name})}checkAbstract(e,t){e===t?this.throwError("cannot instantiate abstract class "+JSON.stringify(t.name)+" directly; use a sub-class",Uw.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Uw.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Pw||(Pw=new Uw("logger/5.7.0")),Pw}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Uw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Tw){if(!e)return;this.globalLogger().throwError("error censorship permanent",Uw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}Cw=!!e,Tw=!!t}static setLogLevel(e){const t=Nw[e.toLowerCase()];null!=t?xw=t:Uw.globalLogger().warn("invalid log level - "+e)}static from(e){return new Uw(e)}}Uw.errors=Dw,Uw.levels=Lw;const Mw=new Uw("bytes/5.7.0");function Fw(e){return!!e.toHexString}function $w(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return $w(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function Hw(e){return"number"==typeof e&&e==e&&e%1==0}function qw(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!Hw(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function Vw(e,t){if(t||(t={}),"number"==typeof e){Mw.checkSafeUint53(e,"invalid arrayify value");const t=[];for(;e;)t.unshift(255&e),e=parseInt(String(e/256));return 0===t.length&&t.push(0),$w(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),Fw(e)&&(e=e.toHexString()),jw(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":Mw.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e>4]+Kw[15&n]}return t}return Mw.throwArgumentError("invalid hexlify value","value",e)}const Gw=new Uw("rlp/5.7.0");function Ww(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function Yw(e,t,r){let n=0;for(let s=0;st+1+n&&Gw.throwError("child data too short",Uw.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:s}}function Qw(e,t){if(0===e.length&&Gw.throwError("data too short",Uw.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&Gw.throwError("data short segment too short",Uw.errors.BUFFER_OVERRUN,{});const n=Yw(e,t+1,r);return t+1+r+n>e.length&&Gw.throwError("data long segment too short",Uw.errors.BUFFER_OVERRUN,{}),Xw(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{}),Xw(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{});const n=Yw(e,t+1,r);return t+1+r+n>e.length&&Gw.throwError("data array too short",Uw.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:zw(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&Gw.throwError("data too short",Uw.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:zw(e.slice(t+1,t+1+r))}}return{consumed:1,result:zw(e[t])}}const Zw=new vn("enr:decoder");class ev{static fromString(e){if(!e.startsWith(Rw.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${Rw.RECORD_PREFIX}'`);return ev.fromRLP(Nt(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=Vw(e),r=Qw(t,0);return r.consumed!==t.length&&Gw.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(sn);return async function(e){const{signature:t,seq:r,kvs:n}=function(e){if(!Array.isArray(e))throw new Error("Decoded ENR must be an array");if(e.length%2!=0)throw new Error("Decoded ENR must have an even number of elements");const[t,r,...n]=e;if(!t||Array.isArray(t))throw new Error("Decoded ENR invalid signature: must be a byte array");if(!r||Array.isArray(r))throw new Error("Decoded ENR invalid sequence number: must be a byte array");return{signature:t,seq:r,kvs:n}}(e),s={};for(let e=0;etv.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let s=0;for(let o=0;o(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},sv={name:"v6",size:16,isFormat:e=>e.length>0&&rv.test(e),encode(e,t,r){let n=16+(r=~~r),s=-1,o=0,i=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l>8),r=97?u-=87:u>=65?u-=55:(u-=48,i=10*i+u),o=(o<<4)+u)}if(!1===a)!0===c?(r>8),r=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]=rs?t[--r]:0;else for(;r=fv||(64512&e.charCodeAt(o))!==fv?t+=3:(n=o,t+=4)}}return t}function yv(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(gv(e)+r));let s=r;for(let r=0;r>6,t[s++]=128|63&o;else if((63488&o)!==pv)t[s++]=224|(61440&o)>>12,t[s++]=128|(4032&o)>>6,t[s++]=128|63&o;else{const i=r+1;if(i===n||o>=fv)t[s++]=239,t[s++]=191,t[s++]=189;else{const n=e.charCodeAt(i);(64512&n)!==fv?(t[s++]=239,t[s++]=191,t[s++]=189):(r=i,o=65536|(1023&o)<<10|1023&n,t[s++]=240|(1835008&o)>>18,t[s++]=128|(258048&o)>>12,t[s++]=128|(4032&o)>>6,t[s++]=128|63&o)}}}return yv.bytes=s-r,t}function mv(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let s=t;s191&&t<224)r=(31&t)<<6|63&e[s++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;const o=pv|r>>10&1023;n+=String.fromCharCode(o),r=fv|1023&r}else r=(15&t)<<12|(63&e[s++])<<6|63&e[s++];n+=String.fromCharCode(r)}return mv.bytes=r-t,n}yv.bytes=0,mv.bytes=0;const bv=e=>e instanceof Uint8Array;function wv(e){return"string"==typeof e?gv(e):e.byteLength}function vv(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):yv(e)}function Ev(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return yv(t,e,r),yv.bytes}const Sv=Math.pow(2,24),Av=Math.pow(2,16),_v=Math.pow(2,8),kv=(e,t)=>e[t]*Sv+e[t+1]*Av+e[t+2]*_v+e[t+3],Iv=(e,t)=>e[t]<<8|e[t+1],Rv=(e,t,r)=>(t=+t,e[r+3]=t,t>>>=8,e[r+2]=t,t>>>=8,e[r+1]=t,t>>>=8,e[r]=t,r+4),Tv=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function Cv(e,t,r,n,s){return r<0&&(n-=r,r=0),n<0&&(n=0),s<0?new Uint8Array(0):r>=t.length||n>=s?0:function(e,t,r,n,s){s-n>t.length-r&&(s=n+t.length-r);let o=s-n;const i=e.length-n;return o>i&&(o=i),(0!==n||se)}}const xv=Nv({encode(e,t,r){t||(t=new Uint8Array(xv.encodingLength(e))),r||(r=0);const n=r,s=e.replace(/^\.|\.$/gm,"");if(s.length){const e=s.split(".");for(let n=0;n=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(o+=i?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=Iv(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,o+=i?0:1,i=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(s+=a+1,s>254)throw new Error("Cannot decode name (name too long)");r.push(mv(e,t,t+a)),t+=a,o+=i?0:a}}return xv.decode.bytes=o,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:wv(e.replace(/^\.|\.$/gm,""))+2}),Pv=Nv({encode(e,t,r){t||(t=new Uint8Array(Pv.encodingLength(e))),r||(r=0);const n=Ev(t,e,r+1);return t[r]=n,Pv.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=mv(e,t+1,t+1+r);return Pv.decode.bytes=r+1,n},encodingLength:e=>wv(e)+1}),Ov=Nv({bytes:12,encode(e,t,r){t||(t=new Uint8Array(Ov.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),s="response"===e.type?32768:0;return Tv(t,e.id||0,r),Tv(t,n|s,r+2),Tv(t,e.questions.length,r+4),Tv(t,e.answers.length,r+6),Tv(t,e.authorities.length,r+8),Tv(t,e.additionals.length,r+10),t},decode(e,t){if(t||(t=0),e.length<12)throw new Error("Header must be 12 bytes");const r=Iv(e,t+2);return{id:Iv(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:lv(r>>11&15),flag_aa:1==(r>>10&1),flag_tc:1==(r>>9&1),flag_rd:1==(r>>8&1),flag_ra:1==(r>>7&1),flag_z:1==(r>>6&1),flag_ad:1==(r>>5&1),flag_cd:1==(r>>4&1),rcode:cv(15&r),questions:new Array(Iv(e,t+4)),answers:new Array(Iv(e,t+6)),authorities:new Array(Iv(e,t+8)),additionals:new Array(Iv(e,t+10))}},encodingLength:()=>12}),Lv=Nv({encode(e,t,r){t||(t=new Uint8Array(Lv.encodingLength(e))),r||(r=0);const n=e.length;return Tv(t,n,r),Cv(e,t,r+2,0,n),Lv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Iv(e,t),n=e.slice(t+2,t+2+r);return Lv.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),Dv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(Dv.encodingLength(e))),r||(r=0),xv.encode(e,t,r+2),Tv(t,xv.encode.bytes,r),Dv.encode.bytes=xv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Iv(e,t),n=xv.decode(e,t+2);return Dv.decode.bytes=r+2,n},encodingLength:e=>xv.encodingLength(e)+2}),Bv=Nv({encode(e,t,r){t||(t=new Uint8Array(Bv.encodingLength(e))),r||(r=0);const n=r;return r+=2,xv.encode(e.mname,t,r),r+=xv.encode.bytes,xv.encode(e.rname,t,r),r+=xv.encode.bytes,Rv(t,e.serial||0,r),r+=4,Rv(t,e.refresh||0,r),r+=4,Rv(t,e.retry||0,r),r+=4,Rv(t,e.expire||0,r),r+=4,Rv(t,e.minimum||0,r),Tv(t,(r+=4)-n-2,n),Bv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=xv.decode(e,t),t+=xv.decode.bytes,n.rname=xv.decode(e,t),t+=xv.decode.bytes,n.serial=kv(e,t),t+=4,n.refresh=kv(e,t),t+=4,n.retry=kv(e,t),t+=4,n.expire=kv(e,t),t+=4,n.minimum=kv(e,t),t+=4,Bv.decode.bytes=t-r,n},encodingLength:e=>22+xv.encodingLength(e.mname)+xv.encodingLength(e.rname)}),Uv=Nv({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t0;){const r=e[t++];if(--n,ne?(bv(e)?e.length:wv(e))+2:2}),Fv=Nv({encode(e,t,r){t||(t=new Uint8Array(Fv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Pv.encode(e.cpu,t,r),r+=Pv.encode.bytes,Pv.encode(e.os,t,r),r+=Pv.encode.bytes,Tv(t,r-n-2,n),Fv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=Pv.decode(e,t),t+=Pv.decode.bytes,n.os=Pv.decode(e,t),t+=Pv.decode.bytes,Fv.decode.bytes=t-r,n},encodingLength:e=>Pv.encodingLength(e.cpu)+Pv.encodingLength(e.os)+2}),$v=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array($v.encodingLength(e))),r||(r=0),xv.encode(e,t,r+2),Tv(t,xv.encode.bytes,r),$v.encode.bytes=xv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=xv.decode(e,t+2);return $v.decode.bytes=xv.decode.bytes+2,r},encodingLength:e=>xv.encodingLength(e)+2}),Hv=Nv({encode(e,t,r){t||(t=new Uint8Array(Hv.encodingLength(e))),r||(r=0),Tv(t,e.priority||0,r+2),Tv(t,e.weight||0,r+4),Tv(t,e.port||0,r+6),xv.encode(e.target,t,r+8);const n=xv.encode.bytes+6;return Tv(t,n,r),Hv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Iv(e,t),n={};return n.priority=Iv(e,t+2),n.weight=Iv(e,t+4),n.port=Iv(e,t+6),n.target=xv.decode(e,t+8),Hv.decode.bytes=r+2,n},encodingLength:e=>8+xv.encodingLength(e.target)}),qv=Nv({encode(e,t,r){const n=qv.encodingLength(e);return t||(t=new Uint8Array(qv.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=qv.ISSUER_CRITICAL),Tv(t,n-2,r),t[r+=2]=e.flags||0,r+=1,Pv.encode(e.tag,t,r),r+=Pv.encode.bytes,Ev(t,e.value,r),r+=wv(e.value),qv.encode.bytes=n,t},decode(e,t){t||(t=0);const r=Iv(e,t),n=t+=2,s={};return s.flags=e[t],t+=1,s.tag=Pv.decode(e,t),t+=Pv.decode.bytes,s.value=mv(e,t,n+r),s.issuerCritical=!!(s.flags&qv.ISSUER_CRITICAL),qv.decode.bytes=r+2,s},encodingLength:e=>Pv.encodingLength(e.tag)+Pv.encodingLength(e.value)+2});qv.ISSUER_CRITICAL=128;const Vv=Nv({encode(e,t,r){t||(t=new Uint8Array(Vv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Tv(t,e.preference||0,r),r+=2,xv.encode(e.exchange,t,r),r+=xv.encode.bytes,Tv(t,r-n-2,n),Vv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=Iv(e,t),t+=2,n.exchange=xv.decode(e,t),t+=xv.decode.bytes,Vv.decode.bytes=t-r,n},encodingLength:e=>4+xv.encodingLength(e.exchange)}),jv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(jv.encodingLength(e))),r||(r=0),Tv(t,4,r),r+=2,nv.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,nv.decode(e,t)),bytes:6}),Kv=Nv({encode:(e,t,r)=>(t||(t=new Uint8Array(Kv.encodingLength(e))),r||(r=0),Tv(t,16,r),r+=2,sv.encode(e,t,r),Kv.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=sv.decode(e,t);return Kv.decode.bytes=18,r},bytes:18}),zv=e=>new Uint8Array(e),Gv=Nv({encode(e,t,r){t||(t=new Uint8Array(Gv.encodingLength(e))),r||(r=0);const n=r,s=dv(e.code);if(Tv(t,s,r),r+=2,e.data)Tv(t,e.data.length,r),r+=2,Cv(e.data,t,r),r+=e.data.length;else switch(s){case 8:{const n=e.sourcePrefixLength||0,s=e.family||function(e){return ov(e)===nv.size?1:2}(e.ip),o=function(e,t,r){r=~~r;const n=ov(e);return"function"==typeof t&&(t=t(r+n)),n===nv.size?nv.encode(e,t,r):sv.encode(e,t,r)}(e.ip,zv),i=Math.ceil(n/8);Tv(t,i+4,r),Tv(t,s,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,Cv(o,t,r,0,i),r+=i}break;case 11:e.timeout?(Tv(t,2,r),r+=2,Tv(t,e.timeout,r),r+=2):(Tv(t,0,r),r+=2);break;case 12:{const n=e.length||0;Tv(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;Tv(t,n,r),r+=2;for(const n of e.tags)Tv(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return Gv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=Iv(e,t),r.type=function(e){switch(e){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return e<0?null:`OPTION_${e}`}(r.code);const n=Iv(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=Iv(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const s=new Uint8Array(1===r.family?4:16);Cv(e,s,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===nv.size)return nv.decode(e,t,r);if(r===sv.size)return sv.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${nv.size} for v4 or ${sv.size} for v6.`)}(s)}break;case 11:n>0&&(r.timeout=Iv(e,t),t+=2);break;case 14:r.tags=[];for(let s=0;s0;)n[o++]=Gv.decode(e,t),t+=Gv.decode.bytes,s-=Gv.decode.bytes;return Wv.decode.bytes=t-r,n},encodingLength:e=>2+dE(e||[],Gv)}),Yv=Nv({encode(e,t,r){t||(t=new Uint8Array(Yv.encodingLength(e))),r||(r=0);const n=r,s=e.key;if(!bv(s))throw new Error("Key must be a Buffer");return r+=2,Tv(t,e.flags,r),t[r+=2]=Yv.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,Cv(s,t,r+=1,0,s.length),r+=s.length,Yv.encode.bytes=r-n,Tv(t,Yv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);if(t+=2,n.flags=Iv(e,t),e[t+=2]!==Yv.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+s+2),t+=n.key.length,Yv.decode.bytes=t-r,n},encodingLength:e=>6+wv(e.key)});Yv.PROTOCOL_DNSSEC=3,Yv.ZONE_KEY=128,Yv.SECURE_ENTRYPOINT=32768;const Jv=Nv({encode(e,t,r){t||(t=new Uint8Array(Jv.encodingLength(e))),r||(r=0);const n=r,s=e.signature;if(!bv(s))throw new Error("Signature must be a Buffer");return r+=2,Tv(t,av(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,Rv(t,e.originalTTL,r),r+=4,Rv(t,e.expiration,r),r+=4,Rv(t,e.inception,r),r+=4,Tv(t,e.keyTag,r),r+=2,xv.encode(e.signersName,t,r),Cv(s,t,r+=xv.encode.bytes,0,s.length),r+=s.length,Jv.encode.bytes=r-n,Tv(t,Jv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);return t+=2,n.typeCovered=iv(Iv(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=kv(e,t),t+=4,n.expiration=kv(e,t),t+=4,n.inception=kv(e,t),t+=4,n.keyTag=Iv(e,t),t+=2,n.signersName=xv.decode(e,t),t+=xv.decode.bytes,n.signature=e.slice(t,r+s+2),t+=n.signature.length,Jv.decode.bytes=t-r,n},encodingLength:e=>20+xv.encodingLength(e.signersName)+wv(e.signature)}),Xv=Nv({encode(e,t,r){t||(t=new Uint8Array(Xv.encodingLength(e))),r||(r=0);const n=r;return r+=2,xv.encode(e.mbox||".",t,r),r+=xv.encode.bytes,xv.encode(e.txt||".",t,r),r+=xv.encode.bytes,Xv.encode.bytes=r-n,Tv(t,Xv.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=xv.decode(e,t)||".",t+=xv.decode.bytes,n.txt=xv.decode(e,t)||".",t+=xv.decode.bytes,Xv.decode.bytes=t-r,n},encodingLength:e=>2+xv.encodingLength(e.mbox||".")+xv.encodingLength(e.txt||".")}),Qv=Nv({encode(e,t,r){t||(t=new Uint8Array(Qv.encodingLength(e))),r||(r=0);const n=r,s=[];for(let t=0;t>8]&&(s[r>>8]=[]),s[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e2+xv.encodingLength(e.nextDomain)+Qv.encodingLength(e.rrtypes)}),eE=Nv({encode(e,t,r){t||(t=new Uint8Array(eE.encodingLength(e))),r||(r=0);const n=r,s=e.salt;if(!bv(s))throw new Error("salt must be a Buffer");const o=e.nextDomain;if(!bv(o))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,Tv(t,e.iterations,r),t[r+=2]=s.length,Cv(s,t,r+=1,0,s.length),t[r+=s.length]=o.length,Cv(o,t,r+=1,0,o.length),r+=o.length,Qv.encode(e.rrtypes,t,r),r+=Qv.encode.bytes,eE.encode.bytes=r-n,Tv(t,eE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=Iv(e,t);const o=e[t+=2];t+=1,n.salt=e.slice(t,t+o);const i=e[t+=o];return t+=1,n.nextDomain=e.slice(t,t+i),t+=i,n.rrtypes=Qv.decode(e,t,s-(t-r)),t+=Qv.decode.bytes,eE.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+Qv.encodingLength(e.rrtypes)}),tE=Nv({encode(e,t,r){t||(t=new Uint8Array(tE.encodingLength(e))),r||(r=0);const n=r,s=e.digest;if(!bv(s))throw new Error("Digest must be a Buffer");return r+=2,Tv(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,Cv(s,t,r+=1,0,s.length),r+=s.length,tE.encode.bytes=r-n,Tv(t,tE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},s=Iv(e,t);return t+=2,n.keyTag=Iv(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+s+2),t+=n.digest.length,tE.decode.bytes=t-r,n},encodingLength:e=>6+wv(e.digest)});function rE(e){switch(e.toUpperCase()){case"A":return jv;case"PTR":case"CNAME":case"DNAME":return $v;case"TXT":return Uv;case"NULL":return Mv;case"AAAA":return Kv;case"SRV":return Hv;case"HINFO":return Fv;case"CAA":return qv;case"NS":return Dv;case"SOA":return Bv;case"MX":return Vv;case"OPT":return Wv;case"DNSKEY":return Yv;case"RRSIG":return Jv;case"RP":return Xv;case"NSEC":return Zv;case"NSEC3":return eE;case"DS":return tE}return Lv}const nE=Nv({encode(e,t,r){t||(t=new Uint8Array(nE.encodingLength(e))),r||(r=0);const n=r;if(xv.encode(e.name,t,r),r+=xv.encode.bytes,Tv(t,av(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");Tv(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,Tv(t,e.flags||0,r+6),r+=8,Wv.encode(e.options||[],t,r),r+=Wv.encode.bytes}else{let n=hv(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),Tv(t,n,r+2),Rv(t,e.ttl||0,r+4),r+=8;const s=rE(e.type);s.encode(e.data,t,r),r+=s.encode.bytes}return nE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=xv.decode(e,t),t+=xv.decode.bytes,r.type=iv(Iv(e,t)),"OPT"===r.type)r.udpPayloadSize=Iv(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=Iv(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=Wv.decode(e,t+8),t+=8+Wv.decode.bytes;else{const n=Iv(e,t+2);r.ttl=kv(e,t+4),r.class=uv(-32769&n),r.flush=!!(32768&n);const s=rE(r.type);r.data=s.decode(e,t+8),t+=8+s.decode.bytes}return nE.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return xv.encodingLength(e.name)+8+rE(e.type).encodingLength(t)}}),sE=Nv({encode(e,t,r){t||(t=new Uint8Array(sE.encodingLength(e))),r||(r=0);const n=r;return xv.encode(e.name,t,r),r+=xv.encode.bytes,Tv(t,av(e.type),r),r+=2,Tv(t,hv(void 0===e.class?"IN":e.class),r),r+=2,sE.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=xv.decode(e,t),t+=xv.decode.bytes,n.type=iv(Iv(e,t)),t+=2,n.class=uv(Iv(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),sE.decode.bytes=t-r,n},encodingLength:e=>xv.encodingLength(e.name)+4}),oE={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(hE(e))),r||(r=0);const s=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),Ov.encode(e,t,r),r+=Ov.encode.bytes,r=pE(e.questions,sE,t,r),r=pE(e.answers,nE,t,r),r=pE(e.authorities,nE,t,r),r=pE(e.additionals,nE,t,r),oE.encode.bytes=r-s,n&&lE.bytes!==t.length?t.slice(0,lE.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=Ov.decode(e,t);return t+=Ov.decode.bytes,t=fE(n.questions,sE,e,t),t=fE(n.answers,nE,e,t),t=fE(n.authorities,nE,e,t),t=fE(n.additionals,nE,e,t),oE.decode.bytes=t-r,n},encodingLength:function(e){return Ov.encodingLength(e)+dE(e.questions||[],sE)+dE(e.answers||[],nE)+dE(e.authorities||[],nE)+dE(e.additionals||[],nE)}};function iE(e,t){if(e.questions)throw new Error("Only one .question object expected instead of a .questions array!");const r=Object.assign({type:t},e);return r.question&&(r.questions=[r.question],delete r.question),r}oE.encode.bytes=0,oE.decode.bytes=0;const aE={encode:function(e,t,r){return t=oE.encode(iE(e,"query"),t,r),aE.encode.bytes=oE.encode.bytes,t},decode:function(e,t){const r=oE.decode(e,t);return aE.decode.bytes=oE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return oE.encodingLength(iE(e,"query"))}};aE.encode.bytes=0,aE.decode.bytes=0;const cE={encode:function(e,t,r){return t=oE.encode(iE(e,"response"),t,r),cE.encode.bytes=oE.encode.bytes,t},decode:function(e,t){const r=oE.decode(e,t);return cE.decode.bytes=oE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return oE.encodingLength(iE(e,"response"))}};cE.encode.bytes=0,cE.decode.bytes=0;const lE=oE.encode,uE=oE.decode,hE=oE.encodingLength;function dE(e,t){let r=0;for(let n=0;n255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==s[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);s[r]=e,o[e]=r}const i=r.charCodeAt(0),a={name:e,encodingLength(e){const t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===i?e.charCodeAt(t-2)===i?r-2:r-1:r},encode(e,t,r){null==t&&(t=new Uint8Array(a.encodingLength(e))),null==r&&(r=0);let n=e.length;e.charCodeAt(n-1)===i&&(e.charCodeAt(n-2)===i?n-=2:n-=1);const o=n%4,c=n-o;let l=r,u=0;for(;u>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===o){const r=s[e.charCodeAt(u)]<<10|s[e.charCodeAt(u+1)]<<4|s[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===o&&(t[l++]=s[e.charCodeAt(u)]<<2|s[e.charCodeAt(u+1)]>>4);return a.encode.bytes=l-r,t},decode(e,t,r){null==t&&(t=0),null==r&&(r=e.length);const s=r-t,c=s%3,l=t+s-c,u=[];for(let r=t;r>18&63],o[t>>12&63],o[t>>6&63],o[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(o[t>>10],o[t>>4&63],o[t<<2&63]),1===n&&u.push(i)}else if(1===c){const t=e[r-1];u.push(o[t>>2],o[t<<4&63]),1===n&&u.push(i,i)}return a.decode.bytes=s,String.fromCharCode.apply(String,u)}};return a}gE("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const yE=gE("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let mE="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;mE||(mE=class extends Error{constructor(e="Request aborted."){super(e)}}),mE.prototype.name="AbortError",mE.prototype.code="ABORT_ERR";const bE="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class wE extends Error{constructor(e,t,r){super("status="+t+" while requesting "+e+" ["+r+"]"),this.uri=e,this.status=t,this.method=r}toJSON(){return{code:this.code,uri:this.uri,status:this.status,method:this.method,endpoint:this.endpoint}}}wE.prototype.name="HTTPStatusError",wE.prototype.code="HTTP_STATUS";class vE extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:_E(this.cause)}}}vE.prototype.name="ResponseError",vE.prototype.code="RESPONSE_ERR";class EE extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}EE.prototype.name="TimeoutError",EE.prototype.code="ETIMEOUT";const SE=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,AE=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function _E(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const kE=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,IE=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,RE=/\[(((pk|name)=([^\]]+)))\]/gi;function TE(e,t){t.lastIndex=0;const r={};for(;;){const n=t.exec(e);if(!n)break;n[2]?r[n[3].toLowerCase()]=n[4]:r[n[1].toLowerCase()]=!0}return r}class CE extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${NE.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}CE.prototype.name="InvalidProtocolError",CE.prototype.code="EPROTOCOL";const NE=["http:","https:","udp4:","udp6:"];class xE{constructor(e,t){this.name=e.name||null,this.protocol=e.protocol;const r="string"==typeof e.port?e.port=parseInt(e.port,10):e.port;if(null==r)this.port=t?"https:"===this.protocol?443:80:e.pk?443:53;else{if("number"!=typeof r&&!isNaN(r))throw new Error(`Invalid Endpoint: port "${e.port}" needs to be a number: ${JSON.stringify(e)}`);this.port=r}}toJSON(){return this.toString()}}class PE extends xE{constructor(e){super(e,!1),this.pk=e.pk||null}toString(){const e=this.port!==(this.pk?443:53)?`:${this.port}`:"",t=this.pk?` [pk=${this.pk}]`:"",r=this.name?` [name=${this.name}]`:"";return`udp://${this.ipv4||`[${this.ipv6}]`}${e}${t}${r}`}}class OE extends PE{constructor(e){if(super(Object.assign({protocol:"udp4:"},e)),!e.ipv4||"string"!=typeof e.ipv4)throw new Error(`Invalid Endpoint: .ipv4 "${e.ipv4}" needs to be set: ${JSON.stringify(e)}`);this.ipv4=e.ipv4}}class LE extends PE{constructor(e){if(super(Object.assign({protocol:"udp6:"},e)),!e.ipv6||"string"!=typeof e.ipv6)throw new Error(`Invalid Endpoint: .ipv6 "${e.ipv6}" needs to be set: ${JSON.stringify(e)}`);this.ipv6=e.ipv6}}function DE(e){return AE.test(e)&&!SE.test(e)?`[${e}]`:e}class BE extends xE{constructor(e){if(super(Object.assign({protocol:"https:"},e),!0),e.host||(e.ipv4&&(e.host=e.ipv4),e.ipv6&&(e.host=`[${e.ipv6}]`)),!e.host||"string"!=typeof e.host)throw new Error(`Invalid Endpoint: host "${e.path}" needs to be set: ${JSON.stringify(e)}`);if(this.host=e.host,this.path=e.path||"/dns-query",this.method=/^post$/i.test(e.method)?"POST":"GET",this.ipv4=e.ipv4,this.ipv6=e.ipv6,!this.ipv6){const e=AE.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||SE.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${DE(this.host)}:${this.port}${this.path}`;try{this.url=new bE(t)}catch(e){throw new Error(e.message+` [${t}]`)}}toString(){const e="https:"===this.protocol?"":"http://",t=this.port!==("https:"===this.protocol?443:80)?`:${this.port}`:"",r="GET"!==this.method?" [post]":"",n="/dns-query"===this.path?"":this.path,s=this.name?` [name=${this.name}]`:"",o=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",i=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${DE(this.host)}${t}${n}${r}${o}${i}${s}`}}function UE(e){let t;if("string"==typeof e)t=function(e){const t=kE.exec(e),r=t[2]||"https:",n=t[3],s=t[5],o=t[6],i=t[7];if("https:"===r||"http:"===r){const e=TE(i,IE);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:s,path:o,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=TE(i,RE),o=/^\[(.*)\]$/.exec(n);if(o&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!o&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return o?new LE({protocol:"udp6:",ipv6:o[1],port:s,pk:t.pk,name:t.name}):new OE({protocol:"udp4:",ipv4:n,port:s,pk:t.pk,name:t.name})}throw new CE(r,e)}(e);else{if("object"!=typeof e||null===e||Array.isArray(e))throw new Error(`Can not convert ${e} to an endpoint`);if(e instanceof xE)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new OE(t);if("udp6:"===r)return new LE(t);if("https:"===r||"http:"===r)return new BE(t);throw new CE(r,JSON.stringify(t))}const ME="application/dns-message";function FE(){}function $E(e,t,r,n,s){return new Promise(((o,i)=>{const a=new bE(e);"GET"===t&&r&&(a.search="?dns="+yE.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",ME),"POST"===t&&l.setRequestHeader("Content-Type",ME),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new EE(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new wE(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new wE(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new wE(c,l.status,t));else{let e;if("string"==typeof l.response)e=yv(l.response);else if(l.response instanceof Uint8Array)e=l.response;else{if(!(Array.isArray(l.response)||l.response instanceof ArrayBuffer))throw new Error("Unprocessable response "+l.response);e=new Uint8Array(l.response)}u(null,e)}},"POST"===t?l.send(r):l.send(),s&&s.addEventListener("abort",h);let u=function(e,t){u=FE,s&&s.removeEventListener("abort",h),o(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new mE);try{l.abort()}catch(e){}}}))}function HE(e){const t=null===e.time||void 0===e.time?Date.now():e.time,r=function(e){return e.filter((e=>e.cors||e.endpoint.cors))}(e.data.map((e=>(e.endpoint=UE(Object.assign({name:e.name},e.endpoint)),e)))),n=r.map((e=>e.endpoint));return{data:{resolvers:r,resolverByName:r.reduce(((e,t)=>(e[t.name]=t,e)),{}),endpoints:n,endpointByName:n.reduce(((e,t)=>(e[t.name]=t,e)),{})},time:t}}Error;const qE=HE({data:[{name:"adfree.usableprivacy.net",endpoint:{protocol:"https:",host:"adfree.usableprivacy.net"},description:"Public updns DoH service with advertising, tracker and malware filters.\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0},{name:"adguard-dns-doh",endpoint:{protocol:"https:",host:"dns.adguard.com",ipv4:"94.140.15.15"},description:"Remove ads and protect your computer from malware (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-family-doh",endpoint:{protocol:"https:",host:"dns-family.adguard.com",ipv4:"94.140.15.16"},description:"Adguard DNS with safesearch and adult content blocking (over DoH)",country:"France",location:{lat:48.8582,long:2.3387},filter:!0},{name:"adguard-dns-unfiltered-doh",endpoint:{protocol:"https:",host:"dns-unfiltered.adguard.com",ipv4:"94.140.14.140"},description:"AdGuard public DNS servers without filters (over DoH)",country:"France",location:{lat:48.8582,long:2.3387}},{name:"ahadns-doh-chi",endpoint:{protocol:"https:",host:"doh.chi.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Chicago, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=chi",country:"United States",location:{lat:41.8483,long:-87.6517},filter:!0,cors:!0},{name:"ahadns-doh-in",endpoint:{protocol:"https:",host:"doh.in.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Mumbai, India. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=in",country:"India",location:{lat:19.0748,long:72.8856},filter:!0,cors:!0},{name:"ahadns-doh-la",endpoint:{protocol:"https:",host:"doh.la.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Los Angeles, USA. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=la",country:"United States",location:{lat:34.0549,long:-118.2578},filter:!0,cors:!0},{name:"ahadns-doh-nl",endpoint:{protocol:"https:",host:"doh.nl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Amsterdam, Netherlands. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=nl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"ahadns-doh-ny",endpoint:{protocol:"https:",host:"doh.ny.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in New York. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=ny",country:"United States",location:{lat:40.7308,long:-73.9975},filter:!0,cors:!0},{name:"ahadns-doh-pl",endpoint:{protocol:"https:",host:"doh.pl.ahadns.net",cors:!0},description:"A zero logging DNS with support for DNS-over-HTTPS (DoH) & DNS-over-TLS (DoT). Blocks ads, malware, trackers, viruses, ransomware, telemetry and more. No persistent logs. DNSSEC. Hosted in Poland. By https://ahadns.com/\nServer statistics can be seen at: https://statistics.ahadns.com/?server=pl",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"alidns-doh",endpoint:{protocol:"https:",host:"dns.alidns.com",ipv4:"223.5.5.5",cors:!0},description:"A public DNS resolver that supports DoH/DoT in mainland China, provided by Alibaba-Cloud.\nWarning: GFW filtering rules are applied by that resolver.\nHomepage: https://alidns.com/",country:"China",location:{lat:34.7725,long:113.7266},filter:!0,log:!0,cors:!0},{name:"ams-ads-doh-nl",endpoint:{protocol:"https:",host:"dnsnl-noads.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.",country:"Romania",location:{lat:45.9968,long:24.997},filter:!0},{name:"ams-doh-nl",endpoint:{protocol:"https:",host:"dnsnl.alekberg.net"},description:"Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Romania",location:{lat:45.9968,long:24.997}},{name:"att",endpoint:{protocol:"https:",host:"dohtrial.att.net"},description:"AT&T test DoH server.",log:!0},{name:"bcn-ads-doh",endpoint:{protocol:"https:",host:"dnses-noads.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611},filter:!0},{name:"bcn-doh",endpoint:{protocol:"https:",host:"dnses.alekberg.net"},description:"Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.",country:"Spain",location:{lat:41.3891,long:2.1611}},{name:"brahma-world",endpoint:{protocol:"https:",host:"dns.brahma.world"},description:"DNS-over-HTTPS server. Non Logging, filters ads, trackers and malware. DNSSEC ready, QNAME Minimization, No EDNS Client-Subnet.\nHosted in Stockholm, Sweden. (https://dns.brahma.world)",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"cisco-doh",endpoint:{protocol:"https:",host:"doh.opendns.com",ipv4:"146.112.41.2"},description:"Remove your DNS blind spot (DoH protocol)\nWarning: modifies your queries to include a copy of your network\naddress when forwarding them to a selection of companies and organizations.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0,log:!0},{name:"cloudflare",endpoint:{protocol:"https:",host:"dns.cloudflare.com",ipv4:"1.0.0.1",cors:!0},description:"Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1",country:"Australia",location:{lat:-33.494,long:143.2104},cors:!0},{name:"cloudflare-family",endpoint:{protocol:"https:",host:"family.cloudflare-dns.com",ipv4:"1.0.0.3",cors:!0},description:"Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"cloudflare-ipv6",endpoint:{protocol:"https:",host:"1dot1dot1dot1.cloudflare-dns.com",cors:!0},description:"Cloudflare DNS over IPv6 (anycast)",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"cloudflare-security",endpoint:{protocol:"https:",host:"security.cloudflare-dns.com",ipv4:"1.0.0.2",cors:!0},description:"Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2",country:"Australia",location:{lat:-33.494,long:143.2104},filter:!0,cors:!0},{name:"controld-block-malware",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p1"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p2"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-block-malware-ad-social",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p3"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking and Social Networks domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-family-friendly",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/family"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS blocks Malware, Ads & Tracking, Adult Content and Drugs domains.",country:"Canada",location:{lat:43.6319,long:-79.3716},filter:!0},{name:"controld-uncensored",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/uncensored"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis DNS unblocks censored domains from various countries.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"controld-unfiltered",endpoint:{protocol:"https:",host:"freedns.controld.com",path:"/p0"},description:"ControlD Free DNS. Take CONTROL of your Internet. Block unwanted content, bypass geo-restrictions and be more productive. DoH protocol and No logging. - https://controld.com/free-dns\nThis is a Unfiltered DNS, no DNS record blocking or manipulation here, if you want to block Malware, Ads & Tracking or Social Network domains, use the other ControlD DNS configs.",country:"Canada",location:{lat:43.6319,long:-79.3716}},{name:"dns.digitale-gesellschaft.ch",endpoint:{protocol:"https:",host:"dns.digitale-gesellschaft.ch"},description:"Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\nHosted in Zurich, Switzerland.\nNon-logging, non-filtering, supports DNSSEC.",country:"Switzerland",location:{lat:47.1449,long:8.1551}},{name:"dns.ryan-palmer",endpoint:{protocol:"https:",host:"dns1.ryan-palmer.com"},description:"Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.",country:"United Kingdom",location:{lat:51.5164,long:-.093}},{name:"dns.sb",endpoint:{protocol:"https:",host:"doh.sb",ipv4:"185.222.222.222",cors:!0},description:"DNSSEC-enabled DoH server by https://xtom.com/\nhttps://dns.sb/doh/",country:"Unknown",location:{lat:47,long:8},cors:!0},{name:"dns.therifleman.name",endpoint:{protocol:"https:",host:"dns.therifleman.name"},description:"DNS-over-HTTPS DNS forwarder from Mumbai, India. Blocks web and Android trackers and ads.\nIP addresses are not logged, but queries are logged for 24 hours for debugging.\nReport issues, send suggestions @ joker349 at protonmail.com.\nAlso supports DoT (for android) @ dns.therifleman.name and plain DNS @ 172.104.206.174",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"dnsforfamily-doh",endpoint:{protocol:"https:",host:"dns-doh.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC). Block adult websites, gambling websites, malwares and advertisements.\nIt also enforces safe search in: Google, YouTube, Bing, DuckDuckGo and Yandex.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforfamily-doh-no-safe-search",endpoint:{protocol:"https:",host:"dns-doh-no-safe-search.dnsforfamily.com"},description:"(DoH Protocol) (Now supports DNSSEC) Block adult websites, gambling websites, malwares and advertisements.\nUnlike other dnsforfamily servers, this one does not enforces safe search. So Google, YouTube, Bing, DuckDuckGo and Yandex are completely accessible without any restriction.\nSocial websites like Facebook and Instagram are not blocked. No DNS queries are logged.\nAs of 26-May-2022 5.9 million websites are blocked and new websites are added to blacklist daily.\nCompletely free, no ads or any commercial motive. Operating for 4 years now.\nWarning: This server is incompatible with anonymization.\nProvided by: https://dnsforfamily.com",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0},{name:"dnsforge.de",endpoint:{protocol:"https:",host:"dnsforge.de",cors:!0},description:"Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.",country:"Germany",location:{lat:52.2998,long:9.447},filter:!0,cors:!0},{name:"dnshome-doh",endpoint:{protocol:"https:",host:"dns.dnshome.de"},description:"https://www.dnshome.de/ public resolver in Germany"},{name:"dnspod-doh",endpoint:{protocol:"https:",host:"doh.pub",cors:!0},description:"A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en",filter:!0,log:!0,cors:!0},{name:"dnswarden-asia-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adblock"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-adultfilter-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/adultfilter"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"dnswarden-asia-uncensor-dohv4",endpoint:{protocol:"https:",host:"doh.asia.dnswarden.com",path:"/uncensored"},description:"Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Singapore",location:{lat:1.2929,long:103.8547}},{name:"dnswarden-eu-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.eu.dnswarden.com"},description:"Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"Germany",location:{lat:50.1103,long:8.7147},filter:!0},{name:"dnswarden-us-adblock-dohv4",endpoint:{protocol:"https:",host:"doh.us.dnswarden.com"},description:"Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).",country:"United States",location:{lat:32.7889,long:-96.8021},filter:!0},{name:"doh-ch-blahdns",endpoint:{protocol:"https:",host:"doh-ch.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/",country:"Netherlands",location:{lat:52.3824,long:4.8995},filter:!0,cors:!0},{name:"doh-cleanbrowsing-adult",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/adult-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It does\nnot block proxy or VPNs, nor mixed-content sites. Sites like Reddit\nare allowed. Google and Bing are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-family",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/family-filter/",cors:!0},description:"Blocks access to all adult, pornographic and explicit sites. It also\nblocks proxy and VPN domains that are used to bypass the filters.\nMixed content sites (like Reddit) are also blocked. Google, Bing and\nYoutube are set to the Safe Mode.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-cleanbrowsing-security",endpoint:{protocol:"https:",host:"doh.cleanbrowsing.org",path:"/doh/security-filter/",cors:!0},description:"Block access to phishing, malware and malicious domains. It does not block adult content.\nBy https://cleanbrowsing.org/",filter:!0,cors:!0},{name:"doh-crypto-sx",endpoint:{protocol:"https:",host:"doh.crypto.sx",cors:!0},description:"DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-crypto-sx-ipv6",endpoint:{protocol:"https:",host:"doh-ipv6.crypto.sx",cors:!0},description:"DNS-over-HTTPS server accessible over IPv6. Anycast, no logs, no censorship, DNSSEC.\nBackend hosted by Scaleway, globally cached via Cloudflare.\nMaintained by Frank Denis.",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"doh-de-blahdns",endpoint:{protocol:"https:",host:"doh-de.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/",country:"Germany",location:{lat:51.2993,long:9.491},filter:!0,cors:!0},{name:"doh-fi-blahdns",endpoint:{protocol:"https:",host:"doh-fi.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/",country:"Finland",location:{lat:60.1758,long:24.9349},filter:!0,cors:!0},{name:"doh-ibksturm",endpoint:{protocol:"https:",host:"ibksturm.synology.me"},description:"DoH & DoT Server, No Logging, No Filters, DNSSEC\nRunning privately by ibksturm in Thurgau, Switzerland"},{name:"doh-jp-blahdns",endpoint:{protocol:"https:",host:"doh-jp.blahdns.com",cors:!0},description:"Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/",country:"Japan",location:{lat:35.6882,long:139.7532},filter:!0,cors:!0},{name:"doh.ffmuc.net",endpoint:{protocol:"https:",host:"doh.ffmuc.net"},description:"An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\nhttps://ffmuc.net/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"doh.tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org"},description:"Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"google",endpoint:{protocol:"https:",host:"dns.google",ipv4:"8.8.8.8",cors:!0},description:"Google DNS (anycast)",country:"United States",location:{lat:37.751,long:-97.822},log:!0,cors:!0},{name:"hdns",endpoint:{protocol:"https:",host:"query.hdns.io",cors:!0},description:"HDNS is a public DNS resolver that supports Handshake domains.\nhttps://www.hdns.io",country:"United States",location:{lat:37.7771,long:-122.406},cors:!0},{name:"he",endpoint:{protocol:"https:",host:"ordns.he.net"},description:"Hurricane Electric DoH server (anycast)\nUnknown logging policy.",country:"United States",location:{lat:37.751,long:-97.822},log:!0},{name:"id-gmail-doh",endpoint:{protocol:"https:",host:"doh.tiar.app"},description:"Non-Logging DNS-over-HTTPS server located in Singapore.\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.",country:"Singapore",location:{lat:1.2929,long:103.8547},filter:!0},{name:"iij",endpoint:{protocol:"https:",host:"public.dns.iij.jp"},description:"DoH server operated by Internet Initiative Japan in Tokyo.\nhttps://www.iij.ad.jp/",country:"Japan",location:{lat:35.69,long:139.69},log:!0},{name:"iqdns-doh",endpoint:{protocol:"https:",host:"a.passcloud.xyz"},description:'Non-logging DoH service runned by V2EX.com user johnsonwil.\nReturns "no such domain" for anti-Chinese government websites. Supports DNSSEC.\nFor more information: https://www.v2ex.com/t/785666',filter:!0},{name:"jp.tiar.app-doh",endpoint:{protocol:"https:",host:"jp.tiar.app"},description:"Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\nNo ECS, Support DNSSEC",country:"Japan",location:{lat:35.6882,long:139.7532}},{name:"jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org"},description:"DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\nCached via Cloudflare."},{name:"libredns",endpoint:{protocol:"https:",host:"doh.libredns.gr"},description:"DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\nhttps://libredns.gr/",country:"Germany",location:{lat:51.2993,long:9.491}},{name:"nextdns",endpoint:{protocol:"https:",host:"anycsast.dns.nextdns.io"},description:"NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nDNSSEC, Anycast, Non-logging, NoFilters\nhttps://www.nextdns.io/",country:"Netherlands",location:{lat:52.3891,long:4.6563}},{name:"nextdns-ultralow",endpoint:{protocol:"https:",host:"dns.nextdns.io",path:"/dnscrypt-proxy"},description:'NextDNS is a cloud-based private DNS service that gives you full control\nover what is allowed and what is blocked on the Internet.\nhttps://www.nextdns.io/\nTo select the server location, the "-ultralow" variant relies on bootstrap servers\ninstead of anycast.'},{name:"njalla-doh",endpoint:{protocol:"https:",host:"dns.njal.la",cors:!0},description:"Non-logging DoH server in Sweden operated by Njalla.\nhttps://dns.njal.la/",country:"Sweden",location:{lat:59.3247,long:18.056},cors:!0},{name:"odoh-cloudflare",endpoint:{protocol:"https:",host:"odoh.cloudflare-dns.com",cors:!0},description:"Cloudflare ODoH server.\nhttps://cloudflare.com",cors:!0},{name:"odoh-crypto-sx",endpoint:{protocol:"https:",host:"odoh.crypto.sx",cors:!0},description:"ODoH target server. Anycast, no logs.\nBackend hosted by Scaleway. Maintained by Frank Denis.",cors:!0},{name:"odoh-id-gmail",endpoint:{protocol:"https:",host:"doh.tiar.app",path:"/odoh"},description:"ODoH target server. Based in Singapore, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"odoh-jp.tiar.app",endpoint:{protocol:"https:",host:"jp.tiar.app",path:"/odoh"},description:"ODoH target server. no logs."},{name:"odoh-jp.tiarap.org",endpoint:{protocol:"https:",host:"jp.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs."},{name:"odoh-resolver4.dns.openinternet.io",endpoint:{protocol:"https:",host:"resolver4.dns.openinternet.io"},description:"ODoH target server. no logs, no filter, DNSSEC.\nRunning on dedicated hardware colocated at Sonic.net in Santa Rosa, CA in the United States.\nUses Sonic's recusrive DNS servers as upstream resolvers (but is not affiliated with Sonic\nin any way). Provided by https://openinternet.io"},{name:"odoh-tiarap.org",endpoint:{protocol:"https:",host:"doh.tiarap.org",path:"/odoh"},description:"ODoH target server via Cloudflare, no logs.\nFilter ads, trackers and malware.",filter:!0},{name:"publicarray-au2-doh",endpoint:{protocol:"https:",host:"doh-2.seby.io",cors:!0},description:"DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\nMaintained by publicarray - https://dns.seby.io",country:"Australia",location:{lat:-33.8591,long:151.2002},cors:!0},{name:"puredns-doh",endpoint:{protocol:"https:",host:"puredns.org",ipv4:"146.190.6.13",cors:!0},description:"Public uncensored DNS resolver in Singapore - https://puredns.org\n** Only available in Indonesia and Singapore **",country:"United States",location:{lat:37.751,long:-97.822},cors:!0},{name:"quad101",endpoint:{protocol:"https:",host:"dns.twnic.tw",cors:!0},description:"DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\nhttps://101.101.101.101/index_en.html",cors:!0},{name:"quad9-doh-ip4-port443-filter-ecs-pri",endpoint:{protocol:"https:",host:"dns11.quad9.net",ipv4:"149.112.112.11"},description:"Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-filter-pri",endpoint:{protocol:"https:",host:"dns.quad9.net",ipv4:"149.112.112.112"},description:"Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"quad9-doh-ip4-port443-nofilter-ecs-pri",endpoint:{protocol:"https:",host:"dns12.quad9.net",ipv4:"9.9.9.12"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip4-port443-nofilter-pri",endpoint:{protocol:"https:",host:"dns10.quad9.net",ipv4:"149.112.112.10"},description:"Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10",country:"United States",location:{lat:37.751,long:-97.822}},{name:"quad9-doh-ip6-port5053-filter-pri",endpoint:{protocol:"https:",host:"dns9.quad9.net"},description:"Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9",country:"United States",location:{lat:37.751,long:-97.822},filter:!0},{name:"safesurfer-doh",endpoint:{protocol:"https:",host:"doh.safesurfer.io"},description:"Family safety focused blocklist for over 2 million adult sites, as well as phishing and malware and more.\nFree to use, paid for customizing blocking for more categories+sites and viewing usage at my.safesurfer.io. Logs taken for viewing\nusage, data never sold - https://safesurfer.io",filter:!0,log:!0},{name:"sth-ads-doh-se",endpoint:{protocol:"https:",host:"dnsse-noads.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332},filter:!0},{name:"sth-doh-se",endpoint:{protocol:"https:",host:"dnsse.alekberg.net"},description:"Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.",country:"Bulgaria",location:{lat:42.696,long:23.332}},{name:"switch",endpoint:{protocol:"https:",host:"dns.switch.ch"},description:"Public DoH service provided by SWITCH in Switzerland\nhttps://www.switch.ch\nProvides protection against malware, but does not block ads.",filter:!0},{name:"uncensoreddns-dk-ipv4",endpoint:{protocol:"https:",host:"unicast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"uncensoreddns-ipv4",endpoint:{protocol:"https:",host:"anycast.uncensoreddns.org"},description:"Also known as censurfridns.\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org",country:"Denmark",location:{lat:55.7123,long:12.0564}},{name:"v.dnscrypt.uk-doh-ipv4",endpoint:{protocol:"https:",host:"v.dnscrypt.uk"},description:"DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\nhttps://www.dnscrypt.uk",country:"United Kingdom",location:{lat:51.4964,long:-.1224}}],time:1654187067783});const VE=new bE("https://martinheidegger.github.io/dns-query/resolvers.json");function jE(e){return/^@/.test(e)}const KE=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:VE,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r){const n=t?t.localStoragePrefix+t.name:null;if(n)try{const e=JSON.parse(localStorage.getItem(n));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:s}=await $E(e,"GET",null,r,void 0),o={time:Date.now(),data:JSON.parse(mv(s))};if(n)try{localStorage.setItem(n,JSON.stringify(o))}catch(e){o.time=null}return o}(this.opts.updateURL,this.opts.persist?{name:"resolvers.json",localStoragePrefix:this.opts.localStoragePrefix,maxTime:Date.now()-this.opts.maxAge}:null,this.opts.timeout).then((e=>HE({data:e.data.resolvers,time:e.time}))).catch((()=>t||qE)):Promise.resolve(qE),this._dataP):this._dataP.then((e=>e.timee.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=WE),"dns"===e&&(e=YE),"function"==typeof e)return this.data().then((t=>t.endpoints.filter(e)));if("string"==typeof e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new Error(`Endpoints (${e}) needs to be iterable (array).`));if(-1===(e=Array.from(e).filter(Boolean)).findIndex(jE))try{return Promise.resolve(e.map(UE))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(jE(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return UE(e)}))))}};function zE(e,t){return t=Object.assign({retries:5,timeout:3e4},t),e.question?(r=t.endpoints,function(e){return null!==e&&"object"==typeof e&&"function"==typeof e.then}(r)?r:Promise.resolve(r)).then((r=>{if(!Array.isArray(r)||0===r.length)throw new Error("No endpoints defined to lookup dns records.");return GE(r.map(UE),function(e){const t=Object.assign({type:"query"},e);return delete t.question,t.questions=[],e.question&&t.questions.push(e.question),t}(e),t)})).then((e=>(e.question=e.questions[0],delete e.questions,e))):Promise.reject(new Error("To request data you need to specify a .question!"));var r}function GE(e,t,r){const n=1===e.length?e[0]:e[Math.floor(Math.random()*e.length)%e.length];return function(e,t,r,n){return n&&n.aborted?Promise.reject(new mE):"udp4:"===e.protocol||"udp6:"===e.protocol?function(){throw new Error('Only "doh" endpoints are supported in the browser')}():function(e,t,r,n){return function(e,t,r,n,s){return $E(e,t,r,n,s)}(e.url,e.method,lE(Object.assign({flags:256},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new vE("Empty.");else try{const e=uE(t);return e.response=r,e}catch(e){n=new vE("Invalid packet (cause="+e.message+")",e)}throw Object.assign(n,{response:r})}))}(e,t,r,n)}(n,t,r.timeout,r.signal).then((e=>(e.endpoint=n.toString(),e)),(s=>{if("AbortError"===s.name||0===r.retries)throw s.endpoint=n.toString(),s;return r.retries>0&&(r.retries-=1),GE(e,t,r)}))}function WE(e){return"https:"===e.protocol||"http:"===e.protocol}function YE(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const JE=new vn("dns-over-https");class XE{endpoints;retries;static async create(e,t){const r=e??await KE.endpoints("doh");return new XE(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await zE({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw JE.error("query failed: ",e),new Error("DNS query failed")}if(!t)throw new Error(`Could not resolve ${e}`);const r=t.map((e=>e.data)),n=[];return r.forEach((e=>{"string"==typeof e?n.push(e):Array.isArray(e)?e.forEach((e=>{"string"==typeof e?n.push(e):n.push(an(e))})):n.push(an(e))})),n}}var QE=__webpack_require__(5818);class ZE{static RECORD_PREFIX=Rw.RECORD_PREFIX;static TREE_PREFIX="enrtree:";static BRANCH_PREFIX="enrtree-branch:";static ROOT_PREFIX="enrtree-root:";static parseAndVerifyRoot(e,t){if(!e.startsWith(this.ROOT_PREFIX))throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);const r=ZE.parseRootValues(e),n=QE.decode.asBytes(t),s=e.split(" sig")[0],o=cn(s);if(!dw(Nt(r.signature,"base64url").slice(0,64),hw(o),new Uint8Array(n)))throw new Error("Unable to verify ENRTree root signature");return r.eRoot}static parseRootValues(e){const t=e.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\d+) sig=([^ ]+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree root entry");t.shift();const[r,n,s,o]=t;if(!r)throw new Error("Could not parse 'e' value from ENRTree root entry");if(!n)throw new Error("Could not parse 'l' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!o)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(s),signature:o}}static parseTree(e){if(!e.startsWith(this.TREE_PREFIX))throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);const t=e.match(/^enrtree:\/\/([^@]+)@(.+)$/);if(!Array.isArray(t))throw new Error("Could not parse ENRTree tree entry");t.shift();const[r,n]=t;if(!r)throw new Error("Could not parse public key from ENRTree tree entry");if(!n)throw new Error("Could not parse domain from ENRTree tree entry");return{publicKey:r,domain:n}}static parseBranch(e){if(!e.startsWith(this.BRANCH_PREFIX))throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);return e.split(this.BRANCH_PREFIX)[1].split(",")}}const eS=new vn("discovery:fetch_nodes");function tS(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function rS(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function nS(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function sS(e,t,r){if(tS(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relaythis._search(s,o)));return oS.info("retrieved peers: ",i.map((e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map((e=>e.toString()))})))),i}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:s}=ZE.parseTree(e[r]),o={domain:s,publicKey:n,visits:{}};for await(const e of async function*(e,t,r){const n={relay:e.relay??0,store:e.store??0,filter:e.filter??0,lightPush:e.lightPush??0},s=n.relay+n.store+n.filter+n.lightPush,o={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=new Set;for(;!tS(n,o)&&ithis._search(s,o))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,s;t.visits[e]=!0;const o=function(e){return e.startsWith(ZE.ROOT_PREFIX)?ZE.ROOT_PREFIX:e.startsWith(ZE.BRANCH_PREFIX)?ZE.BRANCH_PREFIX:e.startsWith(ZE.RECORD_PREFIX)?ZE.RECORD_PREFIX:""}(r);try{switch(o){case ZE.ROOT_PREFIX:return n=ZE.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case ZE.BRANCH_PREFIX:return s=ZE.parseBranch(r),n=function(e,t){const r={};for(const[n,s]of e.entries())t.visits[s]&&(r[n]=!0);if(Object.keys(r).length===e.length)throw new Error("Unresolvable circular path detected");let n;do{n=Math.floor(Math.random()*e.length)}while(r[n]);return e[n]}(s,t),await this._search(n,t);case ZE.RECORD_PREFIX:return ev.fromString(r);default:return null}}catch(t){return oS.error(`Failed to search DNS tree ${o} at subdomain ${e}: ${t}`),null}}catch(t){return oS.error(`Failed to retrieve TXT record at subdomain ${e}: ${t}`),null}}async _getTXTRecord(e,t){if(this._DNSTreeCache[e])return this._DNSTreeCache[e];const r=e!==t.domain?`${e}.${t.domain}`:t.domain,n=await this.dns.resolveTXT(r);if(!n.length)throw new Error("Received empty result array while fetching TXT record");if(!n[0].length)throw new Error("Received empty TXT record");const s=n.join("");return this._DNSTreeCache[e]=s,s}}const aS=new vn("peer-discovery-dns");class cS extends xs{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;aS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){aS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await iS.dnsOverHttp();this.nextPeer=r.getNextPeer.bind(r,e,t)}for await(const e of this.nextPeer()){if(!this._started)return;const{peerInfo:t,shardInfo:r}=e;if(!t)continue;const n={[ub]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let s=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(ub)||(s=!0,await this._components.peerStore.merge(t.id,{tags:n})):(s=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:mn(r)}}})),s&&this.dispatchEvent(new Ps("peer",{detail:t}))}}stop(){this._started=!1}get[kd](){return!0}get[Symbol.toStringTag](){return en}}function lS(e,t=hb){return r=>new cS(r,{enrUrls:e,wantedNodeCapabilityCount:t})}class uS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new uS({query:{numPeers:t},response:void 0})}encode(){return br.encode(this.proto)}static decode(e){const t=br.decode(e);return new uS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const hS="/vac/waku/peer-exchange/2.0.0-alpha1",dS=new vn("peer-exchange");class pS extends is{constructor(e,t){super(hS,e,dS,t)}async query(e){const{numPeers:t,peerId:r}=e,n=uS.createRequest({numPeers:BigInt(t)}),s=await this.components.peerStore.get(r);if(!s)return{peerInfos:null,error:Jr.NO_PEER_AVAILABLE};let o;try{o=await this.getStream(s)}catch(e){return dS.error("Failed to get stream",e),{peerInfos:null,error:Jr.NO_STREAM_AVAILABLE}}const i=await Xn([n.encode()],Un,o,jn,(async e=>await Tn(e)));try{const e=new Ln;i.forEach((t=>{e.append(t)}));const{response:t}=uS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(kr).map((async e=>({ENR:await ev.fromRLP(e)})))),error:null}:(dS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:Jr.EMPTY_PAYLOAD})}catch(e){return dS.error("Failed to decode push reply",e),{peerInfos:null,error:Jr.DECODE_FAILED}}}}const fS=new vn("peer-exchange-discovery"),gS=1e4,yS=3,mS=Xr.PEER_EXCHANGE;class bS extends xs{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(hS)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>fS.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new pS(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new Ps("waku:peer-exchange:started",{detail:!0})),fS.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(fS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[kd](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=gS,maxRetries:n=yS}=this.options;fS.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const s=this.queryAttempts.get(t)??1;s>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,s+1),this.startRecurringQueries(e).catch((e=>{fS.error(`Error in startRecurringQueries: ${e}`)}))}),r*s)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return fS.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){fS.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:s}=t;if(r&&n){if(await this.components.peerStore.has(r)){const{hasMultiaddrDiff:e,hasShardDiff:t}=await this.checkPeerInfoDiff(n,s);if(e||t){fS.info(`Peer ${r.toString()} has updated multiaddrs or shardInfo, updating`),e&&(fS.info(`Peer ${r.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(r,{multiaddrs:n.multiaddrs})),t&&s&&(fS.info(`Peer ${r.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(r,{metadata:{shardInfo:mn(s)}}),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})));continue}}await this.components.peerStore.save(r,{tags:{[mS]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...s&&{metadata:{shardInfo:mn(s)}},...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),fS.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))}}return{error:null,peerInfos:r}}abortQueriesForPeer(e){fS.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}async checkPeerInfoDiff(e,t){const{id:r}=e,n=await this.components.peerStore.get(r),s=n.addresses.map((e=>e.multiaddr.toString())),o=e.multiaddrs.map((e=>e.toString())),i=s.some((e=>!o.includes(e)));let a=!1;const c=n.metadata.get("shardInfo");if(c){const e=yn(c);(e||t)&&(a=e.clusterId!==t?.clusterId||e.shards.some((e=>!t?.shards.includes(e))))}return{hasMultiaddrDiff:i,hasShardDiff:a}}}function wS(e){return t=>new bS(t,e)}const vS=new vn("peer-exchange-discovery"),ES=Xr.LOCAL;class SS extends xs{components;options;isStarted;peers=[];constructor(e,t){super(),this.components=e,this.options=t,this.isStarted=!1,this.peers=this.getPeersFromLocalStorage()}get[Symbol.toStringTag](){return"@waku/local-peer-cache-discovery"}async start(){if(!this.isStarted){vS.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=await vg({id:e});await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[_o(t)],tags:{[this.options?.tagName??ES]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new Ps("peer",{detail:{id:r,multiaddrs:[_o(t)]}})))}vS.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&(vS.info("Stopping Local Storage Discovery"),this.components.events.removeEventListener("peer:identify",this.handleNewPeers),this.isStarted=!1,this.savePeersToLocalStorage())}handleNewPeers=e=>{const{peerId:t,listenAddrs:r}=e.detail,n=function(e){const t=e.find((e=>e.toString().includes("ws")||e.toString().includes("wss")));if(!t)throw new Error("No ws multiaddr found in the given addresses");return t}(r),s=this.getPeersFromLocalStorage(),o=s.findIndex((e=>e.id===t.toString()));o>=0?s[o].address=n.toString():s.push({id:t.toString(),address:n.toString()}),this.peers=s,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(AS):[]}catch(e){return vS.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){vS.error("Error saving peers to local storage:",e)}}}function AS(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const _S=new vn("sdk:create");async function kS(e,t,r){t?.hideWebSocketInfo||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));const n=e?{metadata:qs(e)}:{};return async function(e={}){const t=await lb(e);return!1!==e.start&&await t.start(),t}({connectionManager:{minConnections:1},transports:[rg({filter:!1===t?.filterMultiaddrs?Zf:eg})],streamMuxers:[Lf()],connectionEncryption:[_d()],...t,services:{identify:uf({agentVersion:r??"js-waku"}),ping:Uf({maxInboundStreams:t?.pingMaxInboundStreams??10}),...n,...t?.services}})}async function IS(e={}){const{libp2p:t,pubsubTopics:r}=await async function(e){const{networkConfig:t}=e,r=function(e){if("clusterId"in(t=e)&&"shards"in t&&!("contentTopics"in t)){if(0===e.shards.length)throw new Error("Invalid shards configuration: please provide at least one shard");return un(e)}if(function(e){return"contentTopics"in e}(e)){if(0===e.contentTopics.length)throw new Error("Invalid content topics configuration: please provide at least one content topic");return e.contentTopics.map((t=>fn(t,e.clusterId)))}throw new Error("Unknown shard config. Please use ShardInfo or ContentTopicInfo");var t}(t??tn);_S.info("Creating Waku node with pubsub topics",r);const n=e?.libp2p??{},s=n.peerDiscovery??[];var o;return e?.defaultBootstrap&&s.push(...function(e){return[lS(["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"]),(e,t)=>new SS(e,t),wS(e)]}(r)),e?.bootstrapPeers&&s.push((o={list:e.bootstrapPeers},e=>new sp(e,o))),n.peerDiscovery=s,{libp2p:await kS(r,n,e?.userAgent),pubsubTopics:r}}(e);return new Xo(r,e,t,{store:!0,lightpush:!0,filter:!0})}var RS,TS=__webpack_require__(2549),CS=function(e,t,r,n){return new(r||(r=Promise))((function(s,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},NS=function(e,t){var r,n,s,o={label:0,sent:function(){if(1&s[0])throw s[1];return s[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(o=0)),o;)try{if(r=1,n&&(s=2&a[0]?n.return:a[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,a[1])).done)return s;switch(n=0,s&&(a=[2&a[0],s.value]),a[0]){case 0:case 1:s=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,n=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!((s=(s=o.trys).length>0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]0?[4,this.send(this.queue)]:[3,2];case 1:e.sent()&&(console.log("Sent ",this.queue.length," telemetry logs"),this.queue=[]),e.label=2;case 2:return[2]}}))}))}),this.intervalPeriod)),[2]}))}))},e.prototype.stop=function(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)},e.prototype.send=function(e){return CS(this,void 0,void 0,(function(){var t,r,n,s=this;return NS(this,(function(o){switch(o.label){case 0:if(!window.location.hostname.includes("lab.waku.org"))return[2];t=e.map((function(e){return{id:++s.requestId,telemetryType:e.type.toString(),telemetryData:e}})),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=o.sent()).status?(console.log("DEBUG: Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=o.sent(),console.log("DEBUG: Error sending messages to telemetry service",n),[2,!1];case 4:return[2]}}))}))},e}(),PS=function(){return PS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&s[s.length-1])||6!==a[0]&&2!==a[0])){o=0;continue}if(3===a[0]&&(!s||a[1]>s[0]&&a[1]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]0&&e.push(y),p.successes.length>0&&(m=document.createElement("div"),b=document.getElementById("messagesSent"),m.textContent="Message: ".concat(s," ").concat(c," of ").concat(a),b.insertBefore(m,b.firstChild),b.insertBefore(document.createElement("br"),b.firstChild),document.dispatchEvent(GS),c++),c0&&e.push(f),[2]}}))}))},[2,{node:t,startLightPushSequence:s,startFilterSubscription:o}]}}))}))}$S(void 0,void 0,void 0,(function(){function e(){var e=Math.floor(16*Math.random())+5,t=Math.floor(2001*Math.random())+5e3;s(e,t)}var t,r,n,s,o,i,a,c,l;return HS(this,(function(u){switch(u.label){case 0:return[4,YS(t=new xS("https://telemetry.status.im/waku-metrics",5e3))];case 1:return r=u.sent(),n=r.node,s=r.startLightPushSequence,o=r.startFilterSubscription,document.getElementById("peerID").innerText=n.libp2p.peerId.toString(),document.getElementById("runningScreen").style.display="block",[4,t.start()];case 2:return u.sent(),o(),i=0,a=document.getElementById("numSent"),document.addEventListener("messageSent",(function(){i++,a.textContent=i.toString()})),c=0,l=document.getElementById("numReceived"),document.addEventListener("messageReceived",(function(){c++,l.textContent=c.toString()})),document.addEventListener(zS.type,(function(){return e()})),e(),[2]}}))}))})()})(); +(()=>{var __webpack_modules__={8045:e=>{"use strict";e.exports=function(e,t){for(var r=new Array(arguments.length-1),n=0,o=2,s=!0;o{"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),o=new Array(123),s=0;s<64;)o[n[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;r.encode=function(e,t,r){for(var o,s=null,i=[],a=0,c=0;t>2],o=(3&l)<<4,c=1;break;case 1:i[a++]=n[o|l>>4],o=(15&l)<<2,c=2;break;case 2:i[a++]=n[o|l>>6],i[a++]=n[63&l],c=0}a>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,i)),a=0)}return c&&(i[a++]=n[o],i[a++]=61,1===c&&(i[a++]=61)),s?(a&&s.push(String.fromCharCode.apply(String,i.slice(0,a))),s.join("")):String.fromCharCode.apply(String,i.slice(0,a))};var i="invalid encoding";r.decode=function(e,t,r){for(var n,s=r,a=0,c=0;c1)break;if(void 0===(l=o[l]))throw Error(i);switch(a){case 0:n=l,a=1;break;case 1:t[r++]=n<<2|(48&l)>>4,n=l,a=2;break;case 2:t[r++]=(15&n)<<4|(60&l)>>2,n=l,a=3;break;case 3:t[r++]=(3&n)<<6|l,a=0}}if(1===a)throw Error(i);return r-s},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 o(e){if("string"!=typeof e){var r=s();if(t.verbose&&console.log("codegen: "+r),r="return "+r,e){for(var i=Object.keys(e),a=new Array(i.length+1),c=new Array(i.length),l=0;l{"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{"use strict";e.exports=s;var n=r(8045),o=r(4153)("fs");function s(e,t,r){return"function"==typeof t?(r=t,t={}):t||(t={}),r?!t.xhr&&o&&o.readFile?o.readFile(e,(function(n,o){return n&&"undefined"!=typeof XMLHttpRequest?s.xhr(e,t,r):n?r(n):r(null,t.binary?o:o.toString("utf8"))})):s.xhr(e,t,r):n(s,this,e,t)}s.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 o=0;o{"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 o(e,n,o){t[0]=e,n[o]=r[0],n[o+1]=r[1],n[o+2]=r[2],n[o+3]=r[3]}function s(e,n,o){t[0]=e,n[o]=r[3],n[o+1]=r[2],n[o+2]=r[1],n[o+3]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],t[0]}function a(e,n){return r[3]=e[n],r[2]=e[n+1],r[1]=e[n+2],r[0]=e[n+3],t[0]}e.writeFloatLE=n?o:s,e.writeFloatBE=n?s:o,e.readFloatLE=n?i:a,e.readFloatBE=n?a:i}():function(){function t(e,t,r,n){var o=t<0?1:0;if(o&&(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((o<<31|2139095040)>>>0,r,n);else if(t<11754943508222875e-54)e((o<<31|Math.round(t/1401298464324817e-60))>>>0,r,n);else{var s=Math.floor(Math.log(t)/Math.LN2);e((o<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,r,n)}}function i(e,t,r){var n=e(t,r),o=2*(n>>31)+1,s=n>>>23&255,i=8388607&n;return 255===s?i?NaN:o*(1/0):0===s?1401298464324817e-60*o*i:o*Math.pow(2,s-150)*(i+8388608)}e.writeFloatLE=t.bind(null,r),e.writeFloatBE=t.bind(null,n),e.readFloatLE=i.bind(null,o),e.readFloatBE=i.bind(null,s)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),r=new Uint8Array(t.buffer),n=128===r[7];function o(e,n,o){t[0]=e,n[o]=r[0],n[o+1]=r[1],n[o+2]=r[2],n[o+3]=r[3],n[o+4]=r[4],n[o+5]=r[5],n[o+6]=r[6],n[o+7]=r[7]}function s(e,n,o){t[0]=e,n[o]=r[7],n[o+1]=r[6],n[o+2]=r[5],n[o+3]=r[4],n[o+4]=r[3],n[o+5]=r[2],n[o+6]=r[1],n[o+7]=r[0]}function i(e,n){return r[0]=e[n],r[1]=e[n+1],r[2]=e[n+2],r[3]=e[n+3],r[4]=e[n+4],r[5]=e[n+5],r[6]=e[n+6],r[7]=e[n+7],t[0]}function a(e,n){return r[7]=e[n],r[6]=e[n+1],r[5]=e[n+2],r[4]=e[n+3],r[3]=e[n+4],r[2]=e[n+5],r[1]=e[n+6],r[0]=e[n+7],t[0]}e.writeDoubleLE=n?o:s,e.writeDoubleBE=n?s:o,e.readDoubleLE=n?i:a,e.readDoubleBE=n?a:i}():function(){function t(e,t,r,n,o,s){var i=n<0?1:0;if(i&&(n=-n),0===n)e(0,o,s+t),e(1/n>0?0:2147483648,o,s+r);else if(isNaN(n))e(0,o,s+t),e(2146959360,o,s+r);else if(n>17976931348623157e292)e(0,o,s+t),e((i<<31|2146435072)>>>0,o,s+r);else{var a;if(n<22250738585072014e-324)e((a=n/5e-324)>>>0,o,s+t),e((i<<31|a/4294967296)>>>0,o,s+r);else{var c=Math.floor(Math.log(n)/Math.LN2);1024===c&&(c=1023),e(4503599627370496*(a=n*Math.pow(2,-c))>>>0,o,s+t),e((i<<31|c+1023<<20|1048576*a&1048575)>>>0,o,s+r)}}}function i(e,t,r,n,o){var s=e(n,o+t),i=e(n,o+r),a=2*(i>>31)+1,c=i>>>20&2047,l=4294967296*(1048575&i)+s;return 2047===c?l?NaN:a*(1/0):0===c?5e-324*a*l:a*Math.pow(2,c-1075)*(l+4503599627370496)}e.writeDoubleLE=t.bind(null,r,0,4),e.writeDoubleBE=t.bind(null,n,4,0),e.readDoubleLE=i.bind(null,o,0,4),e.readDoubleBE=i.bind(null,s,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 o(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(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)},o=r.normalize=function(e){var t=(e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),r=n(e),o="";r&&(o=t.shift()+"/");for(var s=0;s0&&".."!==t[s-1]?t.splice(--s,2):r?t.splice(s,1):++s:"."===t[s]?t.splice(s,1):++s;return o+t.join("/")};r.resolve=function(e,t,r){return r||(t=o(t)),n(t)?t:(r||(e=o(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?o(e+"/"+t):t)}},9390:e=>{"use strict";e.exports=function(e,t,r){var n=r||8192,o=n>>>1,s=null,i=n;return function(r){if(r<1||r>o)return e(r);i+r>n&&(s=e(n),i=0);var a=t.call(s,i,i+=r);return 7&i&&(i=1+(7|i)),a}}},1447:(e,t)=>{"use strict";var r=t;r.length=function(e){for(var t=0,r=0,n=0;n191&&n<224?s[i++]=(31&n)<<6|63&e[t++]:n>239&&n<365?(n=((7&n)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[i++]=55296+(n>>10),s[i++]=56320+(1023&n)):s[i++]=(15&n)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o?(i&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))},r.write=function(e,t,r){for(var n,o,s=r,i=0;i>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(o=e.charCodeAt(i+1)))?(n=65536+((1023&n)<<10)+(1023&o),++i,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-s}},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,o=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(o=n))})),t.splice(o,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},736:(e,t,r)=>{e.exports=function(e){function t(e){let r,o,s,i=null;function a(...e){if(!a.enabled)return;const n=a,o=Number(new Date),s=o-(r||o);n.diff=s,n.prev=r,n.curr=o,r=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((r,o)=>{if("%%"===r)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];r=s.call(n,t),e.splice(i,1),i--}return r})),t.formatArgs.call(n,e),(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function o(e,t){let r=0,n=0,o=-1,s=0;for(;r"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(" ",",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(o(e,r))return!1;for(const r of t.names)if(o(e,r))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{"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 o=new r;o.highWaterMark=t,o.lowWaterMark=n,o.removeCallback=e({push:e=>o.push(e),stop:()=>o.stop(),fail:e=>o.fail(e),on:(e,t)=>{o.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>o[Symbol.asyncIterator](),Object.freeze(this)}}t.EventIterator=n,t.default=n},228:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function n(){}function o(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function s(e,t,n,s,i){if("function"!=typeof n)throw new TypeError("The listener must be a function");var a=new o(n,s||e,i),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],a]:e._events[c].push(a):(e._events[c]=a,e._eventsCount++),e}function i(e,t){0==--e._eventsCount?e._events=new n:delete e._events[t]}function a(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),a.prototype.eventNames=function(){var e,n,o=[];if(0===this._eventsCount)return o;for(n in e=this._events)t.call(e,n)&&o.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},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 o=0,s=n.length,i=new Array(s);o{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 o(o,s){r[o]=s,++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])?(o(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:o(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}},5818:(e,t,r)=>{var n;!function(){"use strict";var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node&&(t=global);var o=!t.HI_BASE32_NO_COMMON_JS&&e.exports,s=r.amdO,i="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},c=[0,0,0,0,0,0,0,0],l=function(e,t){t.length>10&&(t="..."+t.substr(-10));var r=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw r.position=e,r},u=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,r,n,o,s,i,c,l,u=[],h=0,d=(e=e.replace(/=/g,"")).length,p=0,f=d>>3<<3;p>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1),u[h++]=255&(s<<7|i<<2|c>>>3),u[h++]=255&(c<<5|l);var g=d-f;return 2===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2)):4===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4)):5===g?(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],s=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1)):7===g&&(t=a[e.charAt(p++)],r=a[e.charAt(p++)],n=a[e.charAt(p++)],o=a[e.charAt(p++)],s=a[e.charAt(p++)],i=a[e.charAt(p++)],c=a[e.charAt(p++)],u[h++]=255&(t<<3|r>>>2),u[h++]=255&(r<<6|n<<1|o>>>4),u[h++]=255&(o<<4|s>>>1),u[h++]=255&(s<<7|i<<2|c>>>3)),u},h=function(e,t){if(!t)return function(e){for(var t,r,n="",o=e.length,s=0,i=0;s191&&t<=223?(r=31&t,i=1):t<=239?(r=15&t,i=2):t<=247?(r=7&t,i=3):l(s,n);for(var a=0;a191)&&l(s,n),r<<=6,r+=63&t;r>=55296&&r<=57343&&l(s,n),r>1114111&&l(s,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,o,s,i,c,h,d,p="",f=e.indexOf("=");-1===f&&(f=e.length);for(var g=0,m=f>>3<<3;g>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))+String.fromCharCode(255&(h<<5|d));var y=f-m;return 2===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))):4===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))):5===y?(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=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|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))):7===y&&(r=a[e.charAt(g++)],n=a[e.charAt(g++)],o=a[e.charAt(g++)],s=a[e.charAt(g++)],i=a[e.charAt(g++)],c=a[e.charAt(g++)],h=a[e.charAt(g++)],p+=String.fromCharCode(255&(r<<3|n>>>2))+String.fromCharCode(255&(n<<6|o<<1|s>>>4))+String.fromCharCode(255&(s<<4|i>>>1))+String.fromCharCode(255&(i<<7|c<<2|h>>>3))),p},d={encode:function(e,t){var r="string"!=typeof e;return r&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),r?function(e){for(var t,r,n,o,s,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s];var h=c-u;return 1===h?(t=e[l],a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e[l++],r=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e[l++],r=e[l++],n=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e[l++],r=e[l++],n=e[l++],o=e[l],a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"="),a}(e):t?function(e){for(var t,r,n,o,s,a="",c=e.length,l=0,u=5*parseInt(c/5);l>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s];var h=c-u;return 1===h?(t=e.charCodeAt(l),a+=i[t>>>3]+i[t<<2&31]+"======"):2===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===h?(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):4===h&&(t=e.charCodeAt(l++),r=e.charCodeAt(l++),n=e.charCodeAt(l++),o=e.charCodeAt(l),a+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"="),a}(e):function(e){var t,r,n,o,s,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>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],o=c[3],s=c[4],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[31&(o<<3|s>>>5)]+i[31&s]):1===l?h+=i[t>>>3]+i[t<<2&31]+"======":2===l?(r=c[1],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[r<<4&31]+"===="):3===l?(r=c[1],n=c[2],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[n<<1&31]+"==="):(r=c[1],n=c[2],o=c[3],h+=i[t>>>3]+i[31&(t<<2|r>>>6)]+i[r>>>1&31]+i[31&(r<<4|n>>>4)]+i[31&(n<<1|o>>>7)]+i[o>>>2&31]+i[o<<3&31]+"=")}while(!u);return h}(e)},decode:h};h.asBytes=u,o?e.exports=d:(t.base32=d,s&&(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 o="input is invalid type",s="object"==typeof window,i=s?window:{};i.JS_SHA3_NO_WINDOW&&(s=!1);var a=!s&&"object"==typeof self;!i.JS_SHA3_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node?i=global:a&&(i=self);for(var c=!i.JS_SHA3_NO_COMMON_JS&&e.exports,l=r.amdO,u=!i.JS_SHA3_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,h="0123456789abcdef".split(""),d=[4,1024,262144,67108864],p=[0,8,16,24],f=[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648],g=[224,256,384,512],m=[128,256],y=["hex","buffer","arrayBuffer","array","digest"],b={128:168,256:136},w=i.JS_SHA3_NO_NODE_JS||!Array.isArray?function(e){return"[object Array]"===Object.prototype.toString.call(e)}:Array.isArray,v=!u||!i.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView?ArrayBuffer.isView:function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer},E=function(e){var t=typeof e;if("string"===t)return[e,!0];if("object"!==t||null===e)throw new Error(o);if(u&&e.constructor===ArrayBuffer)return[new Uint8Array(e),!1];if(!w(e)&&!v(e))throw new Error(o);return[e,!1]},S=function(e){return 0===E(e)[0].length},A=function(e){for(var t=[],r=0;r>5,this.byteCount=this.blockCount<<2,this.outputBlocks=r>>5,this.extraBytes=(31&r)>>3;for(var n=0;n<50;++n)this.s[n]=0}function $(e,t,r){F.call(this,e,t,r)}F.prototype.update=function(e){if(this.finalized)throw new Error("finalize already called");var t=E(e);e=t[0];for(var r,n,o=t[1],s=this.blocks,i=this.byteCount,a=e.length,c=this.blockCount,l=0,u=this.s;l>2]|=n<>2]|=(192|n>>6)<>2]|=(128|63&n)<=57344?(s[r>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|63&n)<>2]|=e[l]<=i){for(this.start=r-i,this.block=s[c],r=0;r>=8);r>0;)o.unshift(r),r=255&(e>>=8),++n;return t?o.push(n):o.unshift(n),this.update(o),o.length},F.prototype.encodeString=function(e){var t=E(e);e=t[0];var r=t[1],n=0,o=e.length;if(r)for(var s=0;s=57344?n+=3:(i=65536+((1023&i)<<10|1023&e.charCodeAt(++s)),n+=4)}else n=o;return n+=this.encode(8*n),this.update(e),n},F.prototype.bytepad=function(e,t){for(var r=this.encode(t),n=0;n>2]|=this.padding[3&t],this.lastByteIndex===this.byteCount)for(e[0]=e[r],t=1;t>4&15]+h[15&e]+h[e>>12&15]+h[e>>8&15]+h[e>>20&15]+h[e>>16&15]+h[e>>28&15]+h[e>>24&15];i%t==0&&(r=A(r),q(r),s=0)}return o&&(e=r[s],a+=h[e>>4&15]+h[15&e],o>1&&(a+=h[e>>12&15]+h[e>>8&15]),o>2&&(a+=h[e>>20&15]+h[e>>16&15])),a},F.prototype.arrayBuffer=function(){this.finalize();var e,t=this.blockCount,r=this.s,n=this.outputBlocks,o=this.extraBytes,s=0,i=0,a=this.outputBits>>3;e=o?new ArrayBuffer(n+1<<2):new ArrayBuffer(a);for(var c=new Uint32Array(e);i>8&255,c[e+2]=t>>16&255,c[e+3]=t>>24&255;a%r==0&&(n=A(n),q(n))}return s&&(e=a<<2,t=n[i],c[e]=255&t,s>1&&(c[e+1]=t>>8&255),s>2&&(c[e+2]=t>>16&255)),c},$.prototype=new F,$.prototype.finalize=function(){return this.encode(this.outputBits,!0),F.prototype.finalize.call(this)};var q=function(e){var t,r,n,o,s,i,a,c,l,u,h,d,p,g,m,y,b,w,v,E,S,A,k,C,I,x,T,_,N,P,L,B,O,R,D,U,M,F,$,q,H,j,V,z,K,G,W,J,X,Y,Z,Q,ee,te,re,ne,oe,se,ie,ae,ce,le,ue;for(n=0;n<48;n+=2)o=e[0]^e[10]^e[20]^e[30]^e[40],s=e[1]^e[11]^e[21]^e[31]^e[41],i=e[2]^e[12]^e[22]^e[32]^e[42],a=e[3]^e[13]^e[23]^e[33]^e[43],c=e[4]^e[14]^e[24]^e[34]^e[44],l=e[5]^e[15]^e[25]^e[35]^e[45],u=e[6]^e[16]^e[26]^e[36]^e[46],h=e[7]^e[17]^e[27]^e[37]^e[47],t=(d=e[8]^e[18]^e[28]^e[38]^e[48])^(i<<1|a>>>31),r=(p=e[9]^e[19]^e[29]^e[39]^e[49])^(a<<1|i>>>31),e[0]^=t,e[1]^=r,e[10]^=t,e[11]^=r,e[20]^=t,e[21]^=r,e[30]^=t,e[31]^=r,e[40]^=t,e[41]^=r,t=o^(c<<1|l>>>31),r=s^(l<<1|c>>>31),e[2]^=t,e[3]^=r,e[12]^=t,e[13]^=r,e[22]^=t,e[23]^=r,e[32]^=t,e[33]^=r,e[42]^=t,e[43]^=r,t=i^(u<<1|h>>>31),r=a^(h<<1|u>>>31),e[4]^=t,e[5]^=r,e[14]^=t,e[15]^=r,e[24]^=t,e[25]^=r,e[34]^=t,e[35]^=r,e[44]^=t,e[45]^=r,t=c^(d<<1|p>>>31),r=l^(p<<1|d>>>31),e[6]^=t,e[7]^=r,e[16]^=t,e[17]^=r,e[26]^=t,e[27]^=r,e[36]^=t,e[37]^=r,e[46]^=t,e[47]^=r,t=u^(o<<1|s>>>31),r=h^(s<<1|o>>>31),e[8]^=t,e[9]^=r,e[18]^=t,e[19]^=r,e[28]^=t,e[29]^=r,e[38]^=t,e[39]^=r,e[48]^=t,e[49]^=r,g=e[0],m=e[1],G=e[11]<<4|e[10]>>>28,W=e[10]<<4|e[11]>>>28,_=e[20]<<3|e[21]>>>29,N=e[21]<<3|e[20]>>>29,ae=e[31]<<9|e[30]>>>23,ce=e[30]<<9|e[31]>>>23,j=e[40]<<18|e[41]>>>14,V=e[41]<<18|e[40]>>>14,R=e[2]<<1|e[3]>>>31,D=e[3]<<1|e[2]>>>31,y=e[13]<<12|e[12]>>>20,b=e[12]<<12|e[13]>>>20,J=e[22]<<10|e[23]>>>22,X=e[23]<<10|e[22]>>>22,P=e[33]<<13|e[32]>>>19,L=e[32]<<13|e[33]>>>19,le=e[42]<<2|e[43]>>>30,ue=e[43]<<2|e[42]>>>30,te=e[5]<<30|e[4]>>>2,re=e[4]<<30|e[5]>>>2,U=e[14]<<6|e[15]>>>26,M=e[15]<<6|e[14]>>>26,w=e[25]<<11|e[24]>>>21,v=e[24]<<11|e[25]>>>21,Y=e[34]<<15|e[35]>>>17,Z=e[35]<<15|e[34]>>>17,B=e[45]<<29|e[44]>>>3,O=e[44]<<29|e[45]>>>3,C=e[6]<<28|e[7]>>>4,I=e[7]<<28|e[6]>>>4,ne=e[17]<<23|e[16]>>>9,oe=e[16]<<23|e[17]>>>9,F=e[26]<<25|e[27]>>>7,$=e[27]<<25|e[26]>>>7,E=e[36]<<21|e[37]>>>11,S=e[37]<<21|e[36]>>>11,Q=e[47]<<24|e[46]>>>8,ee=e[46]<<24|e[47]>>>8,z=e[8]<<27|e[9]>>>5,K=e[9]<<27|e[8]>>>5,x=e[18]<<20|e[19]>>>12,T=e[19]<<20|e[18]>>>12,se=e[29]<<7|e[28]>>>25,ie=e[28]<<7|e[29]>>>25,q=e[38]<<8|e[39]>>>24,H=e[39]<<8|e[38]>>>24,A=e[48]<<14|e[49]>>>18,k=e[49]<<14|e[48]>>>18,e[0]=g^~y&w,e[1]=m^~b&v,e[10]=C^~x&_,e[11]=I^~T&N,e[20]=R^~U&F,e[21]=D^~M&$,e[30]=z^~G&J,e[31]=K^~W&X,e[40]=te^~ne&se,e[41]=re^~oe&ie,e[2]=y^~w&E,e[3]=b^~v&S,e[12]=x^~_&P,e[13]=T^~N&L,e[22]=U^~F&q,e[23]=M^~$&H,e[32]=G^~J&Y,e[33]=W^~X&Z,e[42]=ne^~se&ae,e[43]=oe^~ie&ce,e[4]=w^~E&A,e[5]=v^~S&k,e[14]=_^~P&B,e[15]=N^~L&O,e[24]=F^~q&j,e[25]=$^~H&V,e[34]=J^~Y&Q,e[35]=X^~Z&ee,e[44]=se^~ae&le,e[45]=ie^~ce&ue,e[6]=E^~A&g,e[7]=S^~k&m,e[16]=P^~B&C,e[17]=L^~O&I,e[26]=q^~j&R,e[27]=H^~V&D,e[36]=Y^~Q&z,e[37]=Z^~ee&K,e[46]=ae^~le&te,e[47]=ce^~ue&re,e[8]=A^~g&y,e[9]=k^~m&b,e[18]=B^~C&x,e[19]=O^~I&T,e[28]=j^~R&U,e[29]=V^~D&M,e[38]=Q^~z&G,e[39]=ee^~K&W,e[48]=le^~te&ne,e[49]=ue^~re&oe,e[0]^=f[n],e[1]^=f[n+1]};if(c)e.exports=P;else{for(B=0;BObject.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)o.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){const r=Object.getOwnPropertySymbols(e);for(const n of r)s.call(e,n)&&t.push(n)}return t};function u(e){return Array.isArray(e)?function(e){const t=e.slice(0,0);return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):n(e)?function(e){const t=null===Object.getPrototypeOf(e)?Object.create(null):{};return l(e).forEach((r=>{i(t,r,u(e[r]))})),t}(e):e}const h=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?i(e,r,p(e[r],t[r],n)):i(e,r,u(t[r])))})),e),d=(e,t,r)=>{let n=e.slice(0,0),s=0;return[e,t].forEach((t=>{const a=[];for(let r=0;r!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 o of e)if(void 0!==o){if(!n(o))throw new TypeError("`"+o+"` is not an Option Object");r=p(r,{_:o},t)}return r._}},6585:e=>{var t=1e3,r=60*t,n=60*r,o=24*n,s=7*o;function i(e,t,r,n){var o=t>=1.5*r;return Math.round(e/r)+" "+n+(o?"s":"")}e.exports=function(e,a){a=a||{};var c,l,u=typeof e;if("string"===u&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var i=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(i){var a=parseFloat(i[1]);switch((i[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*a;case"weeks":case"week":case"w":return a*s;case"days":case"day":case"d":return a*o;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))>=o?i(c,l,o,"day"):l>=n?i(c,l,n,"hour"):l>=r?i(c,l,r,"minute"):l>=t?i(c,l,t,"second"):c+" ms"):function(e){var s=Math.abs(e);return s>=o?Math.round(e/o)+"d":s>=n?Math.round(e/n)+"h":s>=r?Math.round(e/r)+"m":s>=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 o={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function s(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t255)return!1;return!0}function i(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function a(e,t){return e<>>32-t}function c(e){return e=i(e^=e>>>16,2246822507),(e=i(e^=e>>>13,3266489909))^e>>>16}function l(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function h(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<>>32-t,e[1]<>>32-t]:(t-=32,[e[1]<>>32-t,e[0]<>>32-t])}function d(e,t){return 0==(t%=64)?e:t<32?[e[0]<>>32-t,e[1]<>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}o.x86.hash32=function(e,t){if(o.inputValidation&&!s(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>>0},o.x86.hash128=function(e,t){if(o.inputValidation&&!s(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,m=0,y=0,b=597399067,w=2869860233,v=951274213,E=2716044179,S=0;S>>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)},o.x64.hash128=function(e,t){if(o.inputValidation&&!s(e))return n;t=t||0;for(var r=e.length%16,i=e.length-r,a=[0,t],c=[0,t],g=[0,0],m=[0,0],y=[2277735313,289559509],b=[1291169091,658871167],w=0;w>>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=o),t.murmurHash3=o}()},5507:function(e,t){(function(){var e,r,n,o,s,i,a,c;c=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var t,n,o,s,i,a;for(t=[],o=s=0;s<=3&&0!==e.length;o=++s){if(o>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}i=(a=r(e))[0],n=a[1],e=e.substring(n),t.push(i)}if(0!==e.length)throw new Error("Invalid IP");switch(t.length){case 1:if(t[0]>4294967295)throw new Error("Invalid IP");return t[0]>>>0;case 2:if(t[0]>255||t[1]>16777215)throw new Error("Invalid IP");return(t[0]<<24|t[1])>>>0;case 3:if(t[0]>255||t[1]>255||t[2]>65535)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2])>>>0;case 4:if(t[0]>255||t[1]>255||t[2]>255||t[3]>255)throw new Error("Invalid IP");return(t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0;default:throw new Error("Invalid IP")}},o=(n=function(e){return e.charCodeAt(0)})("0"),i=n("a"),s=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>>0;else{if(16!==t)break;if("a"<=e[a]&&e[a]<="f")c=c*t+(10+n(e[a])-i)>>>0;else{if(!("A"<=e[a]&&e[a]<="F"))break;c=c*t+(10+n(e[a])-s)>>>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,o;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(o=e.split("/",2),e=o[0],t=o[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=c(this.netLong),this.mask=c(this.maskLong),this.hostmask=c(~this.maskLong),this.first=this.bitmask<=30?c(this.netLong+1):this.base,this.last=this.bitmask<=30?c(this.netLong+this.size-2):c(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?c(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(c(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(c(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),t.ip2long=a,t.long2ip=c,t.Netmask=e}).call(this)},2549:(e,t,r)=>{"use strict";e.exports=r(9100)},5095:e=>{"use strict";e.exports=n;var t,r=/\/|\./;function n(e,t){r.test(e)||(e="google/protobuf/"+e+".proto",t={nested:{google:{nested:{protobuf:{nested:t}}}}}),n[e]=t}n("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),n("duration",{Duration:t={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),n("timestamp",{Timestamp:t}),n("empty",{Empty:{fields:{}}}),n("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),n("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),n("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),n.get=function(e){return n[e]||null}},744:(e,t,r)=>{"use strict";var n=t,o=r(5643),s=r(3262);function i(e,t,r,n){var s=!1;if(t.resolvedType)if(t.resolvedType instanceof o){e("switch(d%s){",n);for(var i=t.resolvedType.values,a=Object.keys(i),c=0;c>>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 o?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 s=!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":s=!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,s?"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=s.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{"use strict";e.exports=function(e){var t=s.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>>3){");for(var r=0;r>>3){")("case 1: k=r.%s(); break",a.keyType)("case 2:"),void 0===o.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!==o.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!==o.packed[c]&&t("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos{"use strict";e.exports=function(e){for(var t,r=s.codegen(["m","w"],e.name+"$encode")("if(!w)")("w=Writer.create()"),a=e.fieldsArray.slice().sort(s.compareFieldsById),c=0;c>>0,8|o.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!==o.packed[h]?r("w.uint32(%i).fork()",(l.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",t)("w.%s(%s[i])",h,t)("w.ldelim()"):(r("for(var i=0;i<%s.length;++i)",t),void 0===d?i(r,l,u,t+"[i]"):r("w.uint32(%i).%s(%s[i])",(l.id<<3|d)>>>0,h,t)),r("}")):(l.optional&&r("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",t,l.name),void 0===d?i(r,l,u,t):r("w.uint32(%i).%s(%s)",(l.id<<3|d)>>>0,h,t))}return r("return w")};var n=r(5643),o=r(361),s=r(3262);function i(e,t,r,n){return t.resolvedType.group?e("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",r,n,(t.id<<3|3)>>>0,(t.id<<3|4)>>>0):e("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",r,n,(t.id<<3|2)>>>0)}},5643:(e,t,r)=>{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="Enum";var o=r(8923),s=r(3262);function i(e,t,r,o,s,i){if(n.call(this,e,r),t&&"object"!=typeof t)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=o,this.comments=s||{},this.valuesOptions=i,this.reserved=void 0,t)for(var a=Object.keys(t),c=0;c{"use strict";e.exports=l;var n=r(7209);((l.prototype=Object.create(n.prototype)).constructor=l).className="Field";var o,s=r(5643),i=r(361),a=r(3262),c=/^required|optional|repeated$/;function l(e,t,r,o,s,l,u){if(a.isObject(o)?(u=s,l=o,o=s=void 0):a.isObject(s)&&(u=l,l=s,s=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!==o&&!c.test(o=o.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(void 0!==s&&!a.isString(s))throw TypeError("extend must be a string");"proto3_optional"===o&&(o="optional"),this.rule=o&&"optional"!==o?o:void 0,this.type=r,this.id=t,this.extend=s||void 0,this.required="required"===o,this.optional=!this.required,this.repeated="repeated"===o,this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=!!a.Long&&void 0!==i.long[r],this.bytes="bytes"===r,this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=u}l.fromJSON=function(e,t){return new l(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)},Object.defineProperty(l.prototype,"packed",{get:function(){return null===this._packed&&(this._packed=!1!==this.getOption("packed")),this._packed}}),l.prototype.setOption=function(e,t,r){return"packed"===e&&(this._packed=null),n.prototype.setOption.call(this,e,t,r)},l.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return a.toObject(["rule","optional"!==this.rule&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},l.prototype.resolve=function(){if(this.resolved)return this;if(void 0===(this.typeDefault=i.defaults[this.type])?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof o?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&null!=this.options.default&&(this.typeDefault=this.options.default,this.resolvedType instanceof s&&"string"==typeof this.typeDefault&&(this.typeDefault=this.resolvedType.values[this.typeDefault])),this.options&&(!0!==this.options.packed&&(void 0===this.options.packed||!this.resolvedType||this.resolvedType instanceof s)||delete this.options.packed,Object.keys(this.options).length||(this.options=void 0)),this.long)this.typeDefault=a.Long.fromNumber(this.typeDefault,"u"===this.type.charAt(0)),Object.freeze&&Object.freeze(this.typeDefault);else if(this.bytes&&"string"==typeof this.typeDefault){var 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 o&&(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(o,s){a.decorateType(o.constructor).add(new l(s,e,t,r,{default:n}))}},l._configure=function(e){o=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 o(){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=o,o()},9100:(e,t,r)=>{"use strict";var n=e.exports=r(5325);n.build="full",n.tokenize=r(527),n.parse=r(4863),n.common=r(5095),n.Root._configure(n.Type,n.parse,n.common)},8252:(e,t,r)=>{"use strict";e.exports=i;var n=r(1344);((i.prototype=Object.create(n.prototype)).constructor=i).className="MapField";var o=r(361),s=r(3262);function i(e,t,r,o,i,a){if(n.call(this,e,t,o,void 0,void 0,i,a),!s.isString(r))throw TypeError("keyType must be a string");this.keyType=r,this.resolvedKeyType=null,this.map=!0}i.fromJSON=function(e,t){return new i(e,t.id,t.keyType,t.type,t.options,t.comment)},i.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return s.toObject(["keyType",this.keyType,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])},i.prototype.resolve=function(){if(this.resolved)return this;if(void 0===o.mapKey[this.keyType])throw Error("invalid key type: "+this.keyType);return n.prototype.resolve.call(this)},i.d=function(e,t,r){return"function"==typeof r?r=s.decorateType(r).name:r&&"object"==typeof r&&(r=s.decorateEnum(r).name),function(n,o){s.decorateType(n.constructor).add(new i(o,e,t,r))}}},2551:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(e){if(e)for(var t=Object.keys(e),r=0;r{"use strict";e.exports=s;var n=r(7209);((s.prototype=Object.create(n.prototype)).constructor=s).className="Method";var o=r(3262);function s(e,t,r,s,i,a,c,l,u){if(o.isObject(i)?(c=i,i=a=void 0):o.isObject(a)&&(c=a,a=void 0),void 0!==t&&!o.isString(t))throw TypeError("type must be a string");if(!o.isString(r))throw TypeError("requestType must be a string");if(!o.isString(s))throw TypeError("responseType must be a string");n.call(this,e,c),this.type=t||"rpc",this.requestType=r,this.requestStream=!!i||void 0,this.responseType=s,this.responseStream=!!a||void 0,this.resolvedRequestType=null,this.resolvedResponseType=null,this.comment=l,this.parsedOptions=u}s.fromJSON=function(e,t){return new s(e,t.type,t.requestType,t.responseType,t.requestStream,t.responseStream,t.options,t.comment,t.parsedOptions)},s.prototype.toJSON=function(e){var t=!!e&&Boolean(e.keepComments);return o.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])},s.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 o,s,i,a=r(1344),c=r(3262),l=r(1457);function u(e,t){if(e&&e.length){for(var r={},n=0;nt)return!0;return!1},h.isReservedName=function(e,t){if(e)for(var r=0;r0;){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-1)return n}else if(n instanceof h&&(n=n.lookup(e.slice(1),t,!0)))return n}else for(var o=0;o{"use strict";e.exports=s,s.className="ReflectionObject";var n,o=r(3262);function s(e,t){if(!o.isString(e))throw TypeError("name must be a string");if(t&&!o.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(s.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(".")}}}),s.prototype.toJSON=function(){throw Error()},s.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)},s.prototype.onRemove=function(e){var t=e.root;t instanceof n&&t._handleRemove(this),this.parent=null,this.resolved=!1},s.prototype.resolve=function(){return this.resolved||this.root instanceof n&&(this.resolved=!0),this},s.prototype.getOption=function(e){if(this.options)return this.options[e]},s.prototype.setOption=function(e,t,r){return r&&this.options&&void 0!==this.options[e]||((this.options||(this.options={}))[e]=t),this},s.prototype.setParsedOption=function(e,t,r){this.parsedOptions||(this.parsedOptions=[]);var n=this.parsedOptions;if(r){var s=n.find((function(t){return Object.prototype.hasOwnProperty.call(t,e)}));if(s){var i=s[e];o.setProperty(i,r,t)}else(s={})[e]=o.setProperty({},r,t),n.push(s)}else{var a={};a[e]=t,n.push(a)}return this},s.prototype.setOptions=function(e,t){if(e)for(var r=Object.keys(e),n=0;n{"use strict";e.exports=i;var n=r(7209);((i.prototype=Object.create(n.prototype)).constructor=i).className="OneOf";var o=r(1344),s=r(3262);function i(e,t,r,o){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=o}function a(e){if(e.parent)for(var t=0;t-1&&this.oneof.splice(t,1),e.partOf=null,this},i.prototype.onAdd=function(e){n.prototype.onAdd.call(this,e);for(var t=0;t{"use strict";e.exports=k,k.filename=null,k.defaults={keepCase:!1};var n=r(527),o=r(5330),s=r(7882),i=r(1344),a=r(8252),c=r(1457),l=r(5643),u=r(9687),h=r(8811),d=r(361),p=r(3262),f=/^[1-9][0-9]*$/,g=/^-?[1-9][0-9]*$/,m=/^0[x][0-9a-fA-F]+$/,y=/^-?0[x][0-9a-fA-F]+$/,b=/^0[0-7]+$/,w=/^-?0[0-7]+$/,v=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,E=/^[a-zA-Z_][a-zA-Z_0-9]*$/,S=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,A=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function k(e,t,r){t instanceof o||(r=t,t=new o),r||(r=k.defaults);var C,I,x,T,_,N=r.preferTrailingComment||!1,P=n(e,r.alternateCommentMode||!1),L=P.next,B=P.push,O=P.peek,R=P.skip,D=P.cmnt,U=!0,M=!1,F=t,$=r.keepCase?function(e){return e}:p.camelCase;function q(e,t,r){var n=k.filename;return r||(k.filename=null),Error("illegal "+(t||"token")+" '"+e+"' ("+(n?n+", ":"")+"line "+P.line+")")}function H(){var e,t=[];do{if('"'!==(e=L())&&"'"!==e)throw q(e);t.push(L()),R(e),e=O()}while('"'===e||"'"===e);return t.join("")}function j(e){var t=L();switch(t){case"'":case'"':return B(t),H();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return function(e){var t=1;switch("-"===e.charAt(0)&&(t=-1,e=e.substring(1)),e){case"inf":case"INF":case"Inf":return t*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(f.test(e))return t*parseInt(e,10);if(m.test(e))return t*parseInt(e,16);if(b.test(e))return t*parseInt(e,8);if(v.test(e))return t*parseFloat(e);throw q(e,"number",!0)}(t)}catch(r){if(e&&S.test(t))return t;throw q(t,"value")}}function V(e,t){var r,n;do{!t||'"'!==(r=O())&&"'"!==r?e.push([n=z(L()),R("to",!0)?z(L()):n]):e.push(H())}while(R(",",!0));var o={options:void 0,setOption:function(e,t){void 0===this.options&&(this.options={}),this.options[e]=t}};X(o,(function(e){if("option"!==e)throw q(e);ee(o,e),R(";")}),(function(){ne(o)}))}function z(e,t){switch(e){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!t&&"-"===e.charAt(0))throw q(e,"id");if(g.test(e))return parseInt(e,10);if(y.test(e))return parseInt(e,16);if(w.test(e))return parseInt(e,8);throw q(e,"id")}function K(){if(void 0!==C)throw q("package");if(C=L(),!S.test(C))throw q(C,"name");F=F.define(C),R(";")}function G(){var e,t=O();switch(t){case"weak":e=x||(x=[]),L();break;case"public":L();default:e=I||(I=[])}t=H(),R(";"),e.push(t)}function W(){if(R("="),T=H(),!(M="proto3"===T)&&"proto2"!==T)throw q(T,"syntax");t.setOption("syntax",T),R(";")}function J(e,t){switch(t){case"option":return ee(e,t),R(";"),!0;case"message":return Y(e,t),!0;case"enum":return Q(e,t),!0;case"service":return function(e,t){if(!E.test(t=L()))throw q(t,"service name");var r=new u(t);X(r,(function(e){if(!J(r,e)){if("rpc"!==e)throw q(e);!function(e,t){var r=D(),n=t;if(!E.test(t=L()))throw q(t,"name");var o,s,i,a,c=t;if(R("("),R("stream",!0)&&(s=!0),!S.test(t=L()))throw q(t);if(o=t,R(")"),R("returns"),R("("),R("stream",!0)&&(a=!0),!S.test(t=L()))throw q(t);i=t,R(")");var l=new h(c,n,o,i,s,a);l.comment=r,X(l,(function(e){if("option"!==e)throw q(e);ee(l,e),R(";")})),e.add(l)}(r,e)}})),e.add(r)}(e,t),!0;case"extend":return function(e,t){if(!S.test(t=L()))throw q(t,"reference");var r=t;X(null,(function(t){switch(t){case"required":case"repeated":Z(e,t,r);break;case"optional":Z(e,M?"proto3_optional":"optional",r);break;default:if(!M||!S.test(t))throw q(t);B(t),Z(e,"optional",r)}}))}(e,t),!0}return!1}function X(e,t,r){var n=P.line;if(e&&("string"!=typeof e.comment&&(e.comment=D()),e.filename=k.filename),R("{",!0)){for(var o;"}"!==(o=L());)t(o);R(";",!0)}else r&&r(),R(";"),e&&("string"!=typeof e.comment||N)&&(e.comment=D(n)||e.comment)}function Y(e,t){if(!E.test(t=L()))throw q(t,"type name");var r=new s(t);X(r,(function(e){if(!J(r,e))switch(e){case"map":!function(e){R("<");var t=L();if(void 0===d.mapKey[t])throw q(t,"type");R(",");var r=L();if(!S.test(r))throw q(r,"type");R(">");var n=L();if(!E.test(n))throw q(n,"name");R("=");var o=new a($(n),z(L()),t,r);X(o,(function(e){if("option"!==e)throw q(e);ee(o,e),R(";")}),(function(){ne(o)})),e.add(o)}(r);break;case"required":case"repeated":Z(r,e);break;case"optional":Z(r,M?"proto3_optional":"optional");break;case"oneof":!function(e,t){if(!E.test(t=L()))throw q(t,"name");var r=new c($(t));X(r,(function(e){"option"===e?(ee(r,e),R(";")):(B(e),Z(r,"optional"))})),e.add(r)}(r,e);break;case"extensions":V(r.extensions||(r.extensions=[]));break;case"reserved":V(r.reserved||(r.reserved=[]),!0);break;default:if(!M||!S.test(e))throw q(e);B(e),Z(r,"optional")}})),e.add(r)}function Z(e,t,r){var n=L();if("group"!==n){for(;n.endsWith(".")||O().startsWith(".");)n+=L();if(!S.test(n))throw q(n,"type");var o=L();if(!E.test(o))throw q(o,"name");o=$(o),R("=");var a=new i(o,z(L()),n,t,r);if(X(a,(function(e){if("option"!==e)throw q(e);ee(a,e),R(";")}),(function(){ne(a)})),"proto3_optional"===t){var l=new c("_"+o);a.setOption("proto3_optional",!0),l.add(a),e.add(l)}else e.add(a);M||!a.repeated||void 0===d.packed[n]&&void 0!==d.basic[n]||a.setOption("packed",!1,!0)}else!function(e,t){var r=L();if(!E.test(r))throw q(r,"name");var n=p.lcFirst(r);r===n&&(r=p.ucFirst(r)),R("=");var o=z(L()),a=new s(r);a.group=!0;var c=new i(n,o,r,t);c.filename=k.filename,X(a,(function(e){switch(e){case"option":ee(a,e),R(";");break;case"required":case"repeated":Z(a,e);break;case"optional":Z(a,M?"proto3_optional":"optional");break;case"message":Y(a,e);break;case"enum":Q(a,e);break;default:throw q(e)}})),e.add(a).add(c)}(e,t)}function Q(e,t){if(!E.test(t=L()))throw q(t,"name");var r=new l(t);X(r,(function(e){switch(e){case"option":ee(r,e),R(";");break;case"reserved":V(r.reserved||(r.reserved=[]),!0);break;default:!function(e,t){if(!E.test(t))throw q(t,"name");R("=");var r=z(L(),!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 q(e);ee(n,e),R(";")}),(function(){ne(n)})),e.add(t,r,n.comment,n.options)}(r,e)}})),e.add(r)}function ee(e,t){var r=R("(",!0);if(!S.test(t=L()))throw q(t,"name");var n,o=t,s=o;r&&(R(")"),s=o="("+o+")",t=O(),A.test(t)&&(n=t.slice(1),o+=t,L())),R("="),function(e,t,r,n){e.setParsedOption&&e.setParsedOption(t,r,n)}(e,s,te(e,o),n)}function te(e,t){if(R("{",!0)){for(var r={};!R("}",!0);){if(!E.test(_=L()))throw q(_,"name");if(null===_)throw q(_,"end of input");var n,o=_;if(R(":",!0),"{"===O())n=te(e,t+"."+_);else if("["===O()){var s;if(n=[],R("[",!0)){do{s=j(!0),n.push(s)}while(R(",",!0));R("]"),void 0!==s&&re(e,t+"."+_,s)}}else n=j(!0),re(e,t+"."+_,n);var i=r[o];i&&(n=[].concat(i).concat(n)),r[o]=n,R(",",!0),R(";",!0)}return r}var a=j(!0);return re(e,t,a),a}function re(e,t,r){e.setOption&&e.setOption(t,r)}function ne(e){if(R("[",!0)){do{ee(e,"option")}while(R(",",!0));R("]")}return e}for(;null!==(_=L());)switch(_){case"package":if(!U)throw q(_);K();break;case"import":if(!U)throw q(_);G();break;case"syntax":if(!U)throw q(_);W();break;case"option":ee(F,_),R(";");break;default:if(J(F,_)){U=!1;continue}throw q(_)}return k.filename=null,{package:C,imports:I,weakImports:x,syntax:T,root:t}}},6237:(e,t,r)=>{"use strict";e.exports=c;var n,o=r(3610),s=o.LongBits,i=o.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 o.Buffer?function(e){return(c.create=function(e){return o.Buffer.isBuffer(e)?new n(e):u(e)})(e)}:u};function d(){var e=new s(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 s(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}c.create=h(),c.prototype._slice=o.Array.prototype.subarray||o.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=o.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=o.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=o.Buffer;return n?n.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,r)},c.prototype.string=function(){var e=this.bytes();return i.read(e,0,e.length)},c.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw a(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},c.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},c._configure=function(e){n=e,c.create=h(),n._configure();var t=o.Long?"toLong":"toNumber";o.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=s;var n=r(6237);(s.prototype=Object.create(n.prototype)).constructor=s;var o=r(3610);function s(e){n.call(this,e)}s._configure=function(){o.Buffer&&(s.prototype._slice=o.Buffer.prototype.slice)},s.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))},s._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 o,s,i,a=r(1344),c=r(5643),l=r(1457),u=r(3262);function h(e){n.call(this,"",e),this.deferred=[],this.files=[]}function d(){}h.fromJSON=function(e,t){return t||(t=new h),e.options&&t.setOptions(e.options),t.addJSON(e.nested)},h.prototype.resolvePath=u.path.resolve,h.prototype.fetch=u.fetch,h.prototype.load=function e(t,r,n){"function"==typeof r&&(n=r,r=void 0);var o=this;if(!n)return u.asPromise(e,o,t,r);var a=n===d;function c(e,t){if(n){if(a)throw e;var r=n;n=null,r(e,t)}}function l(e){var t=e.lastIndexOf("google/protobuf/");if(t>-1){var r=e.substring(t);if(r in i)return r}return null}function h(e,t){try{if(u.isString(t)&&"{"===t.charAt(0)&&(t=JSON.parse(t)),u.isString(t)){s.filename=e;var n,i=s(t,o,r),h=0;if(i.imports)for(;h-1))if(o.files.push(e),e in i)a?h(e,i[e]):(++f,setTimeout((function(){--f,h(e,i[e])})));else if(a){var r;try{r=u.fs.readFileSync(e).toString("utf8")}catch(e){return void(t||c(e))}h(e,r)}else++f,o.fetch(e,(function(r,s){--f,n&&(r?t?f||c(null,o):c(r):h(e,s))}))}var f=0;u.isString(t)&&(t=[t]);for(var g,m=0;m-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{"use strict";e.exports={}},5047:(e,t,r)=>{"use strict";t.Service=r(7595)},7595:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(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)}(o.prototype=Object.create(n.EventEmitter.prototype)).constructor=o,o.prototype.rpcCall=function e(t,r,o,s,i){if(!s)throw TypeError("request must be specified");var a=this;if(!i)return n.asPromise(e,a,t,r,o,s);if(a.rpcImpl)try{return a.rpcImpl(t,r[a.requestDelimited?"encodeDelimited":"encode"](s).finish(),(function(e,r){if(e)return a.emit("error",e,t),i(e);if(null!==r){if(!(r instanceof o))try{r=o[a.responseDelimited?"decodeDelimited":"decode"](r)}catch(e){return a.emit("error",e,t),i(e)}return a.emit("data",r,t),i(null,r)}a.end(!0)}))}catch(e){return a.emit("error",e,t),void setTimeout((function(){i(e)}),0)}else setTimeout((function(){i(Error("already ended"))}),0)},o.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 o=r(8811),s=r(3262),i=r(5047);function a(e,t){n.call(this,e,t),this.methods={},this._methodsArray=null}function c(e){return e._methodsArray=null,e}a.fromJSON=function(e,t){var r=new a(e,t.options);if(t.methods)for(var n=Object.keys(t.methods),s=0;s{"use strict";e.exports=h;var t=/[\s{}=;:[\],'"()<>]/g,r=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,n=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,o=/^ *[*/]+ */,s=/^\s*\*?\/*/,i=/\n/g,a=/\s/,c=/\\(.?)/g,l={0:"\0",r:"\r",n:"\n",t:"\t"};function u(e){return e.replace(c,(function(e,t){switch(t){case"\\":case"":return t;default:return l[t]||""}}))}function h(e,c){e=e.toString();var l=0,h=e.length,d=1,p=0,f={},g=[],m=null;function y(e){return Error("illegal "+e+" (line "+d+")")}function b(t){return e.charAt(t)}function w(t,r,n){var a,l={type:e.charAt(t++),lineEmpty:!1,leading:n},u=t-(c?2:3);do{if(--u<0||"\n"===(a=e.charAt(u))){l.lineEmpty=!0;break}}while(" "===a||"\t"===a);for(var h=e.substring(t,r).split(i),g=0;g0)return g.shift();if(m)return function(){var t="'"===m?n:r;t.lastIndex=l-1;var o=t.exec(e);if(!o)throw y("string");return l=t.lastIndex,A(m),m=null,u(o[1])}();var o,s,i,p,f,S=0===l;do{if(l===h)return null;for(o=!1;a.test(i=b(l));)if("\n"===i&&(S=!0,++d),++l===h)return null;if("/"===b(l)){if(++l===h)throw y("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++,o=!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,o=!0}else{if("*"!==(i=b(l)))return"/";p=l+1,f=c||"*"===b(p);do{if("\n"===i&&++d,++l===h)throw y("comment");s=i,i=b(l)}while("*"!==s||"/"!==i);++l,f&&(w(p,l-2,S),S=!0),o=!0}}}while(o);var k=l;if(t.lastIndex=0,!t.test(b(k++)))for(;k{"use strict";e.exports=b;var n=r(8923);((b.prototype=Object.create(n.prototype)).constructor=b).className="Type";var o=r(5643),s=r(1457),i=r(1344),a=r(8252),c=r(9687),l=r(2551),u=r(6237),h=r(3449),d=r(3262),p=r(1080),f=r(7728),g=r(420),m=r(744),y=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{"use strict";var n=t,o=r(3262),s=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function i(e,t){var r=0,n={};for(t|=0;r{"use strict";var n,o,s=e.exports=r(3610),i=r(4529);s.codegen=r(8561),s.fetch=r(5212),s.path=r(9207),s.fs=s.inquire("fs"),s.toArray=function(e){if(e){for(var t=Object.keys(e),r=new Array(t.length),n=0;n0)t[o]=e(t[o]||{},r,n);else{var s=t[o];s&&(n=[].concat(s).concat(n)),t[o]=n}return t}(e,t=t.split("."),r)},Object.defineProperty(s,"decorateRoot",{get:function(){return i.decorated||(i.decorated=new(r(5330)))}})},2239:(e,t,r)=>{"use strict";e.exports=o;var n=r(3610);function o(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=o.zero=new o(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var i=o.zeroHash="\0\0\0\0\0\0\0\0";o.fromNumber=function(e){if(0===e)return s;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 o(r,n)},o.from=function(e){if("number"==typeof e)return o.fromNumber(e);if(n.isString(e)){if(!n.Long)return o.fromNumber(parseInt(e,10));e=n.Long.fromString(e)}return e.low||e.high?new o(e.low>>>0,e.high>>>0):s},o.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},o.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;o.fromHash=function(e){return e===i?s:new o((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)},o.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)},o.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},o.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},o.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 o(e,t,r){for(var n=Object.keys(t),o=0;o0)},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=o,n.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},n.newError=s,n.ProtocolError=s("ProtocolError"),n.oneOfGetter=function(e){for(var t={},r=0;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{"use strict";e.exports=function(e){var t=o.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{"use strict";var n=t,o=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 s=this.lookup(n);s&&(e=s.decode(e.value))}if(!(e instanceof this.ctor)&&e instanceof o){var i=e.$type.toObject(e,t);return""===r&&(r="type.googleapis.com/"),n=r+("."===e.$type.fullName[0]?e.$type.fullName.slice(1):e.$type.fullName),i["@type"]=n,i}return this.toObject(e,t)}}},3449:(e,t,r)=>{"use strict";e.exports=h;var n,o=r(3610),s=o.LongBits,i=o.base64,a=o.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 o.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 m(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 o.Array(e)},o.Array!==Array&&(h.alloc=o.pool(h.alloc,o.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,s.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=s.from(e);return this._push(g,t.length(),t)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(e){var t=s.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(m,4,e>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(e){var t=s.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(e){return this._push(o.float.writeFloatLE,4,e)},h.prototype.double=function(e){return this._push(o.float.writeDoubleLE,8,e)};var y=o.Array.prototype.set?function(e,t,r){t.set(e,r)}:function(e,t,r){for(var n=0;n>>0;if(!t)return this._push(p,1,0);if(o.isString(e)){var r=h.alloc(t=i.length(e));i.decode(e,r,0),e=r}return this.uint32(t)._push(y,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=s;var n=r(3449);(s.prototype=Object.create(n.prototype)).constructor=s;var o=r(3610);function s(){n.call(this)}function i(e,t,r){e.length<40?o.utf8.write(e,t,r):t.utf8Write?t.utf8Write(e,r):t.write(e,r)}s._configure=function(){s.alloc=o._Buffer_allocUnsafe,s.writeBytesBuffer=o.Buffer&&o.Buffer.prototype instanceof Uint8Array&&"set"===o.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>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=o.Buffer.byteLength(e);return this.uint32(t),t&&this._push(i,t,e),this},s._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),o=r.toUint8Array(t);if(n.length!==o.byteLength)return!1;for(let e=0;e{e.exports=r(8303)},8303:(e,t,r)=>{var n=r(3961);t.operation=function(e){var r=t.timeouts(e);return new n(r,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o{function t(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n=r&&(t=o,r=i)}return t}},495:()=>{}},__webpack_module_cache__={},leafPrototypes,getProto;function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(r.exports,r,r.exports,__webpack_require__),r.exports}__webpack_require__.amdO={},getProto=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,__webpack_require__.t=function(e,t){if(1&t&&(e=this(e)),8&t)return e;if("object"==typeof e&&e){if(4&t&&e.__esModule)return e;if(16&t&&"function"==typeof e.then)return e}var r=Object.create(null);__webpack_require__.r(r);var n={};leafPrototypes=leafPrototypes||[null,getProto({}),getProto([]),getProto(getProto)];for(var o=2&t&&e;"object"==typeof o&&!~leafPrototypes.indexOf(o);o=getProto(o))Object.getOwnPropertyNames(o).forEach((t=>n[t]=()=>e[t]));return n.default=()=>e,__webpack_require__.d(r,n),r},__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{"use strict";var e={};__webpack_require__.r(e),__webpack_require__.d(e,{base10:()=>ne});var t={};__webpack_require__.r(t),__webpack_require__.d(t,{base16:()=>oe,base16upper:()=>se});var r={};__webpack_require__.r(r),__webpack_require__.d(r,{base2:()=>ie});var n={};__webpack_require__.r(n),__webpack_require__.d(n,{base256emoji:()=>ue});var o={};__webpack_require__.r(o),__webpack_require__.d(o,{base32:()=>he,base32hex:()=>ge,base32hexpad:()=>ye,base32hexpadupper:()=>be,base32hexupper:()=>me,base32pad:()=>pe,base32padupper:()=>fe,base32upper:()=>de,base32z:()=>we});var s={};__webpack_require__.r(s),__webpack_require__.d(s,{base36:()=>ve,base36upper:()=>Ee});var i={};__webpack_require__.r(i),__webpack_require__.d(i,{base58btc:()=>Se,base58flickr:()=>Ae});var a={};__webpack_require__.r(a),__webpack_require__.d(a,{base64:()=>ke,base64pad:()=>Ce,base64url:()=>Ie,base64urlpad:()=>xe});var c={};__webpack_require__.r(c),__webpack_require__.d(c,{base8:()=>Te});var l={};__webpack_require__.r(l),__webpack_require__.d(l,{identity:()=>_e});var u={};__webpack_require__.r(u),__webpack_require__.d(u,{code:()=>Be,decode:()=>Re,encode:()=>Oe,name:()=>Le});var h={};__webpack_require__.r(h),__webpack_require__.d(h,{code:()=>Ue,decode:()=>Fe,encode:()=>Me,name:()=>De});var d={};__webpack_require__.r(d),__webpack_require__.d(d,{identity:()=>ct});var p={};__webpack_require__.r(p),__webpack_require__.d(p,{sha256:()=>dt,sha512:()=>pt});var f={};function g(e=0){return new Uint8Array(e)}function m(e=0){return new Uint8Array(e)}__webpack_require__.r(f),__webpack_require__.d(f,{aK:()=>Xi,e8:()=>Oi,DO:()=>Bi,dJ:()=>Yi,OG:()=>Zi,My:()=>Di,Ph:()=>Hi,lX:()=>ji,Id:()=>Gi,fg:()=>ta,qj:()=>Ki,aT:()=>qi,r4:()=>Ji,aY:()=>Li,x:()=>oa,lq:()=>Vi,z:()=>zi,zW:()=>Ui,Q5:()=>na});const y=Math.pow(2,7),b=Math.pow(2,14),w=Math.pow(2,21),v=Math.pow(2,28),E=Math.pow(2,35),S=Math.pow(2,42),A=Math.pow(2,49),k=128,C=127;function I(e){if(eNumber.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function x(e,t,r=0){switch(I(e)){case 8:t[r++]=255&e|k,e/=128;case 7:t[r++]=255&e|k,e/=128;case 6:t[r++]=255&e|k,e/=128;case 5:t[r++]=255&e|k,e/=128;case 4:t[r++]=255&e|k,e>>>=7;case 3:t[r++]=255&e|k,e>>>=7;case 2:t[r++]=255&e|k,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function T(e,t){let r=e[t],n=0;if(n+=r&C,r>>=7;case 3:t.set(r++,255&e|k),e>>>=7;case 2:t.set(r++,255&e|k),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function N(e,t=0){return e instanceof Uint8Array?T(e,t):function(e,t){let r=e.get(t),n=0;if(n+=r&C,r>>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 $;if(eM)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>q&&(n=0n,++r>q&&(r=0n))),new F(Number(n),Number(r))}static fromNumber(e){if(0===e)return $;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 F(r,n)}static from(e){return"number"==typeof e?F.fromNumber(e):"bigint"==typeof e?F.fromBigInt(e):"string"==typeof e?F.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new F(e.low>>>0,e.high>>>0):$}}const $=new F(0,0);$.toBigInt=function(){return 0n},$.zzEncode=$.zzDecode=function(){return this},$.length=function(){return 1};const q=4294967296n;function H(e,t,r){const n=r;let o,s;for(let n=0;n>6|192,t[r++]=63&o|128):55296==(64512&o)&&56320==(64512&(s=e.charCodeAt(n+1)))?(o=65536+((1023&o)<<10)+(1023&s),++n,t[r++]=o>>18|240,t[r++]=o>>12&63|128,t[r++]=o>>6&63|128,t[r++]=63&o|128):(t[r++]=o>>12|224,t[r++]=o>>6&63|128,t[r++]=63&o|128);return r-n}function j(e,t){return RangeError(`index out of range: ${e.pos} + ${t??1} > ${e.len}`)}function V(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class z{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,j(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 j(this,4);return V(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw j(this,4);return 0|V(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,L[0]=t[r],L[1]=t[r+1],L[2]=t[r+2],L[3]=t[r+3],P[0]);var t,r;return this.pos+=4,e}double(){if(this.pos+8>this.len)throw j(this,4);const e=(t=this.buf,r=this.pos,R[0]=t[r],R[1]=t[r+1],R[2]=t[r+2],R[3]=t[r+3],R[4]=t[r+4],R[5]=t[r+5],R[6]=t[r+6],R[7]=t[r+7],O[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 j(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 o=[];let s,i=0;for(;t191&&s<224?o[i++]=(31&s)<<6|63&e[t++]:s>239&&s<365?(s=((7&s)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[i++]=55296+(s>>10),o[i++]=56320+(1023&s)):o[i++]=(15&s)<<12|(63&e[t++])<<6|63&e[t++],i>8191&&((n??(n=[])).push(String.fromCharCode.apply(String,o)),i=0);return null!=n?(i>0&&n.push(String.fromCharCode.apply(String,o.slice(0,i))),n.join("")):String.fromCharCode.apply(String,o.slice(0,i))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw j(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw j(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 F(0,0);let t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw j(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 j(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 j(this,8);const e=V(this.buf,this.pos+=4),t=V(this.buf,this.pos+=4);return new F(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=T(this.buf,this.pos);return this.pos+=I(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 K(e,t,r){const n=function(e){return new z(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}function G(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 W=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n>>0,i=new Uint8Array(s);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var h=0,d=s-1;(0!==u||h>>0,i[d]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");o=h,t++}if(" "!==e[t]){for(var p=s-o;p!==s&&0===i[p];)p++;for(var f=new Uint8Array(n+(s-p)),g=n;p!==s;)f[g++]=i[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,o=0,s=t.length;o!==s&&0===t[o];)o++,r++;for(var i=(s-o)*u+1>>>0,l=new Uint8Array(i);o!==s;){for(var h=t[o],d=0,p=i-1;(0!==h||d>>0,l[p]=h%a>>>0,h=h/a>>>0;if(0!==h)throw new Error("Non-zero carry");n=d,o++}for(var f=i-n;f!==i&&0===l[f];)f++;for(var g=c.repeat(r);fG(o(e))})}function re({name:e,prefix:t,bitsPerChar:r,alphabet:n}){return ee({prefix:t,name:e,encode:e=>function(e,t,r){const n="="===t[t.length-1],o=(1<r;)i-=r,s+=t[o&a>>i];if(0!==i&&(s+=t[o&a<function(e,t,r,n){const o={};for(let e=0;e=8&&(a-=8,i[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}(t,n,r,e)})}const ne=te({prefix:"9",name:"base10",alphabet:"0123456789"}),oe=re({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),se=re({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),ie=re({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),ae=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),ce=ae.reduce(((e,t,r)=>(e[r]=t,e)),[]),le=ae.reduce(((e,t,r)=>{const n=t.codePointAt(0);if(null==n)throw new Error(`Invalid character: ${t}`);return e[n]=r,e}),[]),ue=ee({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+ce[t]),"")},decode:function(e){const t=[];for(const r of e){const e=r.codePointAt(0);if(null==e)throw new Error(`Invalid character: ${r}`);const n=le[e];if(null==n)throw new Error(`Non-base256emoji character: ${r}`);t.push(n)}return new Uint8Array(t)}}),he=re({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),de=re({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),pe=re({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),fe=re({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ge=re({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),me=re({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ye=re({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),be=re({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),we=re({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),ve=te({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ee=te({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Se=te({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ae=te({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ke=re({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ce=re({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ie=re({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xe=re({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Te=re({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),_e=ee({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)}),Ne=new TextEncoder,Pe=new TextDecoder,Le="json",Be=512;function Oe(e){return Ne.encode(JSON.stringify(e))}function Re(e){return JSON.parse(Pe.decode(e))}const De="raw",Ue=85;function Me(e){return G(e)}function Fe(e){return G(e)}var $e=128,qe=-128,He=Math.pow(2,31),je=128,Ve=127,ze=Math.pow(2,7),Ke=Math.pow(2,14),Ge=Math.pow(2,21),We=Math.pow(2,28),Je=Math.pow(2,35),Xe=Math.pow(2,42),Ye=Math.pow(2,49),Ze=Math.pow(2,56),Qe=Math.pow(2,63);const et={encode:function e(t,r,n){r=r||[];for(var o=n=n||0;t>=He;)r[n++]=255&t|$e,t/=128;for(;t&qe;)r[n++]=255&t|$e,t>>>=7;return r[n]=0|t,e.bytes=n-o+1,r},decode:function e(t,r){var n,o=0,s=0,i=r=r||0,a=t.length;do{if(i>=a)throw e.bytes=0,new RangeError("Could not decode varint");n=t[i++],o+=s<28?(n&Ve)<=je);return e.bytes=i-r,o},encodingLength:function(e){return eot(this.code,e)))}throw Error("Unknown type, must be binary type")}}function ht(e){return async t=>new Uint8Array(await crypto.subtle.digest(e,t))}const dt=lt({name:"sha2-256",code:18,encode:ht("SHA-256")}),pt=lt({name:"sha2-512",code:19,encode:ht("SHA-512")});function ft(e,t){const{bytes:r,version:n}=e;return 0===n?function(e,t,r){const{prefix:n}=r;if(n!==Se.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);const o=t.get(n);if(null==o){const o=r.encode(e).slice(1);return t.set(n,o),o}return o}(r,mt(e),t??Se.encoder):function(e,t,r){const{prefix:n}=r,o=t.get(n);if(null==o){const o=r.encode(e);return t.set(n,o),o}return o}(r,mt(e),t??he.encoder)}const gt=new WeakMap;function mt(e){const t=gt.get(e);if(null==t){const t=new Map;return gt.set(e,t),t}return t}class yt{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!==bt)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==wt)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return yt.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=ot(e,t);return yt.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 yt.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{const[r,n]=tt(e.subarray(t));return t+=n,r};let n=r(),o=bt;if(18===n?(n=0,t=0):o=r(),0!==n&&1!==n)throw new RangeError(`Invalid CID version ${n}`);const s=t,i=r(),a=r(),c=t+a;return{version:n,codec:o,multihashCode:i,digestSize:a,multihashSize:c-s,size:c}}static parse(e,t){const[r,n]=function(e,t){switch(e[0]){case"Q":{const r=t??Se;return[Se.prefix,r.decode(`${Se.prefix}${e}`)]}case Se.prefix:{const r=t??Se;return[Se.prefix,r.decode(e)]}case he.prefix:{const r=t??he;return[he.prefix,r.decode(e)]}case ve.prefix:{const r=t??ve;return[ve.prefix,r.decode(e)]}default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),o=yt.decode(n);if(0===o.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return mt(o).set(r,e),o}}const bt=112,wt=18;function vt(e,t,r){const n=nt(e),o=n+nt(t),s=new Uint8Array(o+r.byteLength);return rt(e,s,0),rt(t,s,n),s.set(r,o),s}const Et=Symbol.for("@ipld/js-cid/CID"),St={...l,...r,...c,...e,...t,...o,...s,...i,...a,...n};function At(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}const kt=At("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ct=At("ascii","a",(e=>{let t="a";for(let r=0;r{const t=m((e=e.substring(1)).length);for(let r=0;r4096)return m(n);r+n>e&&(t=m(e),r=0);const o=t.subarray(r,r+=n);return 7&r&&(r=1+(7|r)),o}}();class Lt{len;head;tail;states;constructor(){this.len=0,this.head=new Tt(_t,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new Tt(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Rt((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Dt,10,F.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){const t=F.fromBigInt(e);return this._push(Dt,t.length(),t)}uint64Number(e){return this._push(x,I(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=F.fromBigInt(e).zzEncode();return this._push(Dt,t.length(),t)}sint64Number(e){const t=F.fromNumber(e).zzEncode();return this._push(Dt,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(Bt,1,e?1:0)}fixed32(e){return this._push(Ut,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){const t=F.fromBigInt(e);return this._push(Ut,4,t.lo)._push(Ut,4,t.hi)}fixed64Number(e){const t=F.fromNumber(e);return this._push(Ut,4,t.lo)._push(Ut,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(B,4,e)}double(e){return this._push(D,8,e)}bytes(e){const t=e.length>>>0;return 0===t?this._push(Bt,1,0):this.uint32(t)._push(Mt,t,e)}string(e){const t=function(e){let t=0,r=0;for(let n=0;n127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class Rt extends Tt{next;constructor(e,t){super(Ot,e,t),this.next=void 0}}function Dt(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 Ut(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 Mt(e,t,r){t.set(e,r)}function Ft(e,t,r){t.set(e,r)}function $t(e,t,r){e.length<40?H(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(xt(e),r)}function qt(e,t){const r=new Lt;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}var Ht,jt,Vt,zt,Kt,Gt,Wt,Jt,Xt,Yt,Zt,Qt,er,tr,rr,nr,or,sr,ir,ar,cr,lr,ur,hr,dr,pr,fr,gr,mr,yr;function br(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function wr(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return br("enum",Ht.VARINT,(function(e,r){const n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function vr(e,t){return br("message",Ht.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(Lt.prototype.bytes=function(e){const t=e.length>>>0;return this.uint32(t),t>0&&this._push(Ft,t,e),this},Lt.prototype.string=function(e){const t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push($t,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"}(Ht||(Ht={})),Error;class Er extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"}class Sr extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}function Ar(e){return Boolean(e)}function kr(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 Cr(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:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(jt||(jt={})),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),jt.codec().encode(e.rateLimitProof,t)),null!=e.ephemeral&&(t.uint32(248),t.bool(e.ephemeral)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={payload:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.payload=e.bytes();break;case 2:n.contentTopic=e.string();break;case 3:n.version=e.uint32();break;case 10:n.timestamp=e.sint64();break;case 11:n.meta=e.bytes();break;case 21:n.rateLimitProof=jt.codec().decode(e,e.uint32(),{limits:r.limits?.rateLimitProof});break;case 31:n.ephemeral=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Vt||(Vt={})),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:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(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 o={subscribe:!1,topic:"",contentFilters:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:o.subscribe=t.bool();break;case 2:o.topic=t.string();break;case 3:if(null!=n.limits?.contentFilters&&o.contentFilters.length===n.limits.contentFilters)throw new Er('Decode error - map field "contentFilters" had too many elements');o.contentFilters.push(e.ContentFilter.codec().decode(t,t.uint32(),{limits:n.limits?.contentFilters$}));break;default:t.skipType(7&r)}}return o}))),r),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(zt||(zt={})),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),Jt.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={messages:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Er('Decode error - map field "messages" had too many elements');n.messages.push(Jt.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Kt||(Kt={})),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),zt.codec().encode(e.request,t)),null!=e.push&&(t.uint32(26),Kt.codec().encode(e.push,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=zt.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.push=Kt.codec().decode(e,e.uint32(),{limits:r.limits?.push});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Gt||(Gt={})),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:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Wt||(Wt={})),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),Wt.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:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>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=Wt.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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Jt||(Jt={})),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:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3==2?n.contentTopic=e.string():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Xt||(Xt={})),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=()=>wr(r)}(t=e.FilterSubscribeType||(e.FilterSubscribeType={})),e.codec=()=>(null==n&&(n=vr(((t,n,o={})=>{if(!1!==o.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!==o.lengthDelimited&&n.ldelim()}),((r,n,o={})=>{const s={requestId:"",filterSubscribeType:t.SUBSCRIBER_PING,contentTopics:[]},i=null==n?r.len:r.pos+n;for(;r.pos>>3){case 1:s.requestId=r.string();break;case 2:s.filterSubscribeType=e.FilterSubscribeType.codec().decode(r);break;case 10:s.pubsubTopic=r.string();break;case 11:if(null!=o.limits?.contentTopics&&s.contentTopics.length===o.limits.contentTopics)throw new Er('Decode error - map field "contentTopics" had too many elements');s.contentTopics.push(r.string());break;default:r.skipType(7&t)}}return s}))),n),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Yt||(Yt={})),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},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Zt||(Zt={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.wakuMessage&&(t.uint32(10),tr.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={},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.wakuMessage=tr.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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Qt||(Qt={})),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:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(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.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),er.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:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>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=er.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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(tr||(tr={})),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),ir.codec().encode(e.message,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={pubsubTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.pubsubTopic=e.string();break;case 2:n.message=ir.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(rr||(rr={})),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},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(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.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.request&&(t.uint32(18),rr.codec().encode(e.request,t)),null!=e.response&&(t.uint32(26),nr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.request=rr.codec().decode(e,e.uint32(),{limits:r.limits?.request});break;case 3:n.response=nr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(or||(or={})),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:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(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.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),sr.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:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>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=sr.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=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ir||(ir={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.messageHash&&(t.uint32(10),t.bytes(e.messageHash)),null!=e.message&&(t.uint32(18),hr.codec().encode(e.message,t)),null!=e.pubsubTopic&&(t.uint32(26),t.string(e.pubsubTopic)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.messageHash=e.bytes();break;case 2:n.message=hr.codec().decode(e,e.uint32(),{limits:r.limits?.message});break;case 3:n.pubsubTopic=e.string();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ar||(ar={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.includeData&&!1!==e.includeData&&(t.uint32(16),t.bool(e.includeData)),null!=e.pubsubTopic&&(t.uint32(82),t.string(e.pubsubTopic)),null!=e.contentTopics)for(const r of e.contentTopics)t.uint32(90),t.string(r);if(null!=e.timeStart&&(t.uint32(96),t.sint64(e.timeStart)),null!=e.timeEnd&&(t.uint32(104),t.sint64(e.timeEnd)),null!=e.messageHashes)for(const r of e.messageHashes)t.uint32(162),t.bytes(r);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),null!=e.paginationForward&&!1!==e.paginationForward&&(t.uint32(416),t.bool(e.paginationForward)),null!=e.paginationLimit&&(t.uint32(424),t.uint64(e.paginationLimit)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",includeData:!1,contentTopics:[],messageHashes:[],paginationForward:!1},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 2:n.includeData=e.bool();break;case 10:n.pubsubTopic=e.string();break;case 11:if(null!=r.limits?.contentTopics&&n.contentTopics.length===r.limits.contentTopics)throw new Er('Decode error - map field "contentTopics" had too many elements');n.contentTopics.push(e.string());break;case 12:n.timeStart=e.sint64();break;case 13:n.timeEnd=e.sint64();break;case 20:if(null!=r.limits?.messageHashes&&n.messageHashes.length===r.limits.messageHashes)throw new Er('Decode error - map field "messageHashes" had too many elements');n.messageHashes.push(e.bytes());break;case 51:n.paginationCursor=e.bytes();break;case 52:n.paginationForward=e.bool();break;case 53:n.paginationLimit=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(cr||(cr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{if(!1!==r.lengthDelimited&&t.fork(),null!=e.requestId&&""!==e.requestId&&(t.uint32(10),t.string(e.requestId)),null!=e.statusCode&&(t.uint32(80),t.uint32(e.statusCode)),null!=e.statusDesc&&(t.uint32(90),t.string(e.statusDesc)),null!=e.messages)for(const r of e.messages)t.uint32(162),ar.codec().encode(r,t);null!=e.paginationCursor&&(t.uint32(410),t.bytes(e.paginationCursor)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={requestId:"",messages:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.requestId=e.string();break;case 10:n.statusCode=e.uint32();break;case 11:n.statusDesc=e.string();break;case 20:if(null!=r.limits?.messages&&n.messages.length===r.limits.messages)throw new Er('Decode error - map field "messages" had too many elements');n.messages.push(ar.codec().decode(e,e.uint32(),{limits:r.limits?.messages$}));break;case 51:n.paginationCursor=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(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.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:g(0),merkleRoot:g(0),epoch:g(0),shareX:g(0),shareY:g(0),nullifier:g(0),rlnIdentifier:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>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=>qt(t,e.codec()),e.decode=(t,r)=>K(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.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),ur.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:g(0),contentTopic:""},o=null==t?e.len:e.pos+t;for(;e.pos>>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=ur.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=>qt(t,e.codec()),e.decode=(t,r)=>K(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.enr&&(t.uint32(10),t.bytes(e.enr)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.enr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(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.numPeers&&(t.uint32(8),t.uint64(e.numPeers)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.numPeers=e.uint64():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(pr||(pr={})),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),dr.codec().encode(r,t);!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={peerInfos:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1){if(null!=r.limits?.peerInfos&&n.peerInfos.length===r.limits.peerInfos)throw new Er('Decode error - map field "peerInfos" had too many elements');n.peerInfos.push(dr.codec().decode(e,e.uint32(),{limits:r.limits?.peerInfos$}))}else e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(fr||(fr={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.query&&(t.uint32(10),pr.codec().encode(e.query,t)),null!=e.response&&(t.uint32(18),fr.codec().encode(e.response,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.query=pr.codec().decode(e,e.uint32(),{limits:r.limits?.query});break;case 2:n.response=fr.codec().decode(e,e.uint32(),{limits:r.limits?.response});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(gr||(gr={})),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:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Er('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(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:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.clusterId=e.uint32();break;case 2:if(null!=r.limits?.shards&&n.shards.length===r.limits.shards)throw new Er('Decode error - map field "shards" had too many elements');n.shards.push(e.uint32());break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(yr||(yr={}));function Ir(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function xr(e,...t){if(!((r=e)instanceof Uint8Array||ArrayBuffer.isView(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+", got length="+e.length)}function Tr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");Ir(e.outputLen),Ir(e.blockLen)}function _r(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 Nr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function Pr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Lr(e,t){return e<<32-t|e>>>t}function Br(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e)),xr(e),e}class Or{clone(){return this._cloneInto()}}function Rr(e){const t=t=>e().update(Br(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Dr(e=32){if(Nr&&"function"==typeof Nr.getRandomValues)return Nr.getRandomValues(new Uint8Array(e));if(Nr&&"function"==typeof Nr.randomBytes)return Nr.randomBytes(e);throw new Error("crypto.getRandomValues must be defined")}function Ur(e,t,r){return e&t^e&r^t&r}class Mr extends Or{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=Pr(this.buffer)}update(e){_r(this);const{view:t,buffer:r,blockLen:n}=this,o=(e=Br(e)).length;for(let s=0;sn-s&&(this.process(r,0),s=0);for(let e=s;e>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}(r,n-8,BigInt(8*this.length),o),this.process(r,0);const i=Pr(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>>3,o=Lr(r,17)^Lr(r,19)^r>>>10;qr[e]=o+qr[e-7]+n+qr[e-16]|0}let{A:r,B:n,C:o,D:s,E:i,F:a,G:c,H:l}=this;for(let e=0;e<64;e++){const t=l+(Lr(i,6)^Lr(i,11)^Lr(i,25))+((u=i)&a^~u&c)+Fr[e]+qr[e]|0,h=(Lr(r,2)^Lr(r,13)^Lr(r,22))+Ur(r,n,o)|0;l=c,c=a,a=i,i=s+t|0,s=o,o=n,n=r,r=t+h|0}var u;r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,s=s+this.D|0,i=i+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,s,i,a,c,l)}roundClean(){qr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const jr=Rr((()=>new Hr));var Vr,zr,Kr,Gr,Wr;!function(e){e.Relay="relay",e.Store="store",e.LightPush="lightpush",e.Filter="filter"}(Vr||(Vr={})),function(e){e.GENERIC_FAIL="Generic error",e.ENCODE_FAILED="Failed to encode",e.DECODE_FAILED="Failed to decode",e.EMPTY_PAYLOAD="Payload is empty",e.SIZE_TOO_BIG="Size is too big",e.TOPIC_NOT_CONFIGURED="Topic not configured",e.TOPIC_DECODER_MISMATCH="Topic decoder mismatch",e.INVALID_DECODER_TOPICS="Invalid decoder topics",e.NO_PEER_AVAILABLE="No peer available",e.NO_STREAM_AVAILABLE="No stream available",e.NO_RESPONSE="No response received",e.REMOTE_PEER_REJECTED="Remote peer rejected",e.REQUEST_TIMEOUT="Request timeout",e.RLN_IDENTITY_MISSING="Identity credentials are not set",e.RLN_MEMBERSHIP_INDEX="Membership index is not set",e.RLN_LIMIT_MISSING="User message limit is not set",e.RLN_PROOF_GENERATION="Proof generation failed"}(zr||(zr={})),function(e){e.BOOTSTRAP="bootstrap",e.PEER_EXCHANGE="peer-exchange",e.LOCAL="local-peer-cache"}(Kr||(Kr={})),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"}(Gr||(Gr={})),function(e){e.CONNECTION_STATUS="waku:connection"}(Wr||(Wr={}));const Jr="@waku/bootstrap",Xr={clusterId:1,shards:[0,1,2,3,4,5,6,7,8]};var Yr;function Zr(e,t="utf8"){const r=It[t];if(null==r)throw new Error(`Unsupported encoding "${t}"`);return r.encoder.encode(e).substring(1)}function Qr(e){return"string"==typeof e?xt(e.replace(/^0x/i,"").toLowerCase(),"base16"):e}!function(e){e.Unhealthy="Unhealthy",e.MinimallyHealthy="MinimallyHealthy",e.SufficientlyHealthy="SufficientlyHealthy"}(Yr||(Yr={}));const en=e=>Zr(e,"base16"),tn=e=>Zr(e,"utf8"),rn=e=>xt(e,"utf8");function nn(e,t){const r=t??e.reduce(((e,t)=>e+t.length),0),n=new Uint8Array(r);let o=0;for(const t of e)n.set(t,o),o+=t.length;return n}const on=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??1}/${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")},sn=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}},an=e=>{const t=new Set,r=new Set;for(const n of e){const{clusterId:e,shard:o}=sn(n);t.add(`${e}:${o}`),r.add(e)}if(0===t.size)throw new Error("No valid pubsub topics provided");if(r.size>1)throw new Error("Pubsub topics from multiple cluster IDs are not supported");return{clusterId:r.values().next().value,shards:Array.from(t).map((e=>parseInt(e.split(":")[1])))}};function cn(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 ln(e,t=1,r=8){if(!e)throw Error("Content topic must be specified");return`/waku/2/rs/${t}/${function(e,t=8){const{application:r,version:n}=function(e){const t=e.split("/");if(t.length<5||t.length>6)throw Error("Content topic format is invalid");let r=0;if(6==t.length){if(r=parseInt(t[1]),isNaN(r))throw new Error("Invalid generation field in content topic");if(r>0)throw new Error("Generation greater than 0 is not supported")}const n=t.splice(-4);if(0==n[0].length)throw new Error("Application field cannot be empty");if(0==n[1].length)throw new Error("Version field cannot be empty");if(0==n[2].length)throw new Error("Topic name field cannot be empty");if(0==n[3].length)throw new Error("Encoding field cannot be empty");return{generation:r,application:n[0],version:n[1],topicName:n[2],encoding:n[3]}}(e),o=jr(nn([rn(r),rn(n)])),s=new DataView(o.buffer.slice(-8));return Number(s.getBigUint64(0,!1)%BigInt(t))}(e,r)}`}function un(e,t){return"string"==typeof t?t:void 0!==t?.shard?(e=>{if(void 0===e.shard)throw new Error("Invalid shard");return`/waku/2/rs/${e.clusterId??1}/${e.shard}`})(t):ln(e,t?.clusterId??1)}const hn=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,o=7-e%8;t.getUint8(r)&1<=e.length)throw new Error("Unexpected end of data");n.push(t.getUint16(s))}}return{clusterId:r,shards:n}},dn=e=>{const{clusterId:t,shards:r}=e,n=r.length>=64?130:3+2*r.length,o=new ArrayBuffer(n),s=new DataView(o);if(s.setUint16(0,t),r.length>=64)for(const e of r){const t=Math.floor(e/8)+2,r=7-e%8;s.setUint8(t,s.getUint8(t)|1<{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 kn(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));const r=m(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}function Cn(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let r=0;r0&&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(!Tn(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(!Tn(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=xn(this.bufs,e);return t.buf[t.index]}set(e,t){const r=xn(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r0;){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 kn(r,n)}subarray(e,t){const{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:kn(r,n)}sublist(e,t){const{bufs:r,length:n}=this._subList(e,t),o=new _n;return o.length=n,o.bufs=[...r],o}_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 o=0;o=a)continue;const c=e>=i&&ei&&t<=a;if(c&&l){if(e===i&&t===a){r.push(s);break}const n=e-i;r.push(s.subarray(n,n+(t-e)));break}if(c){if(0===e){r.push(s);continue}r.push(s.subarray(e-i))}else{if(l){if(t===a){r.push(s);break}r.push(s.subarray(0,t-i));break}r.push(s)}}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!(Tn(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 o=new Int32Array(256);for(let e=0;e<256;e++)o[e]=-1;for(let e=0;e=0;t--){const n=this.get(e+t);if(r[t]!==n){c=Math.max(1,t-s[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=m(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=g(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=g(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=g(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=m(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=g(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=g(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=g(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=g(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=g(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 _n))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(let t=0;te+t.byteLength),0)),r.length=t,r}}function Nn(e){return null!=e[Symbol.asyncIterator]}const Pn=e=>{const t=I(e),r=m(t);return _(e,r),Pn.bytes=t,r};function Ln(e,t){const r=(t=t??{}).lengthEncoder??Pn;function*n(e){const t=r(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return Nn(e)?async function*(){for await(const t of e)yield*n(t)}():function*(){for(const t of e)yield*n(t)}()}Pn.bytes=0,Ln.single=(e,t)=>{const r=(t=t??{}).lengthEncoder??Pn;return new _n(r(e.byteLength),e)};class Bn extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class On extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class Rn extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}class Dn extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}var Un;!function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Un||(Un={}));const Mn=e=>{const t=N(e);return Mn.bytes=I(t),t};function Fn(e,t){const r=new _n;let n=Un.LENGTH,o=-1;const s=t?.lengthDecoder??Mn,i=t?.maxLengthLength??8,a=t?.maxDataLength??4194304;function*c(){for(;r.byteLength>0;){if(n===Un.LENGTH)try{if(o=s(r),o<0)throw new Bn("Invalid message length");if(o>a)throw new On("Message length too long");const e=s.bytes;r.consume(e),null!=t?.onLength&&t.onLength(o),n=Un.DATA}catch(e){if(e instanceof RangeError){if(r.byteLength>i)throw new Rn("Message length length too long");break}throw e}if(n===Un.DATA){if(r.byteLength0)throw new Dn("Unexpected end of input")}():function*(){for(const t of e)r.append(t),yield*c();if(r.byteLength>0)throw new Dn("Unexpected end of input")}()}function $n(){const e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}Mn.bytes=0,Fn.fromReader=(e,t)=>{let r=1;return Fn(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 qn{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 Hn{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new qn(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 qn(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 jn extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}}function Vn(e={}){return function(e,t){let r,n,o,s=(t=t??{}).onEnd,i=new Hn,a=$n();const c=e=>null!=n?n(e):(i.push(e),r),l=e=>{if(o)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=>o?r:(o=!0,null!=e?(e=>(i=new Hn,null!=n?n({error:e}):(i.push({error:e}),r)))(e):c({done:!0}));if(r={[Symbol.asyncIterator](){return this},next:async()=>{try{return i.isEmpty()?o?{done:!0}:await new Promise(((t,o)=>{n=s=>{n=null,i.push(s);try{t(e(i))}catch(e){o(e)}return r}})):e(i)}finally{i.isEmpty()&&queueMicrotask((()=>{a.resolve(),a=$n()}))}},return:()=>(i=new Hn,u(),{done:!0}),throw:e=>(u(e),{done:!0}),push:l,end:u,get readableLength(){return i.size},onEmpty:async e=>{const t=e?.signal;if(t?.throwIfAborted(),i.isEmpty())return;let r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new jn)},t.addEventListener("abort",n)})));try{await Promise.race([a.promise,r])}finally{null!=n&&null!=t&&t?.removeEventListener("abort",n)}}},null==s)return r;const h=r;return r={[Symbol.asyncIterator](){return this},next:()=>h.next(),throw:e=>(h.throw(e),null!=s&&(s(e),s=void 0),{done:!0}),return:()=>(h.return(),null!=s&&(s(),s=void 0),{done:!0}),push:l,end:e=>(h.end(e),null!=s&&(s(e),s=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 zn=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=Vn({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 Kn(e,...t){if(null==e)throw new Error("Empty pipeline");if(Xn(e)){const t=e;e=()=>t.source}else if(Jn(e)||Wn(e)){const t=e;e=()=>t}const r=[e,...t];if(r.length>1&&Xn(r[r.length-1])&&(r[r.length-1]=r[r.length-1].sink),r.length>2)for(let e=1;e{let t;for(;e.length>0;)t=e.shift()(t);return t},Wn=e=>null!=e?.[Symbol.asyncIterator],Jn=e=>null!=e?.[Symbol.iterator],Xn=e=>null!=e&&null!=e.sink&&null!=e.source,Yn=e=>t=>{const r=e.sink(t);if(null!=r?.then){const t=Vn({objectMode:!0});let n;r.then((()=>{t.end()}),(e=>{t.end(e)}));const o=e.source;if(Wn(o))n=async function*(){yield*o,t.end()};else{if(!Jn(o))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");n=function*(){yield*o,t.end()}}return zn(t,n())}return e.source};function Zn(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const Qn="consumed";class eo{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new gn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=Zn(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,o;for(let s=0;s{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=Zn(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[Qn]=!0}isStreamLocked(e){return!!e.metadata[Qn]}}class to{multicodec;components;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r){this.multicodec=e,this.components=t,this.pubsubTopics=r,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new eo(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}}const ro={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};let no;const oo=new Uint8Array(16);function so(){if(!no&&(no="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!no))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return no(oo)}const io=[];for(let e=0;e<256;++e)io.push((e+256).toString(16).slice(1));const ao=function(e,t,r){if(ro.randomUUID&&!t&&!e)return ro.randomUUID();const n=(e=e||{}).random||(e.rng||so)();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 io[e[t+0]]+io[e[t+1]]+io[e[t+2]]+io[e[t+3]]+"-"+io[e[t+4]]+io[e[t+5]]+"-"+io[e[t+6]]+io[e[t+7]]+"-"+io[e[t+8]]+io[e[t+9]]+"-"+io[e[t+10]]+io[e[t+11]]+io[e[t+12]]+io[e[t+13]]+io[e[t+14]]+io[e[t+15]]}(n)};class co{proto;constructor(e){this.proto=e}static decode(e){const t=Qt.decode(e);return new co(t)}encode(){return Qt.encode(this.proto)}get wakuMessage(){return this.proto.wakuMessage}get pubsubTopic(){return this.proto.pubsubTopic}}class lo{proto;constructor(e){this.proto=e}static createSubscribeRequest(e,t){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.SUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeRequest(e,t){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.UNSUBSCRIBE,pubsubTopic:e,contentTopics:t})}static createUnsubscribeAllRequest(e){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.UNSUBSCRIBE_ALL,pubsubTopic:e,contentTopics:[]})}static createSubscriberPingRequest(){return new lo({requestId:ao(),filterSubscribeType:Yt.FilterSubscribeType.SUBSCRIBER_PING,pubsubTopic:"",contentTopics:[]})}static decode(e){const t=Yt.decode(e);return new lo(t)}encode(){return Yt.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 uo{proto;constructor(e){this.proto=e}static decode(e){const t=Zt.decode(e);return new uo(t)}encode(){return Zt.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get requestId(){return this.proto.requestId}}const ho=new gn("filter:v2"),po="/vac/waku/filter-subscribe/2.0.0-beta1",fo="/vac/waku/filter-push/2.0.0-beta1";class go extends to{handleIncomingMessage;pubsubTopics;constructor(e,t,r){super(po,r.components,t),this.handleIncomingMessage=e,this.pubsubTopics=t,r.handle(fo,this.onRequest.bind(this),{maxInboundStreams:100}).catch((e=>{ho.error("Failed to register ",fo,e)}))}async subscribe(e,t,r){const n=await this.getStream(t),o=lo.createSubscribeRequest(e,r);let s;try{s=await Kn([o.encode()],Ln,n,Fn,(async e=>await An(e)))}catch(e){return ho.error("Failed to send subscribe request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:t.id}}}const{statusCode:i,requestId:a,statusDesc:c}=uo.decode(s[0].slice());return i<200||i>=300?(ho.error(`Filter subscribe request ${a} failed with status code ${i}: ${c}`),{failure:{error:zr.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 ho.error(`Failed to get a stream for remote peer${t.id.toString()}`,e),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:t.id}}}const o=lo.createUnsubscribeRequest(e,r);try{await Kn([o.encode()],Ln,n.sink)}catch(e){return ho.error("Failed to send unsubscribe request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:t.id}}}return{success:t.id,failure:null}}async unsubscribeAll(e,t){const r=await this.getStream(t),n=lo.createUnsubscribeAllRequest(e),o=await Kn([n.encode()],Ln,r,Fn,(async e=>await An(e)));if(!o||!o.length)return{failure:{error:zr.NO_RESPONSE,peerId:t.id},success:null};const{statusCode:s,requestId:i,statusDesc:a}=uo.decode(o[0].slice());return s<200||s>=300?(ho.error(`Filter unsubscribe all request ${i} failed with status code ${s}: ${a}`),{failure:{error:zr.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 ho.error(`Failed to get a stream for remote peer${e.id.toString()}`,t),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:e.id}}}const r=lo.createSubscriberPingRequest();let n;try{n=await Kn([r.encode()],Ln,t,Fn,(async e=>await An(e)))}catch(t){return ho.error("Failed to send ping request",t),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:e.id}}}if(!n||!n.length)return{success:null,failure:{error:zr.NO_RESPONSE,peerId:e.id}};const{statusCode:o,requestId:s,statusDesc:i}=uo.decode(n[0].slice());return o<200||o>=300?(ho.error(`Filter ping request ${s} failed with status code ${o}: ${i}`),{success:null,failure:{error:zr.REMOTE_PEER_REJECTED,peerId:e.id}}):{success:e.id,failure:null}}onRequest(e){const{connection:t,stream:r}=e,{remotePeer:n}=t;ho.info(`Received message from ${n.toString()}`);try{Kn(r,Fn,(async e=>{for await(const r of e){const e=co.decode(r.slice()),{pubsubTopic:n,wakuMessage:o}=e;if(!o)return void ho.error("Received empty message");if(!n)return void ho.error("Pubsub topic missing from push message");await this.handleIncomingMessage(n,o,t.remotePeer.toString())}})).then((()=>{ho.info("Receiving pipe closed.")}),(async e=>{ho.error(`Error with receiving pipe on peer:${t.remotePeer.toString()} -- stream:${r.id} -- protocol:${r.protocol}: `,e)}))}catch(e){ho.error("Error decoding message",e)}}}class mo{proto;constructor(e){this.proto=e}static createRequest(e,t){return new mo({requestId:ao(),request:{message:e,pubsubTopic:t},response:void 0})}static decode(e){const t=or.decode(e);return new mo(t)}encode(){return or.encode(this.proto)}get query(){return this.proto.request}get response(){return this.proto.response}}const yo=new gn("light-push"),bo="/vac/waku/lightpush/2.0.0-beta1";class wo extends to{pubsubTopics;constructor(e,t){super(bo,t.components,e),this.pubsubTopics=e}async preparePushMessage(e,t){try{if(!t.payload||0===t.payload.length)return yo.error("Failed to send waku light push: payload is empty"),{query:null,error:zr.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 yo.error("Failed to send waku light push: message is bigger than 1MB"),{query:null,error:zr.SIZE_TOO_BIG};const r=await e.toProtoObj(t);return r?{query:mo.createRequest(r,e.pubsubTopic),error:null}:(yo.error("Failed to encode to protoMessage, aborting push"),{query:null,error:zr.ENCODE_FAILED})}catch(e){return yo.error("Failed to prepare push message",e),{query:null,error:zr.GENERIC_FAIL}}}async send(e,t,r){const{query:n,error:o}=await this.preparePushMessage(e,t);if(o||!n)return{success:null,failure:{error:o,peerId:r.id}};let s,i;try{s=await this.getStream(r)}catch(e){return yo.error("Failed to get stream",e),{success:null,failure:{error:zr.NO_STREAM_AVAILABLE,peerId:r.id}}}try{i=await Kn([n.encode()],Ln,s,Fn,(async e=>await An(e)))}catch(e){return yo.error("Failed to send waku light push request",e),{success:null,failure:{error:zr.GENERIC_FAIL,peerId:r.id}}}const a=new _n;let c;i.forEach((e=>{a.append(e)}));try{c=mo.decode(a).response}catch(e){return yo.error("Failed to decode push reply",e),{success:null,failure:{error:zr.DECODE_FAILED,peerId:r.id}}}if(!c)return yo.error("Remote peer fault: No response in PushRPC"),{success:null,failure:{error:zr.NO_RESPONSE,peerId:r.id}};if((l=c.info)&&l.includes("could not generate rln-v2 proof")){const e=(e=>{const t={[zr.RLN_IDENTITY_MISSING]:zr.RLN_IDENTITY_MISSING,[zr.RLN_MEMBERSHIP_INDEX]:zr.RLN_MEMBERSHIP_INDEX,[zr.RLN_LIMIT_MISSING]:zr.RLN_LIMIT_MISSING},r=e.toLowerCase();for(const e in t)if(r.includes(e.toLowerCase()))return t[e];return zr.RLN_PROOF_GENERATION})(c.info);return yo.error("Remote peer rejected the message: ",e),{success:null,failure:{error:e,peerId:r.id}}}var l;return c.isSuccess?{success:r.id,failure:null}:(yo.error("Remote peer rejected the message: ",c.info),{success:null,failure:{error:zr.REMOTE_PEER_REJECTED,peerId:r.id}})}}const vo={payload:new Uint8Array,contentTopic:"",version:void 0,timestamp:void 0,meta:void 0,rateLimitProof:void 0,ephemeral:void 0},Eo=1e6;class So{proto;constructor(e){this.proto=e}static create(e){const t=new So({...e,requestId:ao(),timeStart:e.timeStart?BigInt(e.timeStart.getTime()*Eo):void 0,timeEnd:e.timeEnd?BigInt(e.timeEnd.getTime()*Eo):void 0,messageHashes:e.messageHashes||[],paginationLimit:e.paginationLimit?BigInt(e.paginationLimit):void 0});if(e.pubsubTopic&&!e.contentTopics||!e.pubsubTopic&&e.contentTopics)throw new Error("Both pubsubTopic and contentTopics must be set or unset");if(e.messageHashes&&(e.pubsubTopic||e.contentTopics||e.timeStart||e.timeEnd))throw new Error("Message hash lookup queries cannot include content filter criteria");return t}static decode(e){const t=cr.decode(e);return new So(t)}encode(){return cr.encode(this.proto)}}class Ao{proto;constructor(e){this.proto=e}static decode(e){const t=lr.decode(e);return new Ao(t)}encode(){return lr.encode(this.proto)}get statusCode(){return this.proto.statusCode}get statusDesc(){return this.proto.statusDesc}get messages(){return this.proto.messages}get paginationCursor(){return this.proto.paginationCursor}}const ko=new gn("store"),Co="/vac/waku/store-query/3.0.0";class Io extends to{pubsubTopics;constructor(e,t){super(Co,t.components,e),this.pubsubTopics=e}async*queryPerPage(e,t,r){if(e.contentTopics.toString()!==Array.from(t.keys()).toString())throw new Error("Internal error, the decoders should match the query's content topics");let n=e.paginationCursor;for(;;){const o=So.create({...e,paginationCursor:n});let s;try{s=await this.getStream(r)}catch(e){ko.error("Failed to get stream",e);break}const i=await Kn([o.encode()],Ln,s,Fn,(async e=>await An(e))),a=new _n;i.forEach((e=>{a.append(e)}));const c=Ao.decode(a);if(!c.statusCode||c.statusCode>=300){const e=`Store query failed with status code: ${c.statusCode}, description: ${c.statusDesc}`;throw ko.error(e),new Error(e)}if(!c.messages||!c.messages.length){ko.warn("Stopping pagination due to empty messages in response");break}ko.info(`${c.messages.length} messages retrieved from store`);const l=c.messages.map((e=>{if(!e.message)return Promise.resolve(void 0);const r=e.message.contentTopic;if(r){const o=t.get(r);if(o)return o.fromProtoObj(e.pubsubTopic||"",(n=e.message,{...vo,...n}))}var n;return Promise.resolve(void 0)}));if(yield l,n=e.paginationForward?c.messages[c.messages.length-1].messageHash:c.messages[0].messageHash,c.messages.length>100&&c.messages.length<(e.paginationLimit||20))break}}}class xo extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){const t=this.#e.get(e);return null==t?0:t.length}addEventListener(e,t,r){super.addEventListener(e,t,r);let n=this.#e.get(e);null==n&&(n=[],this.#e.set(e,n)),n.push({callback:t,once:(!0!==r&&!1!==r&&r?.once)??!1})}removeEventListener(e,t,r){super.removeEventListener(e.toString(),t??null,r);let n=this.#e.get(e);null!=n&&(n=n.filter((({callback:e})=>e!==t)),this.#e.set(e,n))}dispatchEvent(e){const t=super.dispatchEvent(e);let r=this.#e.get(e.type);return null==r||(r=r.filter((({once:e})=>!e)),this.#e.set(e.type,r)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}const To=new gn("keep-alive");class _o{relay;libp2p;options;pingKeepAliveTimers=new Map;relayKeepAliveTimers=new Map;constructor({options:e,relay:t,libp2p:r}){this.options=e,this.relay=t,this.libp2p=r}start(e){this.stop(e);const{pingKeepAlive:t,relayKeepAlive:r}=this.options,n=e.toString();if(0!==t){const r=setInterval((()=>{(async()=>{let r;try{try{r=await this.libp2p.services.ping.ping(e),To.info(`Ping succeeded (${n})`,r)}catch(e){return void To.error(`Ping failed for peer (${n}).\n Next ping will be attempted in ${t} seconds.\n `)}try{await this.libp2p.peerStore.merge(e,{metadata:{ping:rn(r.toString())}})}catch(e){To.error("Failed to update ping",e)}}catch(e){To.error(`Ping failed (${n})`,e)}})()}),1e3*t);this.pingKeepAliveTimers.set(n,r)}const o=this.relay;if(o&&0!==r){const t=this.scheduleRelayPings(o,r,e.toString());this.relayKeepAliveTimers.set(e,t)}}stop(e){const t=e.toString();this.pingKeepAliveTimers.has(t)&&(clearInterval(this.pingKeepAliveTimers.get(t)),this.pingKeepAliveTimers.delete(t)),this.relayKeepAliveTimers.has(e)&&(this.relayKeepAliveTimers.get(e)?.map(clearInterval),this.relayKeepAliveTimers.delete(e))}stopAll(){for(const e of[...Object.values(this.pingKeepAliveTimers),...Object.values(this.relayKeepAliveTimers)])clearInterval(e);this.pingKeepAliveTimers.clear(),this.relayKeepAliveTimers.clear()}connectionsExist(){return this.pingKeepAliveTimers.size>0||this.relayKeepAliveTimers.size>0}scheduleRelayPings(e,t,r){const n=[];for(const o of e.pubsubTopics){if(!e.getMeshPeers(o).includes(r))continue;const s=vn({pubsubTopicShardInfo:sn(o),contentTopic:"/relay-ping/1/ping/null",ephemeral:!0}),i=setInterval((()=>{To.info("Sending Waku Relay ping message"),e.send(s,{payload:new Uint8Array([1])}).catch((e=>To.error("Failed to send relay ping",e)))}),1e3*t);n.push(i)}return n}}const No=e=>{if(!e)return-1;try{const t=e.metadata.get("ping");return t?Number(tn(t)):-1}catch(e){return-1}},Po=new gn("connection-manager");class Lo extends xo{pubsubTopics;keepAliveManager;options;libp2p;dialAttemptsForPeer=new Map;dialErrorsForPeer=new Map;currentActiveParallelDialCount=0;pendingPeerDialQueue=[];isP2PNetworkConnected=!1;isConnected(){return!(globalThis?.navigator&&!globalThis?.navigator?.onLine)&&this.isP2PNetworkConnected}stop(){this.keepAliveManager.stopAll(),this.libp2p.removeEventListener("peer:connect",this.onEventHandlers["peer:connect"]),this.libp2p.removeEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"]),this.libp2p.removeEventListener("peer:discovery",this.onEventHandlers["peer:discovery"]),this.stopNetworkStatusListener()}async dropConnection(e){try{this.keepAliveManager.stop(e),await this.libp2p.hangUp(e),Po.info(`Dropped connection with peer ${e.toString()}`)}catch(t){Po.error(`Error dropping connection with peer ${e.toString()} - ${t}`)}}async getPeersByDiscovery(){const e=await this.libp2p.peerStore.all(),t=this.libp2p.getConnections().map((e=>e.remotePeer)),r=[],n=[],o=[],s=[],i=[],a=[];for(const t of e){const e=await this.getTagNamesForPeer(t.id);e.includes(Kr.BOOTSTRAP)?r.push(t):e.includes(Kr.PEER_EXCHANGE)?n.push(t):e.includes(Kr.LOCAL)&&o.push(t)}for(const e of t){const t=await this.libp2p.peerStore.get(e),r=await this.getTagNamesForPeer(e);r.includes(Kr.BOOTSTRAP)?s.push(t):r.includes(Kr.PEER_EXCHANGE)?i.push(t):r.includes(Kr.LOCAL)&&a.push(t)}return{DISCOVERED:{[Kr.BOOTSTRAP]:r,[Kr.PEER_EXCHANGE]:n,[Kr.LOCAL]:o},CONNECTED:{[Kr.BOOTSTRAP]:s,[Kr.PEER_EXCHANGE]:i,[Kr.LOCAL]:a}}}constructor(e){super(),this.libp2p=e.libp2p,this.pubsubTopics=e.pubsubTopics,this.options={maxDialAttemptsForPeer:3,maxBootstrapPeersAllowed:1,maxParallelDials:3,pingKeepAlive:300,relayKeepAlive:300,...e.config},this.keepAliveManager=new _o({relay:e.relay,libp2p:e.libp2p,options:{pingKeepAlive:this.options.pingKeepAlive,relayKeepAlive:this.options.relayKeepAlive}}),this.startEventListeners().then((()=>Po.info("Connection Manager is now running"))).catch((e=>Po.error("Unexpected error while running service",e))),this.dialPeerStorePeers().catch((e=>Po.error("Unexpected error while dialing peer store peers",e)))}async getConnectedPeers(e){const t=this.libp2p.getPeers();return 0===t.length?[]:(await Promise.all(t.map((async e=>{try{return await this.libp2p.peerStore.get(e)}catch(e){return null}})))).filter((e=>!!e)).filter((t=>!e||t.protocols.includes(e))).sort(((e,t)=>No(e)-No(t)))}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){Po.error("Unexpected error while dialing peer store peers",e)}}async startEventListeners(){this.startPeerDiscoveryListener(),this.startPeerConnectionListener(),this.startPeerDisconnectionListener(),this.startNetworkStatusListener()}async dialPeer(e){this.currentActiveParallelDialCount+=1;let t=0;for(;t{e.tags=Array.from(new Set([...e.tags,...r]))})),this.dialAttemptsForPeer.set(e.toString(),-1),this.keepAliveManager.start(e);break}catch(r){r instanceof AggregateError?Po.error(`Error dialing peer ${e.toString()} - ${r.errors}`):Po.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?Po.warn("Errors array is empty for AggregateError"):r=JSON.stringify(t.errors[0]):Po.warn("No errors array found for AggregateError"):r=t.message,Po.info(`Deleting undialable peer ${e.toString()} from peer store. Reason: ${r}`)}this.dialErrorsForPeer.delete(e.toString()),await this.libp2p.peerStore.delete(e),await this.attemptDnsDiscovery()}catch(t){throw new Error(`Error deleting undialable peer ${e.toString()} from peer store - ${t}`)}}async attemptDnsDiscovery(){if(this.libp2p.getConnections().length>0)return;if((await this.libp2p.peerStore.all()).length>0)return;Po.info("Attempting to trigger DNS discovery.");const e=Object.values(this.libp2p.components.components).find((e=>!(!e||!e.toString)&&e.toString().includes(Jr)));e&&await e.findPeers()}processDialQueue(){if(this.pendingPeerDialQueue.length>0&&this.currentActiveParallelDialCount{Po.error(e)}))}}startPeerDiscoveryListener(){this.libp2p.addEventListener("peer:discovery",this.onEventHandlers["peer:discovery"])}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onEventHandlers["peer:connect"])}startPeerDisconnectionListener(){this.libp2p.addEventListener("peer:disconnect",this.onEventHandlers["peer:disconnect"])}async attemptDial(e){await this.shouldDialPeer(e)&&(this.currentActiveParallelDialCount>=this.options.maxParallelDials?this.pendingPeerDialQueue.push(e):await this.dialPeer(e))}onEventHandlers={"peer:discovery":e=>{(async()=>{const{id:t}=e.detail;await this.dispatchDiscoveryEvent(t);try{await this.attemptDial(t)}catch(e){Po.error(`Error dialing peer ${t.toString()} : ${e}`)}})()},"peer:connect":e=>{(async()=>{Po.info(`Connected to peer ${e.detail.toString()}`);const t=e.detail;this.keepAliveManager.start(t),(await this.getTagNamesForPeer(t)).includes(Kr.BOOTSTRAP)?this.libp2p.getConnections().filter((e=>e.tags.includes(Kr.BOOTSTRAP))).length>this.options.maxBootstrapPeersAllowed?await this.dropConnection(t):this.dispatchEvent(new CustomEvent(Gr.PEER_CONNECT_BOOTSTRAP,{detail:t})):this.dispatchEvent(new CustomEvent(Gr.PEER_CONNECT_PEER_EXCHANGE,{detail:t})),this.setP2PNetworkConnected()})()},"peer:disconnect":e=>{(async()=>{this.keepAliveManager.stop(e.detail),this.setP2PNetworkDisconnected()})()},"browser:network":()=>{this.dispatchWakuConnectionEvent()}};async shouldDialPeer(e){if(this.libp2p.getConnections(e).length>0)return Po.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 Po.warn(`Discovered peer ${e.toString()} with ShardInfo ${t} is not part of any of the configured pubsub topics (${this.pubsubTopics}).\n Not dialing.`),!1}return await this.isPeerDialableBasedOnBootstrapStatus(e)?!this.dialAttemptsForPeer.has(e.toString())||(Po.warn(`Peer ${e.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`),!1):(Po.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===Kr.BOOTSTRAP))||this.libp2p.getConnections().filter((e=>e.tags.find((e=>e===Kr.BOOTSTRAP)))).lengththis.pubsubTopics.includes(e)))}async getPeerShardInfo(e,t){const r=(await t.get(e)).metadata.get("shardInfo");if(r)return hn(r)}startNetworkStatusListener(){try{globalThis.addEventListener("online",this.onEventHandlers["browser:network"]),globalThis.addEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Po.error(`Failed to start network listener: ${e}`)}}stopNetworkStatusListener(){try{globalThis.removeEventListener("online",this.onEventHandlers["browser:network"]),globalThis.removeEventListener("offline",this.onEventHandlers["browser:network"])}catch(e){Po.error(`Failed to stop network listener: ${e}`)}}setP2PNetworkConnected(){this.isP2PNetworkConnected||(this.isP2PNetworkConnected=!0,this.dispatchWakuConnectionEvent())}setP2PNetworkDisconnected(){this.isP2PNetworkConnected&&0===this.libp2p.getConnections().length&&(this.isP2PNetworkConnected=!1,this.dispatchWakuConnectionEvent())}dispatchWakuConnectionEvent(){this.dispatchEvent(new CustomEvent(Wr.CONNECTION_STATUS,{detail:this.isConnected()}))}}class Bo{static instance;health;constructor(){this.health={overallStatus:Yr.Unhealthy,protocolStatuses:new Map}}static getInstance(){return Bo.instance||(Bo.instance=new Bo),Bo.instance}getHealthStatus(){return this.health.overallStatus}getProtocolStatus(e){return this.health.protocolStatuses.get(e)}updateProtocolHealth(e,t){const r=this.getNameFromMulticodec(e);let n=Yr.Unhealthy;1==t?n=Yr.MinimallyHealthy:t>=2&&(n=Yr.SufficientlyHealthy),this.health.protocolStatuses.set(r,{name:r,status:n,lastUpdate:new Date}),this.updateOverallHealth()}getNameFromMulticodec(e){let t;if(e.includes("filter"))t=Vr.Filter;else if(e.includes("lightpush"))t=Vr.LightPush;else{if(!e.includes("store"))throw new Error(`Unknown protocol: ${e}`);t=Vr.Store}return t}updateOverallHealth(){const e=[Vr.LightPush,Vr.Filter].map((e=>this.getProtocolStatus(e)?.status));e.some((e=>e===Yr.Unhealthy))?this.health.overallStatus=Yr.Unhealthy:e.some((e=>e===Yr.MinimallyHealthy))?this.health.overallStatus=Yr.MinimallyHealthy:this.health.overallStatus=Yr.SufficientlyHealthy}}const Oo=()=>Bo.getInstance(),Ro=new gn("metadata"),Do="/vac/waku/metadata/1.0.0";class Uo extends to{pubsubTopics;libp2pComponents;handshakesConfirmed=new Map;constructor(e,t){super(Do,t.components,e),this.pubsubTopics=e,this.libp2pComponents=t,t.registrar.handle(Do,(e=>{this.onRequest(e)}))}async query(e){const t=mr.encode(an(this.pubsubTopics)),r=await this.libp2pComponents.peerStore.get(e);if(!r)return{shardInfo:null,error:zr.NO_PEER_AVAILABLE};let n;try{n=await this.getStream(r)}catch(s){return Ro.error("Failed to get stream",s),{shardInfo:null,error:zr.NO_STREAM_AVAILABLE}}const o=await Kn([t],Ln,n,Fn,(async e=>await An(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(o);return s?{shardInfo:null,error:s}:(await this.savePeerShardInfo(e,i),{shardInfo:i,error:null})}async confirmOrAttemptHandshake(e){const t=this.handshakesConfirmed.get(e.toString());return t?{shardInfo:t,error:null}:await this.query(e)}async onRequest(e){try{const{stream:t,connection:r}=e,n=yr.encode(an(this.pubsubTopics)),o=await Kn([n],Ln,t,Fn,(async e=>await An(e))),{error:s,shardInfo:i}=this.decodeMetadataResponse(o);if(s)return;await this.savePeerShardInfo(r.remotePeer,i)}catch(e){Ro.error("Error handling metadata request",e)}}decodeMetadataResponse(e){const t=new _n;e.forEach((e=>{t.append(e)}));const r=yr.decode(t);return r?{shardInfo:r,error:null}:(Ro.error("Error decoding metadata response"),{shardInfo:null,error:zr.DECODE_FAILED})}async savePeerShardInfo(e,t){await this.libp2pComponents.peerStore.merge(e,{metadata:{shardInfo:dn(t)}}),this.handshakesConfirmed.set(e.toString(),t)}}function Mo(e){return t=>new Uo(e,t)}const Fo=Symbol.for("@libp2p/peer-id");function $o(e){return Boolean(e?.[Fo])}const qo=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 o=0,s=0;const i=this.peekChar();if(void 0===i)return;const a="0"===i,c=2**(8*n)-1;for(;;){const r=this.readAtomically((()=>{const t=this.readChar();if(void 0===t)return;const r=Number.parseInt(t,e);return Number.isNaN(r)?void 0:r}));if(void 0===r)break;if(o*=e,o+=r,o>c)return;if(s+=1,void 0!==t&&s>t)return}return 0===s||!r&&a&&s>1?void 0:o}))}readIPv4Addr(){return this.readAtomically((()=>{const e=new Uint8Array(4);for(let t=0;tthis.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){const e=e=>{for(let t=0;tthis.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 o=new Uint8Array(14),s=16-(r+2),[i]=e(o.subarray(0,s));return t.set(o.subarray(0,i),16-i),t}))}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};function Ho(e){if(!(e.length>15))return qo.new(e).parseWith((()=>qo.readIPv4Addr()))}function jo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return qo.new(e).parseWith((()=>qo.readIPv6Addr()))}function Vo(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return qo.new(e).parseWith((()=>qo.readIPAddr()))}const zo=(parseInt("0xFFFF",16),new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]));function Ko(e,t){16===t.length&&4===e.length&&function(e){let t=0;for(const r of e)if(!(t<0)){if(t>11)break;if(255!==r)return!1;t++}return!0}(t)&&(t=t.slice(12)),4===t.length&&16===e.length&&function(e,t){let r=0;for(const n of e)if(!(r<0)){if(r>11)break;if(n!==t[r])return!1;r++}return!0}(e,zo)&&(e=e.slice(12));const r=e.length;if(r!=t.length)throw new Error("Failed to mask ip");const n=new Uint8Array(r);for(let o=0;ot)throw new Error("Invalid CIDR mask");const r=t/8,n=new Uint8Array(r);for(let t=0;t=8?(n[t]=255,e-=8):(n[t]=255-(255>>e),e=0);return n}class Wo{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){const[t,r]=e.split("/");if(!t||!r)throw new Error("Failed to parse given CIDR: "+e);let n=4,o=Ho(t);if(null==o&&(n=16,o=jo(t),null==o))throw new Error("Failed to parse given CIDR: "+e);const s=parseInt(r,10);if(Number.isNaN(s)||String(s).length!==r.length||s<0||s>8*n)throw new Error("Failed to parse given CIDR: "+e);const i=Go(s,8*n);return{network:Ko(o,i),mask:i}}(e));else{const r=Vo(e);if(null==r)throw new Error("Failed to parse network");t=String(t);const n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>8*r.length){const e=Vo(t);if(null==e)throw new Error("Failed to parse mask");this.mask=e}else this.mask=Go(n,8*r.length);this.network=Ko(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=Vo(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(let r=0;r>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case 4:return e.join(".");case 16:{const t=[];for(let r=0;r{r[t++]=255&parseInt(e,10)})),r}if(Qo(e)){const r=e.split(":",8);let n;for(n=0;n0;n--)e.push("0");r.splice.apply(r,e)}const o=new Uint8Array(t+16);for(n=0;n>8&255,o[t++]=255&e}return o}throw new Error("invalid ip address")},ts=-1,rs={},ns={};function os(e){if("number"==typeof e){if(null!=ns[e])return ns[e];throw new Error(`no protocol with code: ${e}`)}if("string"==typeof e){if(null!=rs[e])return rs[e];throw new Error(`no protocol with name: ${e}`)}throw new Error("invalid protocol id type: "+typeof e)}function ss(e,t){switch(os(e).code){case 4:case 41:return function(e){const t=function(e,t=0,r){t=~~t,r=r??e.length-t;const n=new DataView(e.buffer);if(4===r){const n=[];for(let o=0;o65536)throw new Error("Port number is not in range(1, 65536)");const o=ls(n);return kn([r,o],r.length+o.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=he.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 o=ls(n);return kn([r,o],r.length+o.length)}(t);case 466:return function(e){const t=cs.decode(e),r=Uint8Array.from(_(t.length));return kn([r,t],r.length+t.length)}(t);case 481:return hs(globalThis.decodeURIComponent(t));default:return xt(t,"base16")}}[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,ts,"ip6zone"],[43,8,"ipcidr"],[53,ts,"dns",!0],[54,ts,"dns4",!0],[55,ts,"dns6",!0],[56,ts,"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,ts,"unix",!1,!0],[421,ts,"ipfs"],[421,ts,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,ts,"garlic64"],[448,0,"tls"],[449,ts,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,ts,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,ts,"http-path"],[777,ts,"memory"]].forEach((e=>{const t=function(e,t,r,n,o){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(o)}}(...e);ns[t.code]=t,rs[t.name]=t})),os("ip4"),os("ip6"),os("ipcidr");const as=Object.values(St).map((e=>e.decoder)),cs=function(){let e=as[0].or(as[1]);return as.slice(2).forEach((t=>e=e.or(t))),e}();function ls(e){const t=new ArrayBuffer(2);return new DataView(t).setUint16(0,e),new Uint8Array(t)}function us(e){return new DataView(e.buffer).getUint16(e.byteOffset)}function hs(e){const t=xt(e),r=Uint8Array.from(_(t.length));return kn([r,t],r.length+t.length)}function ds(e){const t=N(e);if((e=e.slice(I(t))).length!==t)throw new Error("inconsistent lengths");return Zr(e)}function ps(e){const t=[],r=[];let n=null,o=0;for(;oe.length)throw bs("Invalid address Uint8Array: "+Zr(e,"base16"));t.push([s,l]);const u=ss(s,l);if(r.push([s,u]),!0===a.path){n=u;break}}return{bytes:Uint8Array.from(e),string:fs(r),tuples:t,stringTuples:r,path:n}}function fs(e){const t=[];return e.map((e=>{const r=os(e[0]);return t.push(r.name),e.length>1&&null!=e[1]&&t.push(e[1]),null})),ys(t.join("/"))}function gs(e){return kn(e.map((e=>{const t=os(e[0]);let r=Uint8Array.from(_(t.code));return e.length>1&&null!=e[1]&&(r=kn([r,e[1]])),r})))}function ms(e,t){if(e.size>0)return e.size/8;if(0===e.size)return 0;{const e=N(t instanceof Uint8Array?t:Uint8Array.from(t));return e+I(e)}}function ys(e){return"/"+e.trim().split("/").filter((e=>e)).join("/")}function bs(e){return new Error("Error parsing address: "+e)}const ws=Symbol.for("nodejs.util.inspect.custom"),vs=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Es=[os("dns").code,os("dns4").code,os("dns6").code,os("dnsaddr").code];class Ss extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}}class As{bytes;#t;#r;#n;#o;[vs]=!0;constructor(e){let t;if(null==e&&(e=""),e instanceof Uint8Array)t=ps(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 o=(e=ys(e)).split("/").slice(1);if(1===o.length&&""===o[0])return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s=o.length)throw bs("invalid address: "+e);if(!0===i.path){n=ys(o.slice(s).join("/")),t.push([i.code,is(i.code,n)]),r.push([i.code,n]);break}const a=is(i.code,o[s]);t.push([i.code,a]),r.push([i.code,ss(i.code,a)])}return{string:fs(r),bytes:gs(t),tuples:t,stringTuples:r,path:n}}(e)}else{if(!Cs(e))throw new Error("addr must be a string, Buffer, or another Multiaddr");t=ps(e.bytes)}this.bytes=t.bytes,this.#t=t.string,this.#r=t.tuples,this.#n=t.stringTuples,this.#o=t.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let e,t,r,n,o="";const s=os("tcp"),i=os("udp"),a=os("ip4"),c=os("ip6"),l=os("dns6"),u=os("ip6zone");for(const[h,d]of this.stringTuples())h===u.code&&(o=`%${d??""}`),Es.includes(h)&&(t=s.name,n=443,r=`${d??""}${o}`,e=h===l.code?6:4),h!==s.code&&h!==i.code||(t=os(h).name,n=parseInt(d??"")),h!==a.code&&h!==c.code||(t=os(h).name,r=`${d??""}${o}`,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({},os(e))))}protoCodes(){return this.#r.map((([e])=>e))}protoNames(){return this.#r.map((([e])=>os(e).name))}tuples(){return this.#r.map((([e,t])=>null==t?[e]:[e,t]))}stringTuples(){return this.#n.map((([e,t])=>null==t?[e]:[e,t]))}encapsulate(e){return e=new As(e),new As(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 As(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 As(gs(t.slice(0,r)));return this}getPeerId(){try{let e=[];this.stringTuples().forEach((([t,r])=>{t===rs.p2p.code&&e.push([t,r]),t===rs["p2p-circuit"].code&&(e=[])}));const t=e.pop();if(null!=t?.[1]){const e=t[1];return"Q"===e[0]||"1"===e[0]?Zr(Se.decode(`z${e}`),"base58btc"):Zr(yt.parse(e).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){return this.#o}equals(e){return Cn(this.bytes,e.bytes)}async resolve(e){const t=this.protos().find((e=>e.resolvable));if(null==t)return[this];const r=ks.get(t.name);if(null==r)throw new Ss(`no available resolver for ${t.name}`);return(await r(this,e)).map((e=>Is(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)}[ws](){return`Multiaddr(${this.#t})`}}const ks=new Map;function Cs(e){return Boolean(e?.[vs])}function Is(e){return new As(e)}function xs(e,t){const r=rn(e),n=rn(t.contentTopic),o=function(e){if(!e)return;let t;return t="bigint"==typeof e?e:1000000n*BigInt(e.valueOf()),function(e){const t=new ArrayBuffer(8),r=new DataView(t);return"number"==typeof e?r.setFloat64(0,e,!1):r.setBigInt64(0,e,!1),new Uint8Array(t)}(t)}(t.timestamp),s=nn([r,t.payload,n,t.meta,o].filter(Ar));return jr(s)}class Ts{peers=[];isStarted=!1;pubsubTopic;config;libp2p;filter;peerManager;connectionManager;activeSubscriptions;keepAliveIntervalId;pingFailedAttempts=new Map;receivedMessagesFormPeer=new Set;receivedMessages=new Set;verifiedPeers=new Set;constructor(e){this.config=e.config,this.connectionManager=e.connectionManager,this.filter=e.filter,this.peerManager=e.peerManager,this.libp2p=e.libp2p,this.activeSubscriptions=e.activeSubscriptions,this.pubsubTopic=e.pubsubTopic,this.onConnectionChange=this.onConnectionChange.bind(this),this.onPeerConnected=this.onPeerConnected.bind(this),this.onPeerDisconnected=this.onPeerDisconnected.bind(this)}get reservedContentTopic(){return`/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`}start(){this.isStarted||(this.isStarted=!0,this.startKeepAlive(),this.startConnectionListener(),this.startPeerConnectionListener())}stop(){this.isStarted&&(this.isStarted=!1,this.stopKeepAlive(),this.stopConnectionListener(),this.stopPeerConnectionListener())}async getPeers(){return this.isStarted||(this.peers=await this.peerManager.getPeers()),this.peers}notifyMessageReceived(e,t){const r=this.buildMessageHash(t);return this.verifiedPeers.add(e),this.receivedMessagesFormPeer.add(`${e}-${r}`),!!this.receivedMessages.has(r)||(this.receivedMessages.add(r),!1)}buildMessageHash(e){return function(e,t){const r=xs(e,t);return en(r)}(this.pubsubTopic,e)}startConnectionListener(){this.connectionManager.addEventListener(Wr.CONNECTION_STATUS,this.onConnectionChange)}stopConnectionListener(){this.connectionManager.removeEventListener(Wr.CONNECTION_STATUS,this.onConnectionChange)}async onConnectionChange({detail:e}){e?(await Promise.all(this.peers.map((e=>this.ping(e,!0)))),this.startKeepAlive()):this.stopKeepAlive()}startKeepAlive(){this.keepAliveIntervalId||(this.keepAliveIntervalId=setInterval((()=>{this.peers.map((e=>this.ping(e)))}),this.config.keepAliveIntervalMs))}stopKeepAlive(){this.keepAliveIntervalId&&(clearInterval(this.keepAliveIntervalId),this.keepAliveIntervalId=void 0)}startPeerConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onPeerConnected),this.libp2p.addEventListener("peer:disconnect",this.onPeerDisconnected)}stopPeerConnectionListener(){this.libp2p.removeEventListener("peer:connect",this.onPeerConnected),this.libp2p.removeEventListener("peer:disconnect",this.onPeerDisconnected)}async onPeerConnected(e){this.peers.length>0||(this.peers=await this.peerManager.getPeers(),await Promise.all(this.peers.map((e=>this.subscribe(e)))))}async onPeerDisconnected(e){!this.peers.find((t=>t.id.equals(e.detail)))||(this.peers=await this.peerManager.getPeers(),await Promise.all(this.peers.map((e=>this.subscribe(e)))))}async subscribe(e){let t=e;for(let e=0;e<3;e++){if(!t)return;if((await this.filter.subscribe(this.pubsubTopic,t,Array.from(this.activeSubscriptions.keys()))).success)return;t=await this.peerManager.requestRenew(t.id)}}async ping(e,t=!1){const r=e.id.toString(),n=await this.filter.ping(e);if(n.failure&&t){const t=await this.peerManager.requestRenew(e.id);await this.subscribe(t)}else{if(n.failure){const e=this.pingFailedAttempts.get(r)||0;this.pingFailedAttempts.set(r,e+1)}if(n.success&&this.pingFailedAttempts.set(r,0),(this.pingFailedAttempts.get(r)||0)>=this.config.pingsBeforePeerRenewed){const t=await this.peerManager.requestRenew(e.id);await this.subscribe(t)}}}}const _s=new gn("sdk:filter:subscription");class Ns{pubsubTopic;protocol;config;monitor;subscriptionCallbacks=new Map;constructor(e,t,r,n,o,s,i){this.pubsubTopic=e,this.protocol=t,this.config=s,this.pubsubTopic=e,this.monitor=new Ts({pubsubTopic:e,config:s,libp2p:o,connectionManager:r,filter:t,peerManager:n,lightPush:i,activeSubscriptions:this.subscriptionCallbacks})}async subscribe(e,t){const r=Array.isArray(e)?e:[e];for(const e of r)if(e.pubsubTopic!==this.pubsubTopic)return{failures:[{error:zr.TOPIC_DECODER_MISMATCH}],successes:[]};this.config.enableLightPushFilterCheck&&r.push(Sn(this.monitor.reservedContentTopic,this.pubsubTopic));const n=kr(r),o=Array.from(n.keys()),s=(await this.monitor.getPeers()).map((async e=>this.protocol.subscribe(this.pubsubTopic,e,o))),i=await Promise.allSettled(s),a=this.handleResult(i,"subscribe");return n.forEach(((e,r)=>{const n={decoders:e,callback:t};r!==this.monitor.reservedContentTopic&&this.subscriptionCallbacks.set(r,n)})),this.monitor.start(),a}async unsubscribe(e){const t=(await this.monitor.getPeers()).map((async t=>{const r=await this.protocol.unsubscribe(this.pubsubTopic,t,e);return e.forEach((e=>{this.subscriptionCallbacks.delete(e)})),r})),r=await Promise.allSettled(t),n=this.handleResult(r,"unsubscribe");return 0===this.subscriptionCallbacks.size&&this.monitor.stop(),n}async ping(){const e=(await this.monitor.getPeers()).map((e=>this.protocol.ping(e))),t=await Promise.allSettled(e);return this.handleResult(t,"ping")}async unsubscribeAll(){const e=(await this.monitor.getPeers()).map((async e=>this.protocol.unsubscribeAll(this.pubsubTopic,e))),t=await Promise.allSettled(e);this.subscriptionCallbacks.clear();const r=this.handleResult(t,"unsubscribeAll");return this.monitor.stop(),r}async processIncomingMessage(e,t){if(this.monitor.notifyMessageReceived(t,e))return void _s.info("Message already received, skipping");const{contentTopic:r}=e,n=this.subscriptionCallbacks.get(r);n?(_s.info("Processing message with content topic ",r," on pubsub topic ",this.pubsubTopic),await async function(e,t,r){const{decoders:n,callback:o}=e,{contentTopic:s}=r;if(s)try{const e=n.map((e=>e.fromProtoObj(t,r).then((e=>e||Promise.reject("Decoding failed"))))),s=await Promise.any(e);await o(s)}catch(e){_s.error("Error decoding message",e)}else _s.warn("Message has no content topic, skipping")}(n,this.pubsubTopic,e)):_s.error("No subscription callback available for ",r)}handleResult(e,t){const r={failures:[],successes:[]};for(const n of e)if("rejected"===n.status)_s.error(`Failed to resolve ${t} promise successfully: `,n.reason),r.failures.push({error:zr.GENERIC_FAIL});else{const e=n.value;e.failure?r.failures.push(e.failure):r.successes.push(e.success)}return r}}const Ps=new gn("sdk:filter");class Ls{connectionManager;libp2p;peerManager;lightPush;protocol;config;activeSubscriptions=new Map;constructor(e,t,r,n,o){this.connectionManager=e,this.libp2p=t,this.peerManager=r,this.lightPush=n,this.config=(e=>({keepAliveIntervalMs:e?.keepAliveIntervalMs||6e4,pingsBeforePeerRenewed:e?.pingsBeforePeerRenewed||3,enableLightPushFilterCheck:e?.enableLightPushFilterCheck||!1}))(o),this.protocol=new go((async(e,t,r)=>{const n=this.getActiveSubscription(e);n?await n.processIncomingMessage(t,r):Ps.error(`No subscription locally registered for topic ${e}`)}),e.pubsubTopics,t),this.activeSubscriptions=new Map}async subscribe(e,t){const r=this.getUniquePubsubTopics(e);if(1!==r.length)return{subscription:null,error:zr.INVALID_DECODER_TOPICS,results:null};const n=r[0],{subscription:o,error:s}=await this.createSubscription(n);if(s)return{subscription:null,error:s,results:null};const{failures:i,successes:a}=await o.subscribe(e,t);return{subscription:o,error:null,results:{failures:i,successes:a}}}async createSubscription(e){const t="string"==typeof e?e:on(e)?.[0];cn(t,this.protocol.pubsubTopics);const r=await this.peerManager.getPeers();return 0===r.length?{error:zr.NO_PEER_AVAILABLE,subscription:null}:(Ps.info(`Creating filter subscription with ${r.length} peers: `,r.map((e=>e.id.toString()))),{error:null,subscription:this.getActiveSubscription(t)??this.setActiveSubscription(t,new Ns(t,this.protocol,this.connectionManager,this.peerManager,this.libp2p,this.config,this.lightPush))})}async subscribeWithUnsubscribe(e,t){const r=this.getUniquePubsubTopics(e);if(0===r.length)throw Error("Failed to subscribe: no pubsubTopic found on decoders provided.");if(r.length>1)throw Error("Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.");const{subscription:n,error:o}=await this.createSubscription(r[0]);if(o)throw Error(`Failed to create subscription: ${o}`);await n.subscribe(e,t);const s=Array.from(kr(Array.isArray(e)?e:[e]).keys());return async()=>{await n.unsubscribe(s)}}toSubscriptionIterator(e){return async function(e,t,r){const n=[];let o;o=await e.subscribeWithUnsubscribe(t,(e=>{n.push(e)}));const s=Number.isInteger(r?.timeoutMs),i=Date.now();return{iterator:async function*(){for(;;){if(s&&Date.now()-i>=0)return;await Cr(60);const e=n.shift();if(!o&&0===n.length)return e;!e&&o||(yield e)}}(),async stop(){o&&(await o(),o=void 0)}}}(this,e)}getActiveSubscription(e){return this.activeSubscriptions.get(e)}setActiveSubscription(e,t){return this.activeSubscriptions.set(e,t),t}getUniquePubsubTopics(e){if(!Array.isArray(e))return[e.pubsubTopic];if(0===e.length)return[];const t=new Set(e.map((e=>e.pubsubTopic)));return[...t]}}const Bs=new gn("sdk:light-push"),Os={autoRetry:!1,maxAttempts:3};class Rs{peerManager;protocol;constructor(e,t,r){this.peerManager=t,this.protocol=new wo(e.pubsubTopics,r)}async send(e,t,r=Os){const n=[],o=[],{pubsubTopic:s}=e;try{cn(s,this.protocol.pubsubTopics)}catch(e){return Bs.error("Failed to send waku light push: pubsub topic not configured"),{successes:n,failures:[{error:zr.TOPIC_NOT_CONFIGURED}]}}const i=await this.peerManager.getPeers();if(0===i.length)return{successes:n,failures:[{error:zr.NO_PEER_AVAILABLE}]};const a=await Promise.allSettled(i.map((r=>this.protocol.send(e,t,r))));for(const s of a){if("fulfilled"!==s.status){Bs.error("Failed unexpectedly while sending:",s.reason),o.push({error:zr.GENERIC_FAIL});continue}const{failure:i,success:a}=s.value;a?n.push(a):i&&(o.push(i),r?.autoRetry&&this.attemptRetries((r=>this.protocol.send(e,t,r)),r.maxAttempts))}return Oo().updateProtocolHealth(this.protocol.multicodec,n.length),{successes:n,failures:o}}async attemptRetries(e,t){t=t||3;const r=await this.peerManager.getPeers();if(0!==r.length)for(let n=0;nthis.mapConnectionToPeer(e))))}async requestRenew(e){const t=this.getLockedConnections(),r=this.numPeersToUse-t.length;if(0===r)return;const n=(await Promise.all(this.getUnlockedConnections().filter((t=>!t.remotePeer.equals(e))).slice(0,r).map((e=>this.lockConnection(e))).map((e=>this.mapConnectionToPeer(e)))))[0];if(n)return Ds.info(`requestRenew: Renewed peer ${e.toString()} to ${n.id.toString()}`),n;Ds.warn(`requestRenew: Couldn't renew peer ${e.toString()}.`)}startConnectionListener(){this.libp2p.addEventListener("peer:connect",this.onConnected),this.libp2p.addEventListener("peer:disconnect",this.onDisconnected)}stopConnectionListener(){this.libp2p.removeEventListener("peer:connect",this.onConnected),this.libp2p.removeEventListener("peer:disconnect",this.onDisconnected)}onConnected(e){const t=e.detail;this.lockPeerIfNeeded(t)}onDisconnected(e){const t=e.detail;this.requestRenew(t)}async lockPeerIfNeeded(e){const t=this.getLockedConnections();0!=this.numPeersToUse-t.length&&this.getUnlockedConnections().filter((t=>t.remotePeer.equals(e))).map((e=>this.lockConnection(e)))}getLockedConnections(){return this.libp2p.getConnections().filter((e=>"open"===e.status&&this.isConnectionLocked(e)))}getUnlockedConnections(){return this.libp2p.getConnections().filter((e=>"open"===e.status&&!this.isConnectionLocked(e)))}lockConnection(e){return Ds.info(`requestRenew: Locking connection for peerId=${e.remotePeer.toString()}`),e.tags.push(Us),e}isConnectionLocked(e){return e.tags.includes(Us)}async mapConnectionToPeer(e){const t=e.remotePeer;return this.libp2p.peerStore.get(t)}}const Fs=new gn("waku:store:sdk");class $s{peerManager;protocol;constructor(e,t,r){this.peerManager=r,this.protocol=new Io(e.pubsubTopics,t)}async*queryGenerator(e,t){const{pubsubTopic:r,contentTopics:n,decodersAsMap:o}=this.validateDecodersAndPubsubTopic(e),s={pubsubTopic:r,contentTopics:n,includeData:!0,paginationForward:!0,...t},i=(await this.peerManager.getPeers())[0];if(!i)throw Fs.error("No peers available to query"),new Error("No peers available to query");Fs.info(`Querying store with options: ${JSON.stringify(t)}`);const a=this.protocol.queryPerPage(s,o,i);for await(const e of a)yield e}async queryWithOrderedCallback(e,t,r){Fs.info("Querying store with ordered callback");for await(const n of this.queryGenerator(e,r))if(await this.processMessages(n,t))break}async queryWithPromiseCallback(e,t,r){Fs.info("Querying store with promise callback");let n=!1;for await(const o of this.queryGenerator(e,r)){const e=o.map((async e=>{n||(n=Boolean(await t(e)))}));if(await Promise.all(e),n)break}}async processMessages(e,t){let r=!1;const n=(await Promise.all(e)).filter(Ar);return await Promise.all(n.map((async e=>{e&&!r&&(r=Boolean(await t(e)))}))),r}createCursor(e){return xs(e.pubsubTopic,e)}validateDecodersAndPubsubTopic(e){if(0===e.length)throw Fs.error("No decoders provided"),new Error("No decoders provided");const t=Array.from(new Set(e.map((e=>e.pubsubTopic))));if(t.length>1)throw Fs.error("API does not support querying multiple pubsub topics at once"),new Error("API does not support querying multiple pubsub topics at once");const r=t[0];cn(r,this.protocol.pubsubTopics);const n=new Map;e.forEach((e=>{if(n.has(e.contentTopic))throw Fs.error("API does not support different decoder per content topic"),new Error("API does not support different decoder per content topic");n.set(e.contentTopic,e)}));const o=e.filter((e=>e.pubsubTopic===r)).map((e=>e.contentTopic));if(0===o.length)throw Fs.error(`No decoders found for topic ${r}`),new Error("No decoders found for topic "+r);return{pubsubTopic:r,contentTopics:o,decodersAsMap:n}}}const qs=new gn("wait-for-remote-peer");async function Hs(e,t){qs.info(`Waiting for ${e} peer.`),await new Promise((r=>{const n=async o=>{if(o.detail?.protocols?.includes(e)){const e=t.services.metadata;if(!e)return t.removeEventListener("peer:identify",n),void r();try{await e.confirmOrAttemptHandshake(o.detail.peerId),t.removeEventListener("peer:identify",n),r()}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&qs.error("Connection closed. Some peers can be on different shard."),qs.error(`Error waiting for metadata: ${e}`)}}};t.addEventListener("peer:identify",n)}))}const js=(e,t)=>new Promise(((r,n)=>setTimeout((()=>n(Error(t))),e))),Vs=new gn("waku");class zs{pubsubTopics;libp2p;relay;store;filter;lightPush;connectionManager;health;peerManager;constructor(e,t,r,n,o){this.pubsubTopics=e,this.relay=o,this.libp2p=r,n={filter:!1,lightpush:!1,store:!1,...n};const s=this.libp2p.peerId.toString();if(this.connectionManager=new Lo({libp2p:r,relay:this.relay,pubsubTopics:this.pubsubTopics,config:t?.connectionManager}),this.peerManager=new Ms({libp2p:r,config:{numPeersToUse:t.numPeersToUse}}),this.health=Oo(),n.store){const e=(i=this.connectionManager,a=this.peerManager,e=>new $s(i,e,a));this.store=e(r)}var i,a;if(n.lightpush){const e=function(e,t){return r=>new Rs(e,t,r)}(this.connectionManager,this.peerManager);this.lightPush=e(r)}if(n.filter){const e=function(e,t,r,n){return o=>new Ls(e,o,t,r,n)}(this.connectionManager,this.peerManager,this.lightPush,t.filter);this.filter=e(r)}Vs.info("Waku node created",s,`relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this.lightPush}, filter: ${!!this.filter}`)}get peerId(){return this.libp2p.peerId}get protocols(){return this.libp2p.getProtocols()}async dial(e,t){const r=t??[],n=this.mapToPeerIdOrMultiaddr(e);void 0===t&&(this.relay&&r.push(Vr.Relay),this.store&&r.push(Vr.Store),this.filter&&r.push(Vr.Filter),this.lightPush&&r.push(Vr.LightPush));const o=[];return r.includes(Vr.Relay)&&(this.relay?this.relay.gossipSub.multicodecs.forEach((e=>o.push(e))):Vs.error("Relay codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.Store)&&(this.store?o.push(this.store.protocol.multicodec):Vs.error("Store codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.LightPush)&&(this.lightPush?o.push(this.lightPush.protocol.multicodec):Vs.error("Light Push codec not included in dial codec: protocol not mounted locally")),r.includes(Vr.Filter)&&(this.filter?o.push(this.filter.protocol.multicodec):Vs.error("Filter codec not included in dial codec: protocol not mounted locally")),Vs.info(`Dialing to ${n.toString()} with protocols ${r}`),this.libp2p.dialProtocol(n,o)}async start(){await this.libp2p.start()}async stop(){this.peerManager.stop(),this.connectionManager.stop(),await this.libp2p.stop()}async getPeers(){return this.connectionManager.getConnectedPeers()}async waitForPeers(e,t){return async function(e,t,r){t=t?.length?t:function(e){const t=[];return e.relay&&t.push(Vr.Relay),e.filter&&t.push(Vr.Filter),e.store&&t.push(Vr.Store),e.lightPush&&t.push(Vr.LightPush),t}(e);const n=e.libp2p.getConnections();if(!e.isStarted())throw Error("Waku node is not started");if(n.length>0&&!t.includes(Vr.Relay)){const r=await async function(e,t){const r=e.libp2p.getPeers(),n=e.libp2p.services.metadata,o=function(e){const t=new Map,r={[Vr.Filter]:po,[Vr.LightPush]:bo,[Vr.Store]:Co};for(const n of e)r[n]&&t.set(r[n],!1);return t}(t);if(!r.length||!n)return qs.info(`Skipping waitForMetadata due to missing connections:${r.length} or metadataService:${!!n}`),!1;for(const t of r)try{const r=await e.libp2p.peerStore.get(t);if(r.protocols.some((e=>o.has(e)))&&!(await n.confirmOrAttemptHandshake(t)).error&&(r.protocols.forEach((e=>{o.has(e)&&o.set(e,!0)})),Array.from(o.values()).every((e=>e))))return!0}catch(e){"ERR_CONNECTION_BEING_CLOSED"===e.code&&qs.error("Connection closed. Some peers can be on different shard."),qs.error(`Error while iterating through peers: ${e}`);continue}return!1}(e,t);if(r)return}const o=[];if(t.includes(Vr.Relay)){if(!e.relay)throw Error("Cannot wait for Relay peer: protocol not mounted");o.push(e.relay.waitForPeers())}if(t.includes(Vr.Store)){if(!e.store)throw Error("Cannot wait for Store peer: protocol not mounted");o.push(Hs(Co,e.libp2p))}if(t.includes(Vr.LightPush)){if(!e.lightPush)throw Error("Cannot wait for LightPush peer: protocol not mounted");o.push(Hs(bo,e.libp2p))}if(t.includes(Vr.Filter)){if(!e.filter)throw new Error("Cannot wait for Filter peer: protocol not mounted");o.push(Hs(po,e.libp2p))}r?await async function(e,t){await Promise.race([e,js(t,"Timed out waiting for a remote peer.")])}(Promise.all(o),r):await Promise.all(o)}(this,e,t)}isStarted(){return"started"==this.libp2p.status}isConnected(){return this.connectionManager.isConnected()}mapToPeerIdOrMultiaddr(e){return $o(e)?e:Is(e)}}class Ks extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Gs extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}}Error;class Ws extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}}class Js extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}}class Xs extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}}Error;class Ys extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}}class Zs extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}}class Qs extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}}class ei extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}}class ti extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}}class ri extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}}class ni extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}}class oi extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}}class si extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}}class ii extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}}class ai extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}}class ci extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}}class li extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}}class ui extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}}class hi extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}}class di extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}}Error;class pi extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}}Error;class fi extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}}class gi extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}}class mi extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}}class yi extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}const bi=BigInt(2**32-1),wi=BigInt(32);function vi(e,t=!1){return t?{h:Number(e&bi),l:Number(e>>wi&bi)}:{h:0|Number(e>>wi&bi),l:0|Number(e&bi)}}const Ei={fromBig:vi,split:function(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let o=0;oBigInt(e>>>0)<>>0),shrSH:(e,t,r)=>e>>>r,shrSL:(e,t,r)=>e<<32-r|t>>>r,rotrSH:(e,t,r)=>e>>>r|t<<32-r,rotrSL:(e,t,r)=>e<<32-r|t>>>r,rotrBH:(e,t,r)=>e<<64-r|t>>>r-32,rotrBL:(e,t,r)=>e>>>r-32|t<<64-r,rotr32H:(e,t)=>t,rotr32L:(e,t)=>e,rotlSH:(e,t,r)=>e<>>32-r,rotlSL:(e,t,r)=>t<>>32-r,rotlBH:(e,t,r)=>t<>>64-r,rotlBL:(e,t,r)=>e<>>64-r,add:function(e,t,r,n){const o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:0|o}},add3L:(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),add3H:(e,t,r,n)=>t+r+n+(e/2**32|0)|0,add4L:(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),add4H:(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,add5H:(e,t,r,n,o,s)=>t+r+n+o+s+(e/2**32|0)|0,add5L:(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0)},Si=Ei,[Ai,ki]=(()=>Si.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),Ci=new Uint32Array(80),Ii=new Uint32Array(80);class xi extends Mr{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:o,Cl:s,Dh:i,Dl:a,Eh:c,El:l,Fh:u,Fl:h,Gh:d,Gl:p,Hh:f,Hl:g}=this;return[e,t,r,n,o,s,i,a,c,l,u,h,d,p,f,g]}set(e,t,r,n,o,s,i,a,c,l,u,h,d,p,f,g){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|o,this.Cl=0|s,this.Dh=0|i,this.Dl=0|a,this.Eh=0|c,this.El=0|l,this.Fh=0|u,this.Fl=0|h,this.Gh=0|d,this.Gl=0|p,this.Hh=0|f,this.Hl=0|g}process(e,t){for(let r=0;r<16;r++,t+=4)Ci[r]=e.getUint32(t),Ii[r]=e.getUint32(t+=4);for(let e=16;e<80;e++){const t=0|Ci[e-15],r=0|Ii[e-15],n=Si.rotrSH(t,r,1)^Si.rotrSH(t,r,8)^Si.shrSH(t,r,7),o=Si.rotrSL(t,r,1)^Si.rotrSL(t,r,8)^Si.shrSL(t,r,7),s=0|Ci[e-2],i=0|Ii[e-2],a=Si.rotrSH(s,i,19)^Si.rotrBH(s,i,61)^Si.shrSH(s,i,6),c=Si.rotrSL(s,i,19)^Si.rotrBL(s,i,61)^Si.shrSL(s,i,6),l=Si.add4L(o,c,Ii[e-7],Ii[e-16]),u=Si.add4H(l,n,a,Ci[e-7],Ci[e-16]);Ci[e]=0|u,Ii[e]=0|l}let{Ah:r,Al:n,Bh:o,Bl:s,Ch:i,Cl:a,Dh:c,Dl:l,Eh:u,El:h,Fh:d,Fl:p,Gh:f,Gl:g,Hh:m,Hl:y}=this;for(let e=0;e<80;e++){const t=Si.rotrSH(u,h,14)^Si.rotrSH(u,h,18)^Si.rotrBH(u,h,41),b=Si.rotrSL(u,h,14)^Si.rotrSL(u,h,18)^Si.rotrBL(u,h,41),w=u&d^~u&f,v=h&p^~h&g,E=Si.add5L(y,b,v,ki[e],Ii[e]),S=Si.add5H(E,m,t,w,Ai[e],Ci[e]),A=0|E,k=Si.rotrSH(r,n,28)^Si.rotrBH(r,n,34)^Si.rotrBH(r,n,39),C=Si.rotrSL(r,n,28)^Si.rotrBL(r,n,34)^Si.rotrBL(r,n,39),I=r&o^r&i^o&i,x=n&s^n&a^s&a;m=0|f,y=0|g,f=0|d,g=0|p,d=0|u,p=0|h,({h:u,l:h}=Si.add(0|c,0|l,0|S,0|A)),c=0|i,l=0|a,i=0|o,a=0|s,o=0|r,s=0|n;const T=Si.add3L(A,C,x);r=Si.add3H(T,S,k,I),n=0|T}({h:r,l:n}=Si.add(0|this.Ah,0|this.Al,0|r,0|n)),({h:o,l:s}=Si.add(0|this.Bh,0|this.Bl,0|o,0|s)),({h:i,l:a}=Si.add(0|this.Ch,0|this.Cl,0|i,0|a)),({h:c,l}=Si.add(0|this.Dh,0|this.Dl,0|c,0|l)),({h:u,l:h}=Si.add(0|this.Eh,0|this.El,0|u,0|h)),({h:d,l:p}=Si.add(0|this.Fh,0|this.Fl,0|d,0|p)),({h:f,l:g}=Si.add(0|this.Gh,0|this.Gl,0|f,0|g)),({h:m,l:y}=Si.add(0|this.Hh,0|this.Hl,0|m,0|y)),this.set(r,n,o,s,i,a,c,l,u,h,d,p,f,g,m,y)}roundClean(){Ci.fill(0),Ii.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 Ti=Rr((()=>new xi)),_i=BigInt(0),Ni=BigInt(1),Pi=BigInt(2);function Li(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function Bi(e){if(!Li(e))throw new Error("Uint8Array expected")}function Oi(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}const Ri=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Di(e){Bi(e);let t="";for(let r=0;r=Fi._0&&e<=Fi._9?e-Fi._0:e>=Fi.A&&e<=Fi.F?e-(Fi.A-10):e>=Fi.a&&e<=Fi.f?e-(Fi.a-10):void 0}function qi(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("hex string expected, got unpadded hex of length "+t);const n=new Uint8Array(r);for(let t=0,o=0;t"bigint"==typeof e&&_i<=e;function Ji(e,t,r){return Wi(e)&&Wi(t)&&Wi(r)&&t<=e&&e_i;e>>=Ni,t+=1);return t}const Zi=e=>(Pi<new Uint8Array(e),ea=e=>Uint8Array.from(e);function ta(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=Qi(e),o=Qi(e),s=0;const i=()=>{n.fill(1),o.fill(0),s=0},a=(...e)=>r(o,n,...e),c=(e=Qi())=>{o=a(ea([0]),e),n=a(),0!==e.length&&(o=a(ea([1]),e),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let e=0;const r=[];for(;e{let r;for(i(),c(e);!(r=t(l()));)c();return i(),r}}const ra={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||Li(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 na(e,t,r={}){const n=(t,r,n)=>{const o=ra[r];if("function"!=typeof o)throw new Error("invalid validator function");const s=e[t];if(!(n&&void 0===s||o(s,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+s)};for(const[e,r]of Object.entries(t))n(e,r,!1);for(const[e,t]of Object.entries(r))n(e,t,!0);return e}function oa(e){const t=new WeakMap;return(r,...n)=>{const o=t.get(r);if(void 0!==o)return o;const s=e(r,...n);return t.set(r,s),s}}const sa=BigInt(0),ia=BigInt(1),aa=BigInt(2),ca=BigInt(3),la=BigInt(4),ua=BigInt(5),ha=BigInt(8);function da(e,t){const r=e%t;return r>=sa?r:t+r}function pa(e,t,r){if(tsa;)t&ia&&(n=n*e%r),e=e*e%r,t>>=ia;return n}function fa(e,t,r){let n=e;for(;t-- >sa;)n*=n,n%=r;return n}function ga(e,t){if(e===sa)throw new Error("invert: expected non-zero number");if(t<=sa)throw new Error("invert: expected positive modulus, got "+t);let r=da(e,t),n=t,o=sa,s=ia,i=ia,a=sa;for(;r!==sa;){const e=n/r,t=n%r,c=o-i*e,l=s-a*e;n=r,r=t,o=i,s=a,i=c,a=l}if(n!==ia)throw new Error("invert: does not exist");return da(o,t)}const ma=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ya(e,t){const r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function ba(e,t,r=!1,n={}){if(e<=sa)throw new Error("invalid field: expected ORDER > 0, got "+e);const{nBitLength:o,nByteLength:s}=ya(e,t);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let i;const a=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:s,MASK:Zi(o),ZERO:sa,ONE:ia,create:t=>da(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return sa<=t&&te===sa,isOdd:e=>(e&ia)===ia,neg:t=>da(-t,e),eql:(e,t)=>e===t,sqr:t=>da(t*t,e),add:(t,r)=>da(t+r,e),sub:(t,r)=>da(t-r,e),mul:(t,r)=>da(t*r,e),pow:(e,t)=>function(e,t,r){if(rsa;)r&ia&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ia;return n}(a,e,t),div:(t,r)=>da(t*ga(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>ga(t,e),sqrt:n.sqrt||(t=>(i||(i=function(e){if(e%la===ca){const t=(e+ia)/la;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%ha===ua){const t=(e-ua)/ha;return function(e,r){const n=e.mul(r,aa),o=e.pow(n,t),s=e.mul(r,o),i=e.mul(e.mul(s,aa),o),a=e.mul(s,e.sub(i,e.ONE));if(!e.eql(e.sqr(a),r))throw new Error("Cannot find square root");return a}}return function(e){const t=(e-ia)/aa;let r,n,o;for(r=e-ia,n=0;r%aa===sa;r/=aa,n++);for(o=aa;o1e3)throw new Error("Cannot find square root: likely non-prime P");if(1===n){const t=(e+ia)/la;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 s=(r+ia)/aa;return function(e,i){if(e.pow(i,t)===e.neg(e.ONE))throw new Error("Cannot find square root");let a=n,c=e.pow(e.mul(e.ONE,o),r),l=e.pow(i,s),u=e.pow(i,r);for(;!e.eql(u,e.ONE);){if(e.eql(u,e.ZERO))return e.ZERO;let t=1;for(let r=e.sqr(u);tfunction(e,t){const r=new Array(t.length),n=t.reduce(((t,n,o)=>e.is0(n)?t:(r[o]=t,e.mul(t,n))),e.ONE),o=e.inv(n);return t.reduceRight(((t,n,o)=>e.is0(n)?t:(r[o]=e.mul(t,r[o]),e.mul(t,n))),o),r}(a,e),cmov:(e,t,r)=>r?t:e,toBytes:e=>r?zi(e,s):Vi(e,s),fromBytes:e=>{if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);return r?ji(e):Hi(e)}});return Object.freeze(a)}function wa(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 va(e){const t=wa(e);return t+Math.ceil(t/2)}const Ea=BigInt(0),Sa=BigInt(1);function Aa(e,t){const r=t.negate();return e?r:t}function ka(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Ca(e,t){return ka(e,t),{windows:Math.ceil(t/e)+1,windowSize:2**(e-1)}}const Ia=new WeakMap,xa=new WeakMap;function Ta(e){return xa.get(e)||1}function _a(e,t){return{constTimeNegate:Aa,hasPrecomputes:e=>1!==Ta(e),unsafeLadder(t,r,n=e.ZERO){let o=t;for(;r>Ea;)r&Sa&&(n=n.add(o)),o=o.double(),r>>=Sa;return n},precomputeWindow(e,r){const{windows:n,windowSize:o}=Ca(r,t),s=[];let i=e,a=i;for(let e=0;e>=h,r>i&&(r-=u,o+=Sa);const s=t,d=t+Math.abs(r)-1,p=e%2!=0,f=r<0;0===r?c=c.add(Aa(p,n[s])):a=a.add(Aa(f,n[d]))}return{p:a,f:c}},wNAFUnsafe(r,n,o,s=e.ZERO){const{windows:i,windowSize:a}=Ca(r,t),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let e=0;e>=u,r>a&&(r-=l,o+=Sa),0===r)continue;let i=n[t+Math.abs(r)-1];r<0&&(i=i.negate()),s=s.add(i)}return s},getPrecomputes(e,t,r){let n=Ia.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&Ia.set(t,r(n))),n},wNAFCached(e,t,r){const n=Ta(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){const o=Ta(e);return 1===o?this.unsafeLadder(e,t,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,r),t,n)},setWindowSize(e,r){ka(r,t),xa.set(e,r),Ia.delete(e)}}}function Na(e,t,r,n){if(function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)}))}(n,t),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,s=Yi(BigInt(r.length)),i=s>12?s-3:s>4?s-2:s?2:1,a=(1<=0;e-=i){c.fill(o);for(let t=0;t>BigInt(e)&BigInt(a));c[s]=c[s].add(r[t])}let t=o;for(let e=c.length-1,r=o;e>0;e--)r=r.add(c[e]),t=t.add(r);if(l=l.add(t),0!==e)for(let e=0;e(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"});na(e,t)}(e.Fp),na(e,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ya(e.n,e.nBitLength),...e,p:e.Fp.ORDER})}const La=BigInt(0),Ba=BigInt(1),Oa=BigInt(2),Ra=BigInt(8),Da={zip215:!0};const Ua=BigInt(0),Ma=BigInt(1);const Fa=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),$a=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),qa=(BigInt(0),BigInt(1)),Ha=BigInt(2),ja=BigInt(3),Va=BigInt(5),za=BigInt(8);function Ka(e){const t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Fa,i=e*e%s*e%s,a=fa(i,Ha,s)*i%s,c=fa(a,qa,s)*e%s,l=fa(c,Va,s)*c%s,u=fa(l,t,s)*l%s,h=fa(u,r,s)*u%s,d=fa(h,n,s)*h%s,p=fa(d,o,s)*d%s,f=fa(p,o,s)*d%s,g=fa(f,t,s)*l%s;return{pow_p_5_8:fa(g,Ha,s)*e%s,b2:i}}function Ga(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function Wa(e,t){const r=Fa,n=da(t*t*t,r),o=da(n*n*t,r);let s=da(e*n*Ka(e*o).pow_p_5_8,r);const i=da(t*s*s,r),a=s,c=da(s*$a,r),l=i===e,u=i===da(-e,r),h=i===da(-e*$a,r);return l&&(s=a),(u||h)&&(s=c),(da(s,r)&ia)===ia&&(s=da(-s,r)),{isValid:l||u,value:s}}const Ja=(()=>ba(Fa,void 0,!0))(),Xa=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ja,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:za,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ti,randomBytes:Dr,adjustScalarBytes:Ga,uvRatio:Wa}))(),Ya=(()=>function(e){const t=function(e){const t=Pa(e);return na(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:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=Oa<{try{return{isValid:!0,value:r.sqrt(e*r.inv(t))}}catch(e){return{isValid:!1,value:La}}}),p=t.adjustScalarBytes||(e=>e),f=t.domain||((e,t,r)=>{if(Oi("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function g(e,t){Xi("coordinate "+e,t,La,l)}function m(e){if(!(e instanceof w))throw new Error("ExtendedPoint expected")}const y=oa(((e,t)=>{const{ex:n,ey:o,ez:s}=e,i=e.is0();null==t&&(t=i?Ra:r.inv(s));const a=u(n*t),c=u(o*t),l=u(s*t);if(i)return{x:La,y:Ba};if(l!==Ba)throw new Error("invZ was invalid");return{x:a,y:c}})),b=oa((e=>{const{a:r,d:n}=t;if(e.is0())throw new Error("bad point: ZERO");const{ex:o,ey:s,ez:i,et:a}=e,c=u(o*o),l=u(s*s),h=u(i*i),d=u(h*h),p=u(c*r);if(u(h*u(p+l))!==u(d+u(n*u(c*l))))throw new Error("bad point: equation left != right (1)");if(u(o*s)!==u(i*a))throw new Error("bad point: equation left != right (2)");return!0}));class w{constructor(e,t,r,n){this.ex=e,this.ey=t,this.ez=r,this.et=n,g("x",e),g("y",t),g("z",r),g("t",n),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof w)throw new Error("extended point not allowed");const{x:t,y:r}=e||{};return g("x",t),g("y",r),new w(t,r,Ba,u(t*r))}static normalizeZ(e){const t=r.invertBatch(e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(w.fromAffine)}static msm(e,t){return Na(w,h,e,t)}_setWindowSize(e){S.setWindowSize(this,e)}assertValidity(){b(this)}equals(e){m(e);const{ex:t,ey:r,ez:n}=this,{ex:o,ey:s,ez:i}=e,a=u(t*i),c=u(o*n),l=u(r*i),h=u(s*n);return a===c&&l===h}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:e}=t,{ex:r,ey:n,ez:o}=this,s=u(r*r),i=u(n*n),a=u(Oa*u(o*o)),c=u(e*s),l=r+n,h=u(u(l*l)-s-i),d=c+i,p=d-a,f=c-i,g=u(h*p),m=u(d*f),y=u(h*f),b=u(p*d);return new w(g,m,b,y)}add(e){m(e);const{a:r,d:n}=t,{ex:o,ey:s,ez:i,et:a}=this,{ex:c,ey:l,ez:h,et:d}=e;if(r===BigInt(-1)){const e=u((s-o)*(l+c)),t=u((s+o)*(l-c)),r=u(t-e);if(r===La)return this.double();const n=u(i*Oa*d),p=u(a*Oa*h),f=p+n,g=t+e,m=p-n,y=u(f*r),b=u(g*m),v=u(f*m),E=u(r*g);return new w(y,b,E,v)}const p=u(o*c),f=u(s*l),g=u(a*n*d),y=u(i*h),b=u((o+s)*(c+l)-p-f),v=y-g,E=y+g,S=u(f-r*p),A=u(b*v),k=u(E*S),C=u(b*S),I=u(v*E);return new w(A,k,I,C)}subtract(e){return this.add(e.negate())}wNAF(e){return S.wNAFCached(this,e,w.normalizeZ)}multiply(e){const t=e;Xi("scalar",t,Ba,n);const{p:r,f:o}=this.wNAF(t);return w.normalizeZ([r,o])[0]}multiplyUnsafe(e,t=w.ZERO){const r=e;return Xi("scalar",r,La,n),r===La?E:this.is0()||r===Ba?this:S.wNAFCachedUnsafe(this,r,w.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return S.unsafeLadder(this,n).is0()}toAffine(e){return y(this,e)}clearCofactor(){const{h:e}=t;return e===Ba?this:this.multiplyUnsafe(e)}static fromHex(e,n=!1){const{d:o,a:s}=t,i=r.BYTES;e=Ki("pointHex",e,i),Oi("zip215",n);const a=e.slice(),c=e[i-1];a[i-1]=-129&c;const h=ji(a),p=n?l:r.ORDER;Xi("pointHex.y",h,La,p);const f=u(h*h),g=u(f-Ba),m=u(o*f-s);let{isValid:y,value:b}=d(g,m);if(!y)throw new Error("Point.fromHex: invalid y coordinate");const v=(b&Ba)===Ba,E=!!(128&c);if(!n&&b===La&&E)throw new Error("Point.fromHex: x=0 and x_0=1");return E!==v&&(b=u(-b)),w.fromAffine({x:b,y:h})}static fromPrivateKey(e){return C(e).point}toRawBytes(){const{x:e,y:t}=this.toAffine(),n=zi(t,r.BYTES);return n[n.length-1]|=e&Ba?128:0,n}toHex(){return Di(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Ba,u(t.Gx*t.Gy)),w.ZERO=new w(La,Ba,Ba,La);const{BASE:v,ZERO:E}=w,S=_a(w,8*a);function A(e){return da(e,n)}function k(e){return A(ji(e))}function C(e){const t=r.BYTES;e=Ki("private key",e,t);const n=Ki("hashed private key",s(e),2*t),o=p(n.slice(0,t)),i=n.slice(t,2*t),a=k(o),c=v.multiply(a),l=c.toRawBytes();return{head:o,prefix:i,scalar:a,point:c,pointBytes:l}}function I(e=new Uint8Array,...t){const r=Gi(...t);return k(s(f(r,Ki("context",e),!!o)))}const x=Da;return v._setWindowSize(8),{CURVE:t,getPublicKey:function(e){return C(e).pointBytes},sign:function(e,t,s={}){e=Ki("message",e),o&&(e=o(e));const{prefix:i,scalar:a,pointBytes:c}=C(t),l=I(s.context,i,e),u=v.multiply(l).toRawBytes(),h=A(l+I(s.context,u,c,e)*a);return Xi("signature.s",h,La,n),Ki("result",Gi(u,zi(h,r.BYTES)),2*r.BYTES)},verify:function(e,t,n,s=x){const{context:i,zip215:a}=s,c=r.BYTES;e=Ki("signature",e,2*c),t=Ki("message",t),n=Ki("publicKey",n,c),void 0!==a&&Oi("zip215",a),o&&(t=o(t));const l=ji(e.slice(c,2*c));let u,h,d;try{u=w.fromHex(n,a),h=w.fromHex(e.slice(0,c),a),d=v.multiplyUnsafe(l)}catch(e){return!1}if(!a&&u.isSmallOrder())return!1;const p=I(i,h.toRawBytes(),u.toRawBytes(),t);return h.add(u.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(w.ZERO)},ExtendedPoint:w,utils:{getExtendedPublicKey:C,randomPrivateKey:()=>i(r.BYTES),precompute:(e=8,t=w.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)}}}(Xa))(),Za=(()=>function(e){const t=(na(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,o=e=>da(e,n),s=t.montgomeryBits,i=Math.ceil(s/8),a=t.nByteLength,c=t.adjustScalarBytes||(e=>e),l=t.powPminus2||(e=>pa(e,n-BigInt(2),n));function u(e,t,r){const n=o(e*(t-r));return[t=o(t-n),r=o(r+n)]}const h=(t.a-BigInt(2))/BigInt(4);function d(e){return zi(o(e),i)}function p(e,t){const r=function(e){const t=Ki("u coordinate",e,i);return 32===a&&(t[31]&=127),ji(t)}(t),p=function(e){const t=Ki("scalar",e),r=t.length;if(r!==i&&r!==a)throw new Error("invalid scalar, expected "+i+" or "+a+" bytes, got "+r);return ji(c(t))}(e),f=function(e,t){Xi("u",e,Ua,n),Xi("scalar",t,Ua,n);const r=t,i=e;let a,c=Ma,d=Ua,p=e,f=Ma,g=Ua;for(let e=BigInt(s-1);e>=Ua;e--){const t=r>>e&Ma;g^=t,a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1],g=t;const n=c+d,s=o(n*n),l=c-d,m=o(l*l),y=s-m,b=p+f,w=o((p-f)*n),v=o(b*l),E=w+v,S=w-v;p=o(E*E),f=o(i*o(S*S)),c=o(s*m),d=o(y*(s+o(h*y)))}a=u(g,c,p),c=a[0],p=a[1],a=u(g,d,f),d=a[0],f=a[1];const m=l(d);return o(c*m)}(r,p);if(f===Ua)throw new Error("invalid private or public key received");return d(f)}const f=d(t.Gu);function g(e){return p(e,f)}return{scalarMult:p,scalarMultBase:g,getSharedSecret:(e,t)=>p(e,t),getPublicKey:e=>g(e),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:f}}({P:Fa,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:e=>{const t=Fa,{pow_p_5_8:r,b2:n}=Ka(e);return da(fa(r,ja,t)*n,t)},adjustScalarBytes:Ga,randomBytes:Dr}))();function Qa(e,t){const r=new Uint8Array(64);for(let n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}class ec{type="Ed25519";raw;constructor(e){this.raw=nc(e,32)}toMultihash(){return ct.digest(Wu(this))}toCID(){return yt.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}verify(e,t){return function(e,t,r){return Ya.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this.raw,t,e)}}class tc{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=nc(e,64),this.publicKey=new ec(t)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}sign(e){return function(e,t){const r=e.subarray(0,32);return Ya.sign(t instanceof Uint8Array?t:t.subarray(),r)}(this.raw,e)}}function rc(e){return e=nc(e,32),new ec(e)}function nc(e,t){if((e=Uint8Array.from(e??[])).length!==t)throw new Ws(`Key must be a Uint8Array of length ${t}, got ${e.length}`);return e}var oc,sc,ic,ac;!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1"}(oc||(oc={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1"}(sc||(sc={})),function(e){e.codec=()=>wr(sc)}(oc||(oc={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),oc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.Type=oc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ic||(ic={})),function(e){let t;e.codec=()=>(null==t&&(t=vr(((e,t,r={})=>{!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),oc.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.Type=oc.codec().decode(e);break;case 2:n.Data=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(ac||(ac={}));var cc=__webpack_require__(152);function lc(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 uc(e,t,r=-1){const n=r;let o=e,s=0,i=Math.pow(2,t);for(let r=1;r<8;r++){if(e=0;e--){const r=Math.pow(2,e*t);i[s-e-1]=Math.floor(o/r),o-=i[s-e-1]*r}return e}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function hc(...e){let t=0,r=0;for(const r of e)t+=r.length;const n=new ArrayBuffer(t),o=new Uint8Array(n);for(const t of e)o.set(t,r),r+=t.length;return o}function dc(){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=o.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;r8)return this.error="Too big integer",-1;if(s+1>o.length)return this.error="End of input reached before message was fully decoded",-1;const i=t+1,a=n.subarray(i,i+s);return 0===a[s-1]&&this.warnings.push("Needlessly long encoded length"),this.length=lc(a,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=s+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=uc(this.length,8);if(n.byteLength>127)return this.error="Too big length",vc;if(t=new ArrayBuffer(n.byteLength+1),e)return t;const o=new Uint8Array(n);r=new Uint8Array(t),r[0]=128|n.byteLength;for(let e=0;e=37&&!1===o.idBlock.isHexOnly)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};a=Nc.EndOfContent;break;case 1:a=Nc.Boolean;break;case 2:a=Nc.Integer;break;case 3:a=Nc.BitString;break;case 4:a=Nc.OctetString;break;case 5:a=Nc.Null;break;case 6:a=Nc.ObjectIdentifier;break;case 10:a=Nc.Enumerated;break;case 12:a=Nc.Utf8String;break;case 13:a=Nc.RelativeObjectIdentifier;break;case 14:a=Nc.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:a=Nc.Sequence;break;case 17:a=Nc.Set;break;case 18:a=Nc.NumericString;break;case 19:a=Nc.PrintableString;break;case 20:a=Nc.TeletexString;break;case 21:a=Nc.VideotexString;break;case 22:a=Nc.IA5String;break;case 23:a=Nc.UTCTime;break;case 24:a=Nc.GeneralizedTime;break;case 25:a=Nc.GraphicString;break;case 26:a=Nc.VisibleString;break;case 27:a=Nc.GeneralString;break;case 28:a=Nc.UniversalString;break;case 29:a=Nc.CharacterString;break;case 30:a=Nc.BmpString;break;case 31:a=Nc.DATE;break;case 32:a=Nc.TimeOfDay;break;case 33:a=Nc.DateTime;break;case 34:a=Nc.Duration;break;default:{const e=o.idBlock.isConstructed?new Nc.Constructed:new Nc.Primitive;e.idBlock=o.idBlock,e.lenBlock=o.lenBlock,e.warnings=o.warnings,o=e}}}else a=o.idBlock.isConstructed?Nc.Constructed:Nc.Primitive;return o=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}(o,a),i=o.fromBER(e,t,o.lenBlock.isIndefiniteForm?r:o.lenBlock.length),o.valueBeforeDecodeView=e.subarray(n,n+o.blockLength),{offset:i,result:o}}Rc=fl,Nc.Primitive=Rc,fl.NAME="PRIMITIVE";class ml extends xc{constructor({value:e=[],isIndefiniteForm:t=!1,...r}={}){super(r),this.value=e,this.isIndefiniteForm=t}fromBER(e,t,r){const n=cc._H.toUint8Array(e);if(!mc(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 o=t;for(;(this.isIndefiniteForm?1:r)>0;){const e=gl(n,o,r);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(o=e.offset,this.blockLength+=e.result.blockLength,r-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===Sc)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Sc?this.value.pop():this.warnings.push("No EndOfContent block encoded")),o}toBER(e,t){const r=t||new yc;for(let t=0;t` ${e}`)).join("\n"));const t=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${t} :\n${e.join("\n")}`:`${t} :`}}Dc=yl,Nc.Constructed=Dc,yl.NAME="CONSTRUCTED";class bl extends xc{fromBER(e,t,r){return t}toBER(e){return vc}}bl.override="EndOfContentValueBlock";class wl extends Pc{constructor(e={}){super(e,bl),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}Uc=wl,Nc.EndOfContent=Uc,wl.NAME=Sc;class vl extends Pc{constructor(e={}){super(e,xc),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}`}}Mc=vl,Nc.Null=Mc,vl.NAME="NULL";class El extends(Cc(xc)){constructor({value:e,...t}={}){super(t),t.valueHex?this.valueHexView=cc._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=cc._H.toUint8Array(e);return mc(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,dc.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}El.NAME="BooleanValueBlock";class Sl extends Pc{constructor(e={}){super(e,El),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}`}}Fc=Sl,Nc.Boolean=Fc,Sl.NAME="BOOLEAN";class Al extends(Cc(ml)){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=ml.prototype.fromBER.call(this,e,t,r),-1===n)return n;for(let e=0;e0&&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 o=cc._H.toUint8Array(e);if(!mc(this,o,t,r))return-1;const s=o.subarray(t,t+r);if(this.unusedBits=s[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){const e=s.subarray(1);try{if(e.byteLength){const t=gl(e,0,e.byteLength);-1!==t.offset&&t.offset===r-1&&(this.value=[t.result])}}catch(e){}}return this.valueHexView=s.subarray(1),this.blockLength=s.length,t+r}toBER(e,t){if(this.isConstructed)return ml.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return vc;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}}}Cl.NAME="BitStringValueBlock";class Il extends Pc{constructor({idBlock:e={},lenBlock:t={},...r}={}){var n,o;null!==(n=r.isConstructed)&&void 0!==n||(r.isConstructed=!!(null===(o=r.value)||void 0===o?void 0:o.length)),super({idBlock:{isConstructed:r.isConstructed,...e},lenBlock:{...t,isIndefiniteForm:!!r.isIndefiniteForm},...r},Cl),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 yl.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 xl(e,t){const r=new Uint8Array([0]),n=new Uint8Array(e),o=new Uint8Array(t);let s=n.slice(0);const i=s.length-1,a=o.slice(0),c=a.length-1;let l=0,u=0;for(let e=c=0;e--,u++)l=1==u=s.length?s=hc(new Uint8Array([l%10]),s):s[i-u]=l%10;return r[0]>0&&(s=hc(r,s)),s}function Tl(e){if(e>=bc.length)for(let t=bc.length;t<=e;t++){const e=new Uint8Array([0]);let r=bc[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=hc(e,r)),bc.push(r)}return bc[e]}function _l(e,t){let r=0;const n=new Uint8Array(e),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1;let l,u=0;for(let e=c;e>=0;e--,u++)l=s[i-u]-a[c-u]-r,1==l<0?(r=1,s[i-u]=l+10):(r=0,s[i-u]=l);if(r>0)for(let e=i-c+1;e>=0;e--,u++){if(l=s[i-u]-r,!(l<0)){r=0,s[i-u]=l;break}r=1,s[i-u]=l+10}return s.slice()}qc=Il,Nc.BitString=qc,Il.NAME=kc;class Nl extends(Cc(xc)){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=dc.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=uc(r-t,8,n);return new Uint8Array(e)[0]|=128,e}let o=uc(t,8,n),s=new Uint8Array(o);if(128&s[0]){const e=o.slice(0),t=new Uint8Array(e);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let r=0;r1&&(n=s.length+1),this.valueHexView=s.subarray(n-s.length)),o}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 o=this.valueHexView;let s="",i=!1;for(let i=o.byteLength-1;i>=0;i--){t=o[i];for(let o=0;o<8;o++)1&~t||(n===e?(r=_l(Tl(n),r),s="-"):r=xl(r,Tl(n))),n++,t>>=1}for(let e=0;e0;){const t=new Bl;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;rNumber.MAX_SAFE_INTEGER){fc();const t=BigInt(n);e.valueBigInt=t}else if(e.valueDec=parseInt(n,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,o=!0),this.value.push(e)}}while(-1!==r)}toString(){let e="",t=!1;for(let r=0;r0;){const t=new Dl;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;t4)continue;const s=4-o.length;for(let e=o.length-1;e>=0;e--)r[4*n+e+s]=o[e]}this.valueBlock.value=e}}Wl.NAME="UniversalStringValueBlock";class Jl extends Wl{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}Yc=Jl,Nc.UniversalString=Yc,Jl.NAME="UniversalString";class Xl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}Zc=Xl,Nc.NumericString=Zc,Xl.NAME="NumericString";class Yl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}Qc=Yl,Nc.PrintableString=Qc,Yl.NAME="PrintableString";class Zl extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}el=Zl,Nc.TeletexString=el,Zl.NAME="TeletexString";class Ql extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}tl=Ql,Nc.VideotexString=tl,Ql.NAME="VideotexString";class eu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}rl=eu,Nc.IA5String=rl,eu.NAME="IA5String";class tu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}nl=tu,Nc.GraphicString=nl,tu.NAME="GraphicString";class ru extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}ol=ru,Nc.VisibleString=ol,ru.NAME="VisibleString";class nu extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}sl=nu,Nc.GeneralString=sl,nu.NAME="GeneralString";class ou extends jl{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}il=ou,Nc.CharacterString=il,ou.NAME="CharacterString";class su extends ru{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=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]=pc(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=pc(this.month,2),e[2]=pc(this.day,2),e[3]=pc(this.hour,2),e[4]=pc(this.minute,2),e[5]=pc(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}}}al=su,Nc.UTCTime=al,su.NAME="UTCTime";class iu extends su{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="",o="",s=0,i=0,a=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{const t=new Number(e[e.length-1]);if(isNaN(t.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{let e=1,t=n.indexOf("+"),r="";if(-1===t&&(t=n.indexOf("-"),e=-1),-1!==t){if(r=n.substring(t+1),n=n.substring(0,t),2!==r.length&&4!==r.length)throw new Error("Wrong input string for conversion");let o=parseInt(r.substring(0,2),10);if(isNaN(o.valueOf()))throw new Error("Wrong input string for conversion");if(i=e*o,4===r.length){if(o=parseInt(r.substring(2,4),10),isNaN(o.valueOf()))throw new Error("Wrong input string for conversion");a=e*o}}}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");s=e.valueOf(),o=n.substring(0,c)}else o=n;switch(!0){case 8===o.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==c)throw new Error("Wrong input string for conversion");break;case 10===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*s;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===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){let e=60*s;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===o.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==c){const e=1e3*s;this.millisecond=Math.floor(e)}break;default:throw new Error("Wrong input string for conversion")}const l=t.exec(o);if(null===l)throw new Error("Wrong input string for conversion");for(let e=1;e0&&(r=`0${r}`),t.push(r)})),BigInt("0x"+t.join(""))}function Eu(e){const t=function(e){const{result:t}=function(e){if(!e.byteLength){const e=new Pc({},xc);return e.error="Input buffer has zero length",{offset:-1,result:e}}return gl(cc._H.toUint8Array(e).slice(),0,e.byteLength)}(e),r=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:wu(r[0]),e:wu(r[1])}}(e);if(function(e){if("RSA"!==e.kty)throw new Ws("invalid key type");if(null==e.n)throw new Ws("invalid key modulus");return 8*xt(e.n,"base64url").length}(t)>8192)throw new Js("Key size is too large");const r=ot(18,jr(ic.encode({Type:oc.RSA,Data:e})));return new mu(t,r)}class Su extends Or{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Tr(e);const r=Br(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,o=new Uint8Array(n);o.set(r.length>n?e.create().update(r).digest():r);for(let e=0;enew Su(e,t).update(r).digest();function ku(e){void 0!==e.lowS&&Oi("lowS",e.lowS),void 0!==e.prehash&&Oi("prehash",e.prehash)}Au.create=(e,t)=>new Su(e,t);const{Ph:Cu,aT:Iu}=f;class xu extends Error{constructor(e=""){super(e)}}const Tu={Err:xu,_tlv:{encode:(e,t)=>{const{Err:r}=Tu;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");const n=t.length/2,o=Ui(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Ui(o.length/2|128):"";return Ui(e)+s+o+t},decode(e,t){const{Err:r}=Tu;let n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");const o=t[n++];let s=0;if(128&o){const e=127&o;if(!e)throw new r("tlv.decode(long): indefinite length not supported");if(e>4)throw new r("tlv.decode(long): byte length is too big");const i=t.subarray(n,n+e);if(i.length!==e)throw new r("tlv.decode: length bytes not complete");if(0===i[0])throw new r("tlv.decode(long): zero leftmost byte");for(const e of i)s=s<<8|e;if(n+=e,s<128)throw new r("tlv.decode(long): not minimal encoding")}else s=o;const i=t.subarray(n,n+s);if(i.length!==s)throw new r("tlv.decode: wrong value length");return{v:i,l:t.subarray(n+s)}}},_int:{encode(e){const{Err:t}=Tu;if(e<_u)throw new t("integer: negative integers are not allowed");let r=Ui(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){const{Err:t}=Tu;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Cu(e)}},toSig(e){const{Err:t,_int:r,_tlv:n}=Tu,o="string"==typeof e?Iu(e):e;Bi(o);const{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(e){const{_tlv:t,_int:r}=Tu,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}},_u=BigInt(0),Nu=BigInt(1),Pu=(BigInt(2),BigInt(3));function Lu(e){const t=function(e){const t=Pa(e);return na(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}(e),{Fp:r,n}=t,o=r.BYTES+1,s=2*r.BYTES+1;function i(e){return da(e,n)}function a(e){return ga(e,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:h}=function(e){const t=function(e){const t=Pa(e);na(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:o}=t;if(r){if(!n.eql(o,n.ZERO))throw new Error("invalid 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("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...t})}(e),{Fp:r}=t,n=ba(t.n,t.nBitLength),o=t.toBytes||((e,t,n)=>{const o=t.toAffine();return Gi(Uint8Array.from([4]),r.toBytes(o.x),r.toBytes(o.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:o}=t,s=r.sqr(e),i=r.mul(s,e);return r.add(r.add(i,r.mul(e,n)),o)}if(!r.eql(r.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(e){const{allowedPrivateKeyLengths:r,nByteLength:n,wrapPrivateKey:o,n:s}=t;if(r&&"bigint"!=typeof e){if(Li(e)&&(e=Di(e)),"string"!=typeof e||!r.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*n,"0")}let i;try{i="bigint"==typeof e?e:Hi(Ki("private key",e,n))}catch(t){throw new Error("invalid private key, expected hex or "+n+" bytes, got "+typeof e)}return o&&(i=da(i,s)),Xi("private key",i,Nu,s),i}function c(e){if(!(e instanceof h))throw new Error("ProjectivePoint expected")}const l=oa(((e,t)=>{const{px:n,py:o,pz:s}=e;if(r.eql(s,r.ONE))return{x:n,y:o};const i=e.is0();null==t&&(t=i?r.ONE:r.inv(s));const a=r.mul(n,t),c=r.mul(o,t),l=r.mul(s,t);if(i)return{x:r.ZERO,y:r.ZERO};if(!r.eql(l,r.ONE))throw new Error("invZ was invalid");return{x:a,y:c}})),u=oa((e=>{if(e.is0()){if(t.allowInfinityPoint&&!r.is0(e.py))return;throw new Error("bad point: ZERO")}const{x:n,y:o}=e.toAffine();if(!r.isValid(n)||!r.isValid(o))throw new Error("bad point: x or y not FE");const s=r.sqr(o),a=i(n);if(!r.eql(s,a))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class h{constructor(e,t,n){if(this.px=e,this.py=t,this.pz=n,null==e||!r.isValid(e))throw new Error("x required");if(null==t||!r.isValid(t))throw new Error("y required");if(null==n||!r.isValid(n))throw new Error("z required");Object.freeze(this)}static fromAffine(e){const{x:t,y:n}=e||{};if(!e||!r.isValid(t)||!r.isValid(n))throw new Error("invalid affine point");if(e instanceof h)throw new Error("projective point not allowed");const o=e=>r.eql(e,r.ZERO);return o(t)&&o(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(Ki("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return h.BASE.multiply(a(e))}static msm(e,t){return Na(h,n,e,t)}_setWindowSize(e){p.setWindowSize(this,e)}assertValidity(){u(this)}hasEvenY(){const{y:e}=this.toAffine();if(r.isOdd)return!r.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){c(e);const{px:t,py:n,pz:o}=this,{px:s,py:i,pz:a}=e,l=r.eql(r.mul(t,a),r.mul(s,o)),u=r.eql(r.mul(n,a),r.mul(i,o));return l&&u}negate(){return new h(this.px,r.neg(this.py),this.pz)}double(){const{a:e,b:n}=t,o=r.mul(n,Pu),{px:s,py:i,pz:a}=this;let c=r.ZERO,l=r.ZERO,u=r.ZERO,d=r.mul(s,s),p=r.mul(i,i),f=r.mul(a,a),g=r.mul(s,i);return g=r.add(g,g),u=r.mul(s,a),u=r.add(u,u),c=r.mul(e,u),l=r.mul(o,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(o,u),f=r.mul(e,f),g=r.sub(d,f),g=r.mul(e,g),g=r.add(g,u),u=r.add(d,d),d=r.add(u,d),d=r.add(d,f),d=r.mul(d,g),l=r.add(l,d),f=r.mul(i,a),f=r.add(f,f),d=r.mul(f,g),c=r.sub(c,d),u=r.mul(f,p),u=r.add(u,u),u=r.add(u,u),new h(c,l,u)}add(e){c(e);const{px:n,py:o,pz:s}=this,{px:i,py:a,pz:l}=e;let u=r.ZERO,d=r.ZERO,p=r.ZERO;const f=t.a,g=r.mul(t.b,Pu);let m=r.mul(n,i),y=r.mul(o,a),b=r.mul(s,l),w=r.add(n,o),v=r.add(i,a);w=r.mul(w,v),v=r.add(m,y),w=r.sub(w,v),v=r.add(n,s);let E=r.add(i,l);return v=r.mul(v,E),E=r.add(m,b),v=r.sub(v,E),E=r.add(o,s),u=r.add(a,l),E=r.mul(E,u),u=r.add(y,b),E=r.sub(E,u),p=r.mul(f,v),u=r.mul(g,b),p=r.add(u,p),u=r.sub(y,p),p=r.add(y,p),d=r.mul(u,p),y=r.add(m,m),y=r.add(y,m),b=r.mul(f,b),v=r.mul(g,v),y=r.add(y,b),b=r.sub(m,b),b=r.mul(f,b),v=r.add(v,b),m=r.mul(y,v),d=r.add(d,m),m=r.mul(E,v),u=r.mul(w,u),u=r.sub(u,m),m=r.mul(w,y),p=r.mul(E,p),p=r.add(p,m),new h(u,d,p)}subtract(e){return this.add(e.negate())}is0(){return this.equals(h.ZERO)}wNAF(e){return p.wNAFCached(this,e,h.normalizeZ)}multiplyUnsafe(e){const{endo:n,n:o}=t;Xi("scalar",e,_u,o);const s=h.ZERO;if(e===_u)return s;if(this.is0()||e===Nu)return this;if(!n||p.hasPrecomputes(this))return p.wNAFCachedUnsafe(this,e,h.normalizeZ);let{k1neg:i,k1:a,k2neg:c,k2:l}=n.splitScalar(e),u=s,d=s,f=this;for(;a>_u||l>_u;)a&Nu&&(u=u.add(f)),l&Nu&&(d=d.add(f)),f=f.double(),a>>=Nu,l>>=Nu;return i&&(u=u.negate()),c&&(d=d.negate()),d=new h(r.mul(d.px,n.beta),d.py,d.pz),u.add(d)}multiply(e){const{endo:n,n:o}=t;let s,i;if(Xi("scalar",e,Nu,o),n){const{k1neg:t,k1:o,k2neg:a,k2:c}=n.splitScalar(e);let{p:l,f:u}=this.wNAF(o),{p:d,f}=this.wNAF(c);l=p.constTimeNegate(t,l),d=p.constTimeNegate(a,d),d=new h(r.mul(d.px,n.beta),d.py,d.pz),s=l.add(d),i=u.add(f)}else{const{p:t,f:r}=this.wNAF(e);s=t,i=r}return h.normalizeZ([s,i])[0]}multiplyAndAddUnsafe(e,t,r){const n=h.BASE,o=(e,t)=>t!==_u&&t!==Nu&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),s=o(this,t).add(o(e,r));return s.is0()?void 0:s}toAffine(e){return l(this,e)}isTorsionFree(){const{h:e,isTorsionFree:r}=t;if(e===Nu)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===Nu?this:r?r(h,this):this.multiplyUnsafe(t.h)}toRawBytes(e=!0){return Oi("isCompressed",e),this.assertValidity(),o(h,this,e)}toHex(e=!0){return Oi("isCompressed",e),Di(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=_a(h,t.endo?Math.ceil(d/2):d);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:a,weierstrassEquation:i,isWithinCurveOrder:function(e){return Ji(e,Nu,t.n)}}}({...t,toBytes(e,t,n){const o=t.toAffine(),s=r.toBytes(o.x),i=Gi;return Oi("isCompressed",n),n?i(Uint8Array.from([t.hasEvenY()?2:3]),s):i(Uint8Array.from([4]),s,r.toBytes(o.y))},fromBytes(e){const t=e.length,n=e[0],i=e.subarray(1);if(t!==o||2!==n&&3!==n){if(t===s&&4===n)return{x:r.fromBytes(i.subarray(0,r.BYTES)),y:r.fromBytes(i.subarray(r.BYTES,2*r.BYTES))};throw new Error("invalid Point, expected length of "+o+", or uncompressed "+s+", got "+t)}{const e=Hi(i);if(!Ji(e,Nu,r.ORDER))throw new Error("Point is not on curve");const t=u(e);let o;try{o=r.sqrt(t)}catch(e){const t=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+t)}return!(1&~n)!=((o&Nu)===Nu)&&(o=r.neg(o)),{x:e,y:o}}}}),d=e=>Di(Vi(e,t.nByteLength));function p(e){return e>n>>Nu}const f=(e,t,r)=>Hi(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=Ki("compactSignature",e,2*r),new g(f(e,0,r),f(e,r,2*r))}static fromDER(e){const{r:t,s:r}=Tu.toSig(Ki("DER",e));return new g(t,r)}assertValidity(){Xi("r",this.r,Nu,n),Xi("s",this.s,Nu,n)}addRecoveryBit(e){return new g(this.r,this.s,e)}recoverPublicKey(e){const{r:n,s:o,recovery:s}=this,l=w(Ki("msgHash",e));if(null==s||![0,1,2,3].includes(s))throw new Error("recovery id invalid");const u=2===s||3===s?n+t.n:n;if(u>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&s?"03":"02",p=c.fromHex(h+d(u)),f=a(u),g=i(-l*f),m=i(o*f),y=c.BASE.multiplyAndAddUnsafe(p,g,m);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return qi(this.toDERHex())}toDERHex(){return Tu.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return qi(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const m={isValidPrivateKey(e){try{return l(e),!0}catch(e){return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const e=va(t.n);return function(e,t,r=!1){const n=e.length,o=wa(t),s=va(t);if(n<16||n1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const i=da(r?ji(e):Hi(e),t-ia)+ia;return r?zi(i,o):Vi(i,o)}(t.randomBytes(e),t.n)},precompute:(e=8,t=c.BASE)=>(t._setWindowSize(e),t.multiply(BigInt(3)),t)};function y(e){const t=Li(e),r="string"==typeof e,n=(t||r)&&e.length;return t?n===o||n===s:r?n===2*o||n===2*s:e instanceof c}const b=t.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");const r=Hi(e),n=8*e.length-t.nBitLength;return n>0?r>>BigInt(n):r},w=t.bits2int_modN||function(e){return i(b(e))},v=Zi(t.nBitLength);function E(e){return Xi("num < 2^"+t.nBitLength,e,_u,v),Vi(e,t.nByteLength)}const S={lowS:t.lowS,prehash:!1},A={lowS:t.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:t,getPublicKey:function(e,t=!0){return c.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t,r=!0){if(y(e))throw new Error("first arg must be private key");if(!y(t))throw new Error("second arg must be public key");return c.fromHex(t).multiply(l(e)).toRawBytes(r)},sign:function(e,n,o=S){const{seed:s,k2sig:u}=function(e,n,o=S){if(["recovered","canonical"].some((e=>e in o)))throw new Error("sign() legacy options not supported");const{hash:s,randomBytes:u}=t;let{lowS:d,prehash:f,extraEntropy:m}=o;null==d&&(d=!0),e=Ki("msgHash",e),ku(o),f&&(e=Ki("prehashed msgHash",s(e)));const y=w(e),v=l(n),A=[E(v),E(y)];if(null!=m&&!1!==m){const e=!0===m?u(r.BYTES):m;A.push(Ki("extraEntropy",e))}const k=Gi(...A),C=y;return{seed:k,k2sig:function(e){const t=b(e);if(!h(t))return;const r=a(t),n=c.BASE.multiply(t).toAffine(),o=i(n.x);if(o===_u)return;const s=i(r*i(C+o*v));if(s===_u)return;let l=(n.x===o?0:2)|Number(n.y&Nu),u=s;return d&&p(s)&&(u=function(e){return p(e)?i(-e):e}(s),l^=1),new g(o,u,l)}}}(e,n,o),d=t;return ta(d.hash.outputLen,d.nByteLength,d.hmac)(s,u)},verify:function(e,r,n,o=A){const s=e;r=Ki("msgHash",r),n=Ki("publicKey",n);const{lowS:l,prehash:u,format:h}=o;if(ku(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==h&&"compact"!==h&&"der"!==h)throw new Error("format must be compact or der");const d="string"==typeof s||Li(s),p=!d&&!h&&"object"==typeof s&&null!==s&&"bigint"==typeof s.r&&"bigint"==typeof s.s;if(!d&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let f,m;try{if(p&&(f=new g(s.r,s.s)),d){try{"compact"!==h&&(f=g.fromDER(s))}catch(e){if(!(e instanceof Tu.Err))throw e}f||"der"===h||(f=g.fromCompact(s))}m=c.fromHex(n)}catch(e){return!1}if(!f)return!1;if(l&&f.hasHighS())return!1;u&&(r=t.hash(r));const{r:y,s:b}=f,v=w(r),E=a(b),S=i(v*E),k=i(y*E),C=c.BASE.multiplyAndAddUnsafe(m,S,k)?.toAffine();return!!C&&i(C.x)===y},ProjectivePoint:c,Signature:g,utils:m}}function Bu(e){return{hash:e,hmac:(t,...r)=>Au(e,t,function(...e){let t=0;for(let r=0;r(e+t/Uu)/t;const Fu=ba(Ou,void 0,void 0,{sqrt:function(e){const t=Ou,r=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=e*e*e%t,u=l*l*e%t,h=fa(u,r,t)*u%t,d=fa(h,r,t)*u%t,p=fa(d,Uu,t)*l%t,f=fa(p,o,t)*p%t,g=fa(f,s,t)*f%t,m=fa(g,a,t)*g%t,y=fa(m,c,t)*m%t,b=fa(y,a,t)*g%t,w=fa(b,r,t)*u%t,v=fa(w,i,t)*f%t,E=fa(v,n,t)*l%t,S=fa(E,Uu,t);if(!Fu.eql(Fu.sqr(S),e))throw new Error("Cannot find square root");return S}}),$u=function(e,t){const r=t=>Lu({...e,...Bu(t)});return{...r(t),create:r}}({a:BigInt(0),b:BigInt(7),Fp:Fu,n:Ru,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{const t=Ru,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Du*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Mu(s*e,t),c=Mu(-n*e,t);let l=da(e-a*r-c*o,t),u=da(-a*n-c*s,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}}},jr);function qu(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}BigInt(0),$u.ProjectivePoint;class Hu{type="secp256k1";raw;_key;constructor(e){this._key=function(e){try{return $u.ProjectivePoint.fromHex(e),e}catch(e){throw new Js(String(e))}}(e),this.raw=function(e){return $u.ProjectivePoint.fromHex(e).toRawBytes(!0)}(this._key)}toMultihash(){return ct.digest(Wu(this))}toCID(){return yt.createV1(114,this.toMultihash())}toString(){return Se.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}verify(e,t){return function(e,t,r){const n=dt.digest(r instanceof Uint8Array?r:r.subarray());if(qu(n))return n.then((({digest:r})=>$u.verify(t,r,e))).catch((e=>{throw new pu(String(e))}));try{return $u.verify(t,n.digest,e)}catch(e){throw new pu(String(e))}}(this._key,t,e)}}class ju{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=function(e){try{return $u.getPublicKey(e,!0),e}catch(e){throw new Xs(String(e))}}(e),this.publicKey=new Hu(t??function(e){try{return $u.getPublicKey(e,!0)}catch(e){throw new Xs(String(e))}}(e))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&Cn(this.raw,e.raw)}sign(e){return function(e,t){const r=dt.digest(t instanceof Uint8Array?t:t.subarray());if(qu(r))return r.then((({digest:t})=>$u.sign(t,e).toDERRawBytes())).catch((e=>{throw new du(String(e))}));try{return $u.sign(r.digest,e).toDERRawBytes()}catch(e){throw new du(String(e))}}(this.raw,e)}}function Vu(e){return new Hu(e)}async function zu(e,t){if("Ed25519"===e)return async function(){const{privateKey:e,publicKey:t}=function(){const e=Ya.utils.randomPrivateKey(),t=Ya.getPublicKey(e);return{privateKey:Qa(e,t),publicKey:t}}();return new tc(e,t)}();if("secp256k1"===e)return async function(){const e=$u.utils.randomPrivateKey();return new ju(e)}();if("RSA"===e)return async function(e){if(e>8192)throw new Ws("Key size is too large");const t=await async function(e){const t=await gu.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 async function(e){if(null==e.privateKey||null==e.publicKey)throw new Ws("Private and public key are required");return Promise.all([gu.get().subtle.exportKey("jwk",e.privateKey),gu.get().subtle.exportKey("jwk",e.publicKey)])}(t);return{privateKey:r[0],publicKey:r[1]}}(e),r=ot(18,jr(ic.encode({Type:oc.RSA,Data:bu(t.publicKey)})));return new yu(t.privateKey,new mu(t.publicKey,r))}(t??2048);throw new yi}async function Ku(e,t){if("Ed25519"!==e)throw new yi("Seed key derivation only supported for Ed25519 keys");return async function(e){const{privateKey:t,publicKey:r}=function(e){if(32!==e.length)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=Ya.getPublicKey(t);return{privateKey:Qa(t,r),publicKey:r}}(e);return new tc(t,r)}(t)}function Gu(e){const{Type:t,Data:r}=ic.decode(e),n=r??new Uint8Array;switch(t){case oc.RSA:return Eu(n);case oc.Ed25519:return rc(n);case oc.secp256k1:return Vu(n);default:throw new yi}}function Wu(e){return ic.encode({Type:oc[e.type],Data:e.raw})}const Ju=Symbol.for("@libp2p/service-capabilities"),Xu=Symbol.for("@libp2p/service-dependencies"),Yu=Symbol.for("nodejs.util.inspect.custom");class Zu{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[Fo]=!0;toString(){return null==this.string&&(this.string=Se.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return yt.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){if(null==e)return!1;if(e instanceof Uint8Array)return Cn(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=e?.toMultihash()?.bytes)return Cn(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Yu](){return`PeerId(${this.toString()})`}}class Qu extends Zu{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}}class eh extends Zu{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}}class th extends Zu{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}}class rh{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ct.digest(xt(this.url))}[Yu](){return`PeerId(${this.url})`}[Fo]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return yt.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Zr(e)),e.toString()===this.toString())}}function nh(e,t){let r;if("1"===e.charAt(0)||"Q"===e.charAt(0))r=st(Se.decode(`z${e}`));else{if(null==t)throw new Ws('Please pass a multibase decoder for strings that do not start with "1" or "Q"');r=st(t.decode(e))}return sh(r)}function oh(e){if("Ed25519"===e.type)return new eh({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new th({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new Qu({multihash:e.toCID().multihash,publicKey:e});throw new yi}function sh(e){if(function(e){return e.code===dt.code}(e))return new Qu({multihash:e});if(function(e){return e.code===ct.code}(e))try{const t=function(e){const{Type:t,Data:r}=ic.decode(e.digest),n=r??new Uint8Array;switch(t){case oc.Ed25519:return rc(n);case oc.secp256k1:return Vu(n);default:throw new yi}}(e);if("Ed25519"===t.type)return new eh({multihash:e,publicKey:t});if("secp256k1"===t.type)return new th({multihash:e,publicKey:t})}catch(t){const r=Zr(e.digest);return new rh(new URL(r))}throw new ai("Supplied PeerID Multihash is invalid")}function ih(e){if(null==e?.multihash||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new ii("Supplied PeerID CID is invalid");if(2336===e.code){const t=Zr(e.multihash.digest);return new rh(new URL(t))}return sh(e.multihash)}class ah extends Error{type;code;constructor(e,t,r){super(e??"The operation was aborted"),this.type="aborted",this.name=r??"AbortError",this.code=t??"ABORT_ERR"}}async function ch(e,t,r){if(null==t)return e;if(t.aborted)return Promise.reject(new ah(r?.errorMessage,r?.errorCode,r?.errorName));let n;const o=new ah(r?.errorMessage,r?.errorCode,r?.errorName);try{return await Promise.race([e,new Promise(((e,r)=>{n=()=>{r(o)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}class lh{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=$n(),this.haveNext=$n()}[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=$n(),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=$n(),await ch(this.readNext.promise,t?.signal,t)}}class uh extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}class hh extends Error{code;constructor(e,t){super(e),this.code=t}}class dh extends hh{type;constructor(e){super(e,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}}function ph(e,t){const r=new lh;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 o=new _n,s={read:async(e,t)=>{let r;t?.signal?.throwIfAborted();const s=new Promise(((e,n)=>{r=()=>{n(new dh("Read aborted"))},t?.signal?.addEventListener("abort",r)}));try{if(null==e){const{done:e,value:t}=await Promise.race([n.next(),s]);return!0===e?new _n:t}for(;o.byteLength{t?.signal?.throwIfAborted(),e instanceof Uint8Array?await r.push(e,t):await r.push(e.subarray(),t)},unwrap:()=>{if(o.byteLength>0){const r=e.source;e.source=async function*(){!1===t?.yieldBytes?yield o:yield*o,yield*r}()}return e}};return s}class fh extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"}class gh extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"}class mh extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"}function yh(e,t={}){const r=ph(e,t);null!=t.maxDataLength&&null==t.maxLengthLength&&(t.maxLengthLength=I(t.maxDataLength));const n=t?.lengthDecoder??N,o=t?.lengthEncoder??_;return{read:async e=>{let o=-1;const s=new _n;for(;;){s.append(await r.read(1,e));try{o=n(s)}catch(e){if(e instanceof RangeError)continue;throw e}if(o<0)throw new fh("Invalid message length");if(null!=t?.maxLengthLength&&s.byteLength>t.maxLengthLength)throw new mh("message length length too long");if(o>-1)break}if(null!=t?.maxDataLength&&o>t.maxDataLength)throw new gh("message length too long");return r.read(o,e)},write:async(e,t)=>{await r.write(new _n(o(e.byteLength),e),t)},writeV:async(e,t)=>{const n=new _n(...e.flatMap((e=>[o(e.byteLength),e])));await r.write(n,t)},unwrap:()=>r.unwrap()}}function bh(){const e=$n();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 wh=65535,vh=Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);function Eh(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`positive integer expected, not ${e}`)}function Sh(e){if("boolean"!=typeof e)throw new Error(`boolean expected, not ${e}`)}function Ah(e){return e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name}function kh(e,...t){if(!Ah(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${e.length}`)}function Ch(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 Ih=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));if(68!==new Uint8Array(new Uint32Array([287454020]).buffer)[0])throw new Error("Non little-endian hardware is not supported");function xh(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected, got "+typeof e);return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!Ah(e))throw new Error("Uint8Array expected, got "+typeof e);e=Nh(e)}return e}const Th=(e,t)=>(Object.assign(t,e),t);function _h(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);const o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,l=n?0:4;e.setUint32(t+c,i,n),e.setUint32(t+l,a,n)}function Nh(e){return Uint8Array.from(e)}function Ph(...e){for(let t=0;tUint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),Bh=Lh("expand 16-byte k"),Oh=Lh("expand 32-byte k"),Rh=Ih(Bh),Dh=Ih(Oh);function Uh(e,t){return e<>>32-t}function Mh(e){return e.byteOffset%4==0}Dh.slice();const Fh=2**32-1,$h=new Uint32Array;function qh(e,t){const{allowShortKeys:r,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t)}(0,t);if("function"!=typeof e)throw new Error("core must be a function");return Eh(o),Eh(i),Sh(s),Sh(r),(t,a,c,l,u=0)=>{kh(t),kh(a),kh(c);const h=c.length;if(void 0===l&&(l=new Uint8Array(h)),kh(l),Eh(u),u<0||u>=Fh)throw new Error("arx: counter overflow");if(l.length=Fh)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;t255&e[t++]|(255&e[t++])<<8;class jh{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,kh(e=xh(e),32);const t=Hh(e,0),r=Hh(e,2),n=Hh(e,4),o=Hh(e,6),s=Hh(e,8),i=Hh(e,10),a=Hh(e,12),c=Hh(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|o<<9),this.r[4]=255&(o>>>4|s<<12),this.r[5]=s>>>1&8190,this.r[6]=8191&(s>>>14|i<<2),this.r[7]=8065&(i>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=Hh(e,16+2*t)}process(e,t,r=!1){const n=r?0:2048,{h:o,r:s}=this,i=s[0],a=s[1],c=s[2],l=s[3],u=s[4],h=s[5],d=s[6],p=s[7],f=s[8],g=s[9],m=Hh(e,t+0),y=Hh(e,t+2),b=Hh(e,t+4),w=Hh(e,t+6),v=Hh(e,t+8),E=Hh(e,t+10),S=Hh(e,t+12),A=Hh(e,t+14);let k=o[0]+(8191&m),C=o[1]+(8191&(m>>>13|y<<3)),I=o[2]+(8191&(y>>>10|b<<6)),x=o[3]+(8191&(b>>>7|w<<9)),T=o[4]+(8191&(w>>>4|v<<12)),_=o[5]+(v>>>1&8191),N=o[6]+(8191&(v>>>14|E<<2)),P=o[7]+(8191&(E>>>11|S<<5)),L=o[8]+(8191&(S>>>8|A<<8)),B=o[9]+(A>>>5|n),O=0,R=O+k*i+C*(5*g)+I*(5*f)+x*(5*p)+T*(5*d);O=R>>>13,R&=8191,R+=_*(5*h)+N*(5*u)+P*(5*l)+L*(5*c)+B*(5*a),O+=R>>>13,R&=8191;let D=O+k*a+C*i+I*(5*g)+x*(5*f)+T*(5*p);O=D>>>13,D&=8191,D+=_*(5*d)+N*(5*h)+P*(5*u)+L*(5*l)+B*(5*c),O+=D>>>13,D&=8191;let U=O+k*c+C*a+I*i+x*(5*g)+T*(5*f);O=U>>>13,U&=8191,U+=_*(5*p)+N*(5*d)+P*(5*h)+L*(5*u)+B*(5*l),O+=U>>>13,U&=8191;let M=O+k*l+C*c+I*a+x*i+T*(5*g);O=M>>>13,M&=8191,M+=_*(5*f)+N*(5*p)+P*(5*d)+L*(5*h)+B*(5*u),O+=M>>>13,M&=8191;let F=O+k*u+C*l+I*c+x*a+T*i;O=F>>>13,F&=8191,F+=_*(5*g)+N*(5*f)+P*(5*p)+L*(5*d)+B*(5*h),O+=F>>>13,F&=8191;let $=O+k*h+C*u+I*l+x*c+T*a;O=$>>>13,$&=8191,$+=_*i+N*(5*g)+P*(5*f)+L*(5*p)+B*(5*d),O+=$>>>13,$&=8191;let q=O+k*d+C*h+I*u+x*l+T*c;O=q>>>13,q&=8191,q+=_*a+N*i+P*(5*g)+L*(5*f)+B*(5*p),O+=q>>>13,q&=8191;let H=O+k*p+C*d+I*h+x*u+T*l;O=H>>>13,H&=8191,H+=_*c+N*a+P*i+L*(5*g)+B*(5*f),O+=H>>>13,H&=8191;let j=O+k*f+C*p+I*d+x*h+T*u;O=j>>>13,j&=8191,j+=_*l+N*c+P*a+L*i+B*(5*g),O+=j>>>13,j&=8191;let V=O+k*g+C*f+I*p+x*d+T*h;O=V>>>13,V&=8191,V+=_*u+N*l+P*c+L*a+B*i,O+=V>>>13,V&=8191,O=(O<<2)+O|0,O=O+R|0,R=8191&O,O>>>=13,D+=O,o[0]=R,o[1]=D,o[2]=U,o[3]=M,o[4]=F,o[5]=$,o[6]=q,o[7]=H,o[8]=j,o[9]=V}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 o=(1^n)-1;for(let e=0;e<10;e++)r[e]&=o;o=~o;for(let t=0;t<10;t++)e[t]=e[t]&o|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 s=e[0]+t[0];e[0]=65535&s;for(let r=1;r<8;r++)s=(e[r]+t[r]|0)+(s>>>16)|0,e[r]=65535&s;Ph(r)}update(e){Ch(this);const{buffer:t,blockLen:r}=this,n=(e=xh(e)).length;for(let o=0;o>>0,e[o++]=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 Vh=function(e){const t=(t,r)=>e(r).update(xh(t)).digest(),r=e(new Uint8Array(32));return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t}((e=>new jh(e)));function zh(e,t,r,n,o,s=20){let i=e[0],a=e[1],c=e[2],l=e[3],u=t[0],h=t[1],d=t[2],p=t[3],f=t[4],g=t[5],m=t[6],y=t[7],b=o,w=r[0],v=r[1],E=r[2],S=i,A=a,k=c,C=l,I=u,x=h,T=d,_=p,N=f,P=g,L=m,B=y,O=b,R=w,D=v,U=E;for(let e=0;e{e.update(t);const r=t.length%16;r&&e.update(Wh.subarray(r))},Xh=new Uint8Array(32);function Yh(e,t,r,n,o){const s=e(t,r,Xh),i=Vh.create(s);o&&Jh(i,o),Jh(i,n);const a=new Uint8Array(16),c=(l=a,new DataView(l.buffer,l.byteOffset,l.byteLength));var l;_h(c,0,BigInt(o?o.length:0),!0),_h(c,8,BigInt(n.length),!0),i.update(a);const u=i.digest();return Ph(s,a),u}const Zh=e=>(t,r,n)=>(kh(t,32),kh(r),{encrypt(o,s){const i=o.length,a=i+16;s?kh(s,a):s=new Uint8Array(a),e(t,r,o,s,1);const c=Yh(e,t,r,s.subarray(0,-16),n);return s.set(c,i),Ph(c),s},decrypt(o,s){const i=o.length,a=i-16;if(i<16)throw new Error("encrypted data must be at least 16 bytes");s?kh(s,a):s=new Uint8Array(a);const c=o.subarray(0,-16),l=o.subarray(-16),u=Yh(e,t,r,c,n);if(!function(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;njr(e.subarray()),getHKDF(e,t){const r=function(e,t,r){return Tr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Au(e,Br(r),Br(t))}(jr,t,e),n=function(e,t,r,n=32){if(Tr(e),Ir(n),n>255*e.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(n/e.outputLen);void 0===r&&(r=td);const s=new Uint8Array(o*e.outputLen),i=Au.create(e,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let t=0;t({publicKey:Za.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>Za.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>Qh(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,o)=>Qh(n,t,r).decrypt(e.subarray(),o)},nd=e=>{const t=m(2);return t[0]=e>>8,t[1]=e,t};nd.bytes=2;const od=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){let t=0;return t+=e[0]<<8,t+=e[1],t}return e.getUint16(0)};function sd(e,t){t.enabled&&vh&&(e?(t(`LOCAL_STATIC_PUBLIC_KEY ${Zr(e.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${Zr(e.privateKey,"hex")}`)):t("Missing local static keys."))}function id(e,t){t.enabled&&vh&&(e?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${Zr(e.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${Zr(e.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function ad(e,t){t.enabled&&vh&&t(e?`REMOTE_EPHEMERAL_PUBLIC_KEY ${Zr(e.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function cd(e,t,r){r.enabled&&vh&&(r(`CIPHER_STATE_1 ${e.n.getUint64()} ${e.k&&Zr(e.k,"hex")}`),r(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&Zr(t.k,"hex")}`))}od.bytes=2;class ld extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=ld.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"}class ud{n;bytes;view;constructor(e=0){this.n=e,this.bytes=g(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}const hd=g(0);class dd{k;n;crypto;constructor(e,t=void 0,r=0){this.crypto=e,this.k=t,this.n=new ud(r)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();const r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();const n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class pd{cs;ck;h;crypto;constructor(e,t){this.crypto=e;const r=xt(t,"utf-8");this.h=function(e,t){if(t.length<=32){const e=g(32);return e.set(t),e}return e.hash(t)}(e,r),this.ck=this.h,this.cs=new dd(e)}mixKey(e){const[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new dd(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new _n(this.h,e))}encryptAndHash(e){const t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){const t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){const[e,t]=this.crypto.hkdf(this.ck,hd);return[new dd(this.crypto,e),new dd(this.crypto,t)]}}class fd{ss;s;e;rs;re;initiator;crypto;constructor(e){const{crypto:t,protocolName:r,prologue:n,initiator:o,s,e:i,rs:a,re:c}=e;this.crypto=t,this.ss=new pd(t,r),this.ss.mixHash(n),this.initiator=o,this.s=s,this.e=i,this.rs=a,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");const e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength(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>>3==1?r.webtransportCerthashes.push(e.bytes()):e.skipType(7&t)}return r}))),t),e.encode=t=>qt(t,e.codec()),e.decode=t=>K(t,e.codec())}(md||(md={})),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),md.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{const r={identityKey:g(0),identitySig:g(0)},n=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:r.identityKey=e.bytes();break;case 2:r.identitySig=e.bytes();break;case 4:r.extensions=md.codec().decode(e,e.uint32());break;default:e.skipType(7&t)}}return r}))),t),e.encode=t=>qt(t,e.codec()),e.decode=t=>K(t,e.codec())}(yd||(yd={}));class Ed{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(e,t={}){const{staticNoiseKey:r,extensions:n,crypto:o,prologueBytes:s}=t,{metrics:i}=e;this.components=e;const a=o??rd;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(a),this.extensions=n,this.metrics=i?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(i):void 0,this.staticKey=r?a.generateX25519KeyPairFromSeed(r):a.generateX25519KeyPair(),this.prologue=s??g(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ju]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){const r=yh(e,{lengthEncoder:nd,lengthDecoder:od,maxDataLength:wh}),n=await this.performHandshakeInitiator(r,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(r,n);e.source=o.source,e.sink=o.sink;const s=Gu(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:oh(s)}}async secureInbound(e,t){const r=yh(e,{lengthEncoder:nd,lengthDecoder:od,maxDataLength:wh}),n=await this.performHandshakeResponder(r,this.components.privateKey,t?.remotePeer?.publicKey,t),o=await this.createSecureConnection(r,n);e.source=o.source,e.sink=o.sink;const s=Gu(n.payload.identityKey);return{conn:e,remoteExtensions:n.payload.extensions,remotePeer:oh(s)}}async performHandshakeInitiator(e,t,r,n){let o;try{o=await async function(e,t){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await bd(s,a.publicKey,l),h=new gd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});sd(h.s,r),r.trace("Stage 0 - Initiator starting to send first message."),await n.write(h.writeMessageA(hd),t),r.trace("Stage 0 - Initiator finished sending first message."),id(h.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");const d=h.readMessageB(await n.read(t));var p,f;r.trace("Stage 1 - Initiator received the message."),ad(h.re,r),p=h.rs,(f=r).enabled&&vh&&f(p?`REMOTE_STATIC_PUBLIC_KEY ${Zr(p.subarray(),"hex")}`:"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");const g=await wd(d,h.rs,c);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),await n.write(h.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");const[m,y]=h.ss.split();return cd(m,y,r),{payload:g,encrypt:e=>m.encryptWithAd(hd,e),decrypt:(e,t)=>y.decryptWithAd(hd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return o}async performHandshakeResponder(e,t,r,n){let o;try{o=await async function(e,t){const{log:r,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=e,u=await bd(s,a.publicKey,l),h=new gd({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});sd(h.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),h.readMessageA(await n.read(t)),r.trace("Stage 0 - Responder received first message."),ad(h.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(h.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),id(h.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");const d=h.readMessageC(await n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");const p=await wd(d,h.rs,c),[f,g]=h.ss.split();return cd(f,g,r),{payload:p,encrypt:e=>g.encryptWithAd(hd,e),decrypt:(e,t)=>f.decryptWithAd(hd,e,t)}}({connection:e,privateKey:t,remoteIdentityKey:r,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},n),this.metrics?.xxHandshakeSuccesses.increment()}catch(e){throw this.metrics?.xxHandshakeErrors.increment(),e}return o}async createSecureConnection(e,t){const[r,n]=function(){const e=bh(),t=bh();return[{source:e.source,sink:t.sink},{source:t.source,sink:e.sink}]}(),o=e.unwrap();return await Kn(r,function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(s=n.length),o=n instanceof Uint8Array?e.encrypt(n.subarray(r,s)):e.encrypt(n.sublist(r,s)),t?.encryptedPackets.increment(),yield new _n(nd(o.byteLength),o)}}}(t,this.metrics),o,(e=>Fn(e,{lengthDecoder:od})),function(e,t){return async function*(r){for await(const n of r)for(let r=0;rn.length&&(o=n.length),o-16new Ed(t,e)}const Ad=Symbol.for("@libp2p/peer-discovery"),kd=tp("dns4"),Cd=tp("dns6"),Id=tp("dnsaddr"),xd=ep(tp("dns"),Id,kd,Cd),Td=ep(tp("ip4"),tp("ip6")),_d=ep(Qd(Td,tp("tcp")),Qd(xd,tp("tcp"))),Nd=Qd(Td,tp("udp")),Pd=Qd(Nd,tp("utp")),Ld=Qd(Nd,tp("quic")),Bd=Qd(Nd,tp("quic-v1")),Od=ep(Qd(_d,tp("ws")),Qd(xd,tp("ws"))),Rd=ep(Qd(Od,tp("p2p")),Od),Dd=ep(Qd(_d,tp("wss")),Qd(xd,tp("wss")),Qd(_d,tp("tls"),tp("ws")),Qd(xd,tp("tls"),tp("ws"))),Ud=ep(Qd(Dd,tp("p2p")),Dd),Md=ep(Qd(_d,tp("http")),Qd(Td,tp("http")),Qd(xd,tp("http"))),Fd=ep(Qd(_d,tp("https")),Qd(Td,tp("https")),Qd(xd,tp("https"))),$d=Qd(Nd,tp("webrtc-direct"),tp("certhash")),qd=ep(Qd($d,tp("p2p")),$d),Hd=Qd(Bd,tp("webtransport"),tp("certhash"),tp("certhash")),jd=ep(Qd(Hd,tp("p2p")),Hd),Vd=ep(Qd(Rd,tp("p2p-webrtc-star"),tp("p2p")),Qd(Ud,tp("p2p-webrtc-star"),tp("p2p")),Qd(Rd,tp("p2p-webrtc-star")),Qd(Ud,tp("p2p-webrtc-star"))),zd=(ep(Qd(Rd,tp("p2p-websocket-star"),tp("p2p")),Qd(Ud,tp("p2p-websocket-star"),tp("p2p")),Qd(Rd,tp("p2p-websocket-star")),Qd(Ud,tp("p2p-websocket-star"))),ep(Qd(Md,tp("p2p-webrtc-direct"),tp("p2p")),Qd(Fd,tp("p2p-webrtc-direct"),tp("p2p")),Qd(Md,tp("p2p-webrtc-direct")),Qd(Fd,tp("p2p-webrtc-direct")))),Kd=ep(Od,Dd,Md,Fd,Vd,zd,_d,Pd,Ld,xd,qd,jd),Gd=(ep(Qd(Kd,tp("p2p-stardust"),tp("p2p")),Qd(Kd,tp("p2p-stardust"))),ep(Qd(Kd,tp("p2p")),Vd,zd,qd,jd,tp("p2p"))),Wd=ep(Qd(Gd,tp("p2p-circuit"),Gd),Qd(Gd,tp("p2p-circuit")),Qd(tp("p2p-circuit"),Gd),Qd(Kd,tp("p2p-circuit")),Qd(tp("p2p-circuit"),Kd),tp("p2p-circuit")),Jd=()=>ep(Qd(Wd,Jd),Wd),Xd=Jd(),Yd=ep(Qd(Xd,Gd,Xd),Qd(Gd,Xd),Qd(Xd,Gd),Xd,Gd);function Zd(e){return function(t){let r;try{r=Is(t)}catch(e){return!1}const n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function Qd(...e){function t(t){if(t.length(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:Zd(t),partialMatch:t}}function ep(...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:Zd(t),partialMatch:t}}function tp(e){const t=e;return{toString:function(){return t},matches:function(e){let r;try{r=Is(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}}}ep(Qd(Xd,tp("webrtc"),tp("p2p")),Qd(Xd,tp("webrtc")),Qd(Kd,tp("webrtc"),tp("p2p")),Qd(Kd,tp("webrtc")),tp("webrtc"));class rp extends xo{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(!Yd.matches(e)){this.log.error("Invalid multiaddr");continue}const t=Is(e),r=t.getPeerId();if(null==r){this.log.error("Invalid bootstrap multiaddr without peer id");continue}const n={id:nh(r),multiaddrs:[t]};this.list.push(n)}this._init=t}[Ad]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[Ju]=["@libp2p/peer-discovery"];isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}async _discoverBootstrapPeers(){if(null!=this.timer)for(const e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??"bootstrap"]:{value:this._init.tagValue??50,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),null==this.timer)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch((t=>{this.log.error("could not dial bootstrap peer %p",e.id,t)}))}}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}const np=Uint8Array.from([3,1]);var op,sp;!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,r={})=>{const n={multiaddr:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>3==1?n.multiaddr=e.bytes():e.skipType(7&t)}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(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,n={})=>{const o={peerId:g(0),seq:0n,addresses:[]},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:o.peerId=t.bytes();break;case 2:o.seq=t.uint64();break;case 3:if(null!=n.limits?.addresses&&o.addresses.length===n.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');o.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;default:t.skipType(7&r)}}return o}))),r),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(op||(op={}));class ip{static createFromProtobuf=e=>{const t=op.decode(e),r=sh(st(t.peerId)),n=(t.addresses??[]).map((e=>Is(e.multiaddr))),o=t.seq;return new ip({peerId:r,multiaddrs:n,seqNumber:o})};static DOMAIN="libp2p-peer-record";static CODEC=np;peerId;multiaddrs;seqNumber;domain=ip.DOMAIN;codec=ip.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=op.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof ip&&!!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(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,r={})=>{const n={publicKey:g(0),payloadType:g(0),payload:g(0),signature:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:n.payload=e.bytes();break;case 5:n.signature=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(sp||(sp={}));class ap extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}}class cp{static createFromProtobuf=async e=>{const t=sp.decode(e),r=Gu(t.publicKey);return new cp({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t)=>{if(null==t)throw new Error("Missing private key");const r=e.domain,n=e.codec,o=e.marshal(),s=lp(r,n,o),i=await t.sign(s.subarray());return new cp({publicKey:t.publicKey,payloadType:n,payload:o,signature:i})};static openAndCertify=async(e,t)=>{const r=await cp.createFromProtobuf(e);if(!await r.validate(t))throw new ap("Envelope signature is not valid for the given domain");return r};publicKey;payloadType;payload;signature;marshaled;constructor(e){const{publicKey:t,payloadType:r,payload:n,signature:o}=e;this.publicKey=t,this.payloadType=r,this.payload=n,this.signature=o}marshal(){return null==this.marshaled&&(this.marshaled=sp.encode({publicKey:Wu(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return Cn(this.marshal(),e.marshal())}async validate(e){const t=lp(e,this.payloadType,this.payload);return this.publicKey.verify(t.subarray(),this.signature)}}const lp=(e,t,r)=>{const n=xt(e),o=_(n.byteLength),s=_(t.length),i=_(r.length);return new _n(o,n,s,t,i,r)};var up=__webpack_require__(5507);const hp=["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 up.Netmask(e)));function dp(e){for(const t of hp)if(t.contains(e))return!0;return!1}function pp(e){return Jo(e)?dp(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){const t=e.split(":");if(t.length<2)return!1;const r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return dp(`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(r.substring(0,2),16)}.${parseInt(r.substring(2),16)}`)}(e):/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)?function(e){const t=e.split(":");return dp(t[t.length-1])}(e):Xo(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}function fp(e){try{const[[t,r]]=e.stringTuples();if(null==r)return!0;if(53===t||54===t||55===t||56===t)return!1;if(4===t||41===t)return pp(r)??!1}catch{}return!0}const gp=e=>({match:t=>!(t.length<1)&&!!e(t[0])&&t.slice(1),pattern:"fn"}),mp=e=>({match:t=>gp((t=>t===e)).match(t),pattern:e}),yp=()=>({match:e=>gp((e=>"string"==typeof e)).match(e),pattern:"{string}"}),bp=()=>({match:e=>gp((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),wp=()=>({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{Se.decode(`z${e[1]}`)}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),vp=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{Ie.decode(e[1])}catch{return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),Ep=e=>({match:t=>{const r=e.match(t);return!1===r?t:r},pattern:`optional(${e.pattern})`}),Sp=(...e)=>({match:t=>{let r;for(const n of e){const e=n.match(t);!1!==e&&(null==r||e.lengthe.pattern)).join(", ")})`}),Ap=(...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 kp(...e){function t(t){let r=(e=>e.toString().split("/").slice(1))(t);for(const t of e){const e=t.match(r);if(!1===e)return!1;r=e}return r}return{matchers:e,matches:function(e){return!1!==t(e)},exactMatch:function(e){const r=t(e);return!1!==r&&0===r.length}}}const Cp=Ap(mp("dns4"),yp()),Ip=Ap(mp("dns6"),yp()),xp=Ap(mp("dnsaddr"),yp()),Tp=Ap(mp("dns"),yp()),_p=(kp(Cp,Ep(wp())),kp(Ip,Ep(wp())),kp(xp,Ep(wp())),kp(Sp(Tp,xp,Cp,Ip),Ep(wp())),Ap(mp("ip4"),gp(Jo))),Np=Ap(mp("ip6"),gp(Xo)),Pp=Sp(_p,Np),Lp=Sp(Pp,Tp,Cp,Ip,xp),Bp=kp(Sp(Pp,Ap(Sp(Tp,xp,Cp,Ip),Ep(wp())))),Op=(kp(_p),kp(Np),kp(Pp),Ap(Lp,mp("tcp"),bp())),Rp=Ap(Lp,mp("udp"),bp()),Dp=kp(Ap(Op,Ep(wp()))),Up=(kp(Rp),Ap(Rp,mp("quic"),Ep(wp()))),Mp=Ap(Rp,mp("quic-v1"),Ep(wp())),Fp=Sp(Up,Mp),$p=(kp(Up),kp(Mp),Sp(Lp,Op,Rp,Up,Mp)),qp=Sp(Ap($p,mp("ws"),Ep(wp()))),Hp=kp(qp),jp=Sp(Ap($p,mp("wss"),Ep(wp())),Ap($p,mp("tls"),Ep(Ap(mp("sni"),yp())),mp("ws"),Ep(wp()))),Vp=kp(jp),zp=Ap(Rp,mp("webrtc-direct"),Ep(vp()),Ep(vp()),Ep(wp())),Kp=kp(zp),Gp=Ap(Mp,mp("webtransport"),Ep(vp()),Ep(vp()),Ep(wp())),Wp=kp(Gp),Jp=Sp(qp,jp,Ap(Op,Ep(wp())),Ap(Fp,Ep(wp())),Ap(Lp,Ep(wp())),zp,Gp,wp()),Xp=(kp(Jp),kp(Ap(Jp,mp("p2p-circuit"),wp()))),Yp=kp(Sp(Ap(Jp,mp("p2p-circuit"),mp("webrtc"),Ep(wp())),Ap(Jp,mp("webrtc"),Ep(wp())),Ap(mp("webrtc"),Ep(wp()))));function Zp(e,t){const r=yh(e,t),n={read:async(e,t)=>{const n=await r.read(t);return e.decode(n)},write:async(e,t,n)=>{await r.write(t.encode(e),n)},writeV:async(e,t,n)=>{await r.writeV(e.map((e=>t.encode(e))),n)},pb:e=>({read:async t=>n.read(e,t),write:async(t,r)=>n.write(t,e,r),writeV:async(t,r)=>n.writeV(t,e,r),unwrap:()=>n}),unwrap:()=>r.unwrap()};return n}var Qp;kp(Sp(Ap(Lp,mp("tcp"),bp(),mp("http"),Ep(wp())),Ap(Lp,mp("http"),Ep(wp())))),kp(Sp(Ap(Lp,mp("tcp"),Sp(Ap(mp("443"),mp("http")),Ap(bp(),mp("https"))),Ep(wp())),Ap(Lp,mp("tls"),mp("http"),Ep(wp())),Ap(Lp,mp("https"),Ep(wp())))),kp(Sp(Ap(mp("memory"),yp(),Ep(wp())))),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,r={})=>{const n={listenAddrs:[],protocols:[]},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:if(null!=r.limits?.listenAddrs&&n.listenAddrs.length===r.limits.listenAddrs)throw new Er('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:if(null!=r.limits?.protocols&&n.protocols.length===r.limits.protocols)throw new Er('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Qp||(Qp={}));var ef=__webpack_require__(4866);const tf="object"==typeof window&&"object"==typeof document&&9===document.nodeType,rf=ef(),nf=tf&&!rf,of=rf&&!tf,sf=rf&&tf,af=void 0!==globalThis.process&&void 0!==globalThis.process.release&&"node"===globalThis.process.release.name&&!rf,cf="function"==typeof importScripts&&"undefined"!=typeof self&&"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,lf=(void 0!==globalThis.process&&void 0!==globalThis.process.env&&globalThis.process.env.NODE_ENV,"undefined"!=typeof navigator&&"ReactNative"===navigator.product),uf="ipfs",hf=5e3,df=1,pf=1,ff=10,gf=8192,mf=!0,yf=!0;class bf{host;protocol;started;timeout;peerId;privateKey;peerStore;registrar;addressManager;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;events;runOnLimitedConnection;log;constructor(e,t){var r,n;this.protocol=t.protocol,this.started=!1,this.peerId=e.peerId,this.privateKey=e.privateKey,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.events=e.events,this.log=t.log,this.timeout=t.timeout??hf,this.maxInboundStreams=t.maxInboundStreams??df,this.maxOutboundStreams=t.maxOutboundStreams??pf,this.maxMessageSize=t.maxMessageSize??gf,this.maxObservedAddresses=t.maxObservedAddresses??ff,this.runOnLimitedConnection=t.runOnLimitedConnection??yf,this.host={protocolVersion:`${t.protocolPrefix??uf}/0.1.0`,agentVersion:(r=e.nodeInfo,n=t.agentVersion,null!=n||(n=`${r.name}/${r.version}`,af||of?n+=` UserAgent=${globalThis.process.version}`:(nf||cf||sf||lf)&&(n+=` UserAgent=${globalThis.navigator.userAgent}`)),n)}}isStarted(){return this.started}async start(){this.started||(await this.peerStore.merge(this.peerId,{metadata:{AgentVersion:xt(this.host.agentVersion),ProtocolVersion:xt(this.host.protocolVersion)}}),await this.registrar.handle(this.protocol,(e=>{this.handleProtocol(e).catch((e=>{this.log.error(e)}))}),{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.registrar.unhandle(this.protocol),this.started=!1}}class wf extends bf{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??uf}/id/1.0.0`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??mf)&&e.events.addEventListener("connection:open",(e=>{const t=e.detail;this.identify(t).catch((e=>{e.name!==ci.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}[Ju]=["@libp2p/identify"];async _identify(e,t={}){let r;if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{r=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection});const n=Zp(r,{maxDataLength:this.maxMessageSize}).pb(Qp),o=await n.read(t);return await r.close(t),o}catch(e){throw r?.abort(e),e}}async identify(e,t={}){const r=await this._identify(e,t),{publicKey:n,protocols:o,observedAddr:s}=r;if(null==n)throw new li("public key was missing from identify message");const i=ih(Gu(n).toCID());if(!e.remotePeer.equals(i))throw new li("identified peer does not match the expected peer");if(this.peerId.equals(i))throw new li("identified peer is our own peer id?");return this.maybeAddObservedAddress(s),this.log("identify completed for peer %p and protocols %o",i,o),async function(e,t,r,n,o){if(r("received identify from %p",n.remotePeer),null==o)throw new li("message was null or undefined");const s={};if(o.listenAddrs.length>0&&(s.addresses=o.listenAddrs.map((e=>({isCertified:!1,multiaddr:Is(e)})))),o.protocols.length>0&&(s.protocols=o.protocols),null!=o.publicKey){const e=Gu(o.publicKey);if(!oh(e).equals(n.remotePeer))throw new li("public key did not match remote PeerId");s.publicKey=e}let i;if(null!=o.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);let t=o.signedPeerRecord;const a=await cp.openAndCertify(t,ip.DOMAIN);let c=ip.createFromProtobuf(a.payload);const l=ih(a.publicKey.toCID());if(!c.peerId.equals(l))throw new li("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(c.peerId))throw new li("signing key does not match remote PeerId");let u;try{u=await e.get(c.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=u&&(s.metadata=u.metadata,null!=u.peerRecordEnvelope)){const e=await cp.createFromProtobuf(u.peerRecordEnvelope),n=ip.createFromProtobuf(e.payload);n.seqNumber>=c.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",n.seqNumber,c.seqNumber),c=n,t=u.peerRecordEnvelope)}s.peerRecordEnvelope=t,s.addresses=c.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),i={seq:c.seqNumber,addresses:c.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,s),await e.patch(n.remotePeer,s),null!=o.agentVersion||null!=o.protocolVersion){const t={};null!=o.agentVersion&&(t.AgentVersion=xt(o.agentVersion)),null!=o.protocolVersion&&(t.ProtocolVersion=xt(o.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,t),await e.merge(n.remotePeer,{metadata:t})}const a={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:o.listenAddrs.map((e=>Is(e))),observedAddr:null==o.observedAddr?void 0:Is(o.observedAddr),protocols:o.protocols,signedPeerRecord:i,connection:n};return t.safeDispatchEvent("peer:identify",{detail:a}),a}(this.peerStore,this.events,this.log,e,r)}maybeAddObservedAddress(e){const t=function(e){if(null!=e&&e.length>0)try{return Is(e)}catch{}}(e);null!=t&&(this.log.trace("our observed address was %a",t),fp(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||function(e){try{const[[r,n]]=e.stringTuples();if(null==n)return!1;if(41===r)return t=n,new Wo("2000::/3").contains(t)}catch{}var t;return!1}(t)?Dp.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address"))}async handleProtocol(e){const{connection:t,stream:r}=e,n=AbortSignal.timeout(this.timeout);try{const e=await this.peerStore.get(this.peerId),o=this.addressManager.getAddresses().map((e=>e.decapsulateCode(os("p2p").code)));let s=e.peerRecordEnvelope;if(o.length>0&&null==s){const e=new ip({peerId:this.peerId,multiaddrs:o});s=(await cp.seal(e,this.privateKey)).marshal().subarray()}let i=t.remoteAddr.bytes;Bp.matches(t.remoteAddr)||(i=void 0);const a=Zp(r).pb(Qp);await a.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Wu(this.privateKey.publicKey),listenAddrs:o.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:i,protocols:e.protocols},{signal:n}),await r.close({signal:n})}catch(e){this.log.error("could not respond to identify request",e),r.abort(e)}}}function vf(e={}){return t=>new wf(t,e)}function Ef(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 Sf=()=>{const e=new Error("Delay aborted");return e.name="AbortError",e},Af=new WeakMap,kf=function({clearTimeout:e,setTimeout:t}={}){return(r,{value:n,signal:o}={})=>{if(o?.aborted)return Promise.reject(Sf());let s,i,a;const c=e??clearTimeout,l=()=>{c(s),a(Sf())},u=new Promise(((e,c)=>{i=()=>{o&&o.removeEventListener("abort",l),e(n)},a=c,s=(t??setTimeout)(i,r)}));return o&&o.addEventListener("abort",l,{once:!0}),Af.set(u,(()=>{c(s),s=null,i()})),u}}();class Cf extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}class If extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}}class xf{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 Tf}async consume(e,t=1,r={}){const n=this.getKey(e),o=this._getKeySecDuration(r);let s=this.memoryStorage.incrby(n,t,o);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(n,s.consumedPoints,this.blockDuration)),new Cf("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let e=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));e=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 Tf{storage;constructor(){this.storage=new Map}incrby(e,t,r){const n=this.storage.get(e);if(null!=n){const o=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||o>0?(n.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){const n=1e3*r,o=this.storage.get(e);null!=o&&clearTimeout(o.timeoutId);const s={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,s),n>0&&(s.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=s.timeoutId.unref&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:s.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 _f;!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"}(_f||(_f={}));const Nf=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),Pf=Object.freeze({NEW_STREAM:_f.NEW_STREAM,MESSAGE:_f.MESSAGE_INITIATOR,CLOSE:_f.CLOSE_INITIATOR,RESET:_f.RESET_INITIATOR}),Lf=Object.freeze({MESSAGE:_f.MESSAGE_RECEIVER,CLOSE:_f.CLOSE_RECEIVER,RESET:_f.RESET_RECEIVER}),Bf=1<<20;class Of{_buffer;_headerInfo;_maxMessageSize;_maxUnprocessedMessageQueueSize;constructor(e=Bf,t=4194304){this._buffer=new _n,this._headerInfo=null,this._maxMessageSize=e,this._maxUnprocessedMessageQueueSize=t}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new li("Unprocessed message queue size too large!");const t=[];for(;0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}const{id:e,type:r,length:n,offset:o}=this._headerInfo;if(this._buffer.length-othis._maxMessageSize)throw new li("Message size too large");return{id:t>>3,type:s,offset:r+o,length:n}}}const Rf=128,Df=127;function Uf(e,t=0){let r,n=0,o=0,s=t;const i=e.length;do{if(s>=i||o>49)throw t=0,new RangeError("Could not decode varint");r=e.get(s++),n+=o<28?(r&Df)<=Rf);return{value:n,offset:t=s-t}}const Mf=10240,Ff=new class{_pool;_poolOffset;constructor(){this._pool=m(Mf),this._poolOffset=0}write(e,t){const r=this._pool;let n=this._poolOffset;_(e.id<<3|e.type,r,n),n+=I(e.id<<3|e.type),e.type!==_f.NEW_STREAM&&e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||null==e.data?(_(0,r,n),n+=I(0)):(_(e.data.length,r,n),n+=I(e.data.length));const o=r.subarray(this._poolOffset,n);Mf-n<100?(this._pool=m(Mf),this._poolOffset=0):this._poolOffset=n,t.append(o),e.type!==_f.NEW_STREAM&&e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};class $f extends Error{constructor(e="Stream input buffer error"){super(e),this.name="StreamInputBufferError"}}function qf(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally}class Hf{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=$n(),this.closed=$n(),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=Vn({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 ri(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";const t={signal:this.sinkController.signal};if("outbound"===this.direction){const e=this.sendNewStream(t);qf(e)&&await e}const r=()=>{Ef(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 _n(r):r;const e=this.sendData(r,t);qf(e)&&(this.sendingData=$n(),await e,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",r)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),"writing"===this.writeStatus&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(e){null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseRead?.(),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),this.onCloseWrite?.(),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(e){"open"===this.status&&(this.log.trace("closing gracefully"),this.status="closing",await ch(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 ch(this.sink([]),e.signal)),"writing"===this.writeStatus&&(null!=this.sendingData&&await ch(this.sendingData.promise,e.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await ch(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();qf(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 ti("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 jf extends Hf{name;streamId;send;types;maxDataSize;constructor(e){super(e),this.types="outbound"===e.direction?Pf:Lf,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:Pf.NEW_STREAM,data:new _n(xt(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 Vf(e){const t={...e,type:`${Nf[e.type]} (${e.type})`};return e.type===_f.NEW_STREAM&&(t.data=Zr(e.data instanceof Uint8Array?e.data:e.data.subarray())),e.type!==_f.MESSAGE_INITIATOR&&e.type!==_f.MESSAGE_RECEIVER||(t.data=Zr(e.data instanceof Uint8Array?e.data:e.data.subarray(),"base16")),t}class zf{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=Vn({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=Kn(this._source,(e=>async function*(e){for await(const t of e){const e=new _n;Ff.write(t,e),yield e}}(e))),this.closeController=new AbortController,this.rateLimiter=new xf({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 ei("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:o}=e;if(this.log("new %s stream %s",n,t),"initiator"===n&&this._streams.initiators.size===(this._init.maxOutboundStreams??1024))throw new mi("Too many outbound streams open");if(o.has(t))throw new Error(`${n} stream ${t} already exists!`);const s=function(e){const{id:t,name:r,send:n,onEnd:o,type:s="initiator",maxMsgSize:i=Bf}=e;return new jf({id:"initiator"===s?`i${t}`:`r${t}`,streamId:t,name:`${r??t}`,direction:"initiator"===s?"outbound":"inbound",maxDataSize:i,onEnd:o,send:n,log:e.logger.forComponent(`libp2p:mplex:stream:${s}:${t}`)})}({id:t,name:r,send:async e=>{this.log.enabled&&this.log.trace("%s stream %s send",n,t,Vf(e)),this._source.push(e)},type:n,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",n,t,s.protocol),o.delete(t),null!=this._init.onStreamEnd&&this._init.onStreamEnd(s)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return o.set(t,s),s}_createSink(){return async e=>{const t=()=>{Ef(e,this.log)};this.closeController.signal.addEventListener("abort",t);try{const t=new Of(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",Vf(e)),e.type===_f.NEW_STREAM){if(this._streams.receivers.size===(this._init.maxInboundStreams??1024)){this.log("too many inbound streams open"),this._source.push({id:t,type:_f.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:Zr(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,Nf[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 o=this._init.maxStreamBufferSize??4194304;try{switch(r){case _f.MESSAGE_INITIATOR:case _f.MESSAGE_RECEIVER:if(n.sourceReadableLength()>o)throw this._source.push({id:e.id,type:r===_f.MESSAGE_INITIATOR?_f.RESET_RECEIVER:_f.RESET_INITIATOR}),new $f("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");n.sourcePush(e.data);break;case _f.CLOSE_INITIATOR:case _f.CLOSE_RECEIVER:n.remoteCloseWrite();break;case _f.RESET_INITIATOR:case _f.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 Kf{protocol="/mplex/6.7.0";_init;components;constructor(e,t={}){this.components=e,this._init=t}[Symbol.toStringTag]="@libp2p/mplex";[Ju]=["@libp2p/stream-multiplexing"];createStreamMuxer(e={}){return new zf(this.components,{...e,...this._init})}}function Gf(e={}){return t=>new Kf(t,e)}function Wf(e){if(isNaN(e)||e<=0)throw new Ws("random bytes length must be a Number bigger than 0");return Dr(e)}class Jf{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;log;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handleMessage=this.handleMessage.bind(this)}[Symbol.toStringTag]="@libp2p/ping";async start(){await this.components.registrar.handle(this.protocol,this.handleMessage,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}handleMessage(e){this.log("incoming ping from %p",e.connection.remotePeer);const{stream:t}=e,r=Date.now();AbortSignal.timeout(this.timeout).addEventListener("abort",(()=>{t?.abort(new hi("ping timeout"))})),Kn(t,(async function*(e){let r=0;for await(const n of e){if(r+=n.byteLength,r>32)return void t?.abort(new li("Too much data received"));yield n}}),t).catch((r=>{this.log.error("incoming ping from %p failed with error",e.connection.remotePeer,r),t?.abort(r)})).finally((()=>{const t=Date.now()-r;this.log("incoming ping from %p complete in %dms",e.connection.remotePeer,t)}))}async ping(e,t={}){this.log("pinging %p",e);const r=Date.now(),n=Wf(32),o=await this.components.connectionManager.openConnection(e,t);let s,i=()=>{};if(null==t.signal){const e=AbortSignal.timeout(this.timeout);t={...t,signal:e}}try{s=await o.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),i=()=>{s?.abort(new Ks)},t.signal?.addEventListener("abort",i,{once:!0});const e=await Kn([n],s,(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 ui(`Did not receive a ping ack after ${a}ms`);if(!Cn(n,e.subarray()))throw new ui(`Received wrong ping ack after ${a}ms`);return this.log("ping %p complete in %dms",o.remotePeer,a),a}catch(e){throw this.log.error("error while pinging %p",o.remotePeer,e),s?.abort(e),e}finally{t.signal?.removeEventListener("abort",i),null!=s&&await s.close()}}}function Xf(e={}){return t=>new Jf(t,e)}const Yf=Symbol.for("@libp2p/transport");var Zf;!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Zf||(Zf={}));const Qf=[os("tcp").code,os("dns").code,os("dnsaddr").code,os("dns4").code,os("dns6").code];function eg(e){return rg("sni",e)?.[1]}function tg(e){const t=rg("tcp",e)?.[1];return null==t?"":`:${t}`}function rg(e,t){let r;try{r=os(e).code}catch(e){return}for(const[e,n]of t)if(e===r&&null!=n)return[e,n]}function ng(e){return e.some((([e,t])=>e===os("tls").code))}function og(e,t,r){const n=sg[os(e).name];if(null==n)throw new Error(`Can't interpret protocol ${os(e).name}`);const o=n(t,r);return e===os("ip6").code?`[${o}]`:o}const sg={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:`[${e}]`,tcp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`tcp://${og(r[0],r[1]??"",t)}:${e}`},udp:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`udp://${og(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(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}`},p2p:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}`},http:(e,t)=>{const r=ng(t),n=eg(t),o=tg(t);if(r&&null!=n)return`https://${n}${o}`;const s=r?"https://":"http://",i=t.pop();if(null==i)throw new Error("Unexpected end of multiaddr");let a=og(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},"http-path":(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return`${og(r[0],r[1]??"",t)}/${decodeURIComponent(e)}`},tls:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return og(r[0],r[1]??"",t)},sni:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");return og(r[0],r[1]??"",t)},https:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=og(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`https://${n}`},ws:(e,t)=>{const r=ng(t),n=eg(t),o=tg(t);if(r&&null!=n)return`wss://${n}${o}`;const s=r?"wss://":"ws://",i=t.pop();if(null==i)throw new Error("Unexpected end of multiaddr");let a=og(i[0],i[1]??"",t);return a=a.replace("tcp://",""),`${s}${a}`},wss:(e,t)=>{const r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");let n=og(r[0],r[1]??"",t);return n=n.replace("tcp://",""),`wss://${n}`}},ig=async e=>{if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&await new Promise(((t,r)=>{function n(){e.removeEventListener("open",o),e.removeEventListener("error",s)}function o(){n(),t()}function s(t){n(),r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}e.addEventListener("open",o),e.addEventListener("error",s)}))},ag=(e,t)=>((t=t??{}).closeOnEnd=!1!==t.closeOnEnd,async r=>{for await(const t of r){try{await ig(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 cg=__webpack_require__(544);function lg(e){return e instanceof ArrayBuffer||"ArrayBuffer"===e?.constructor?.name&&"number"==typeof e?.byteLength}const ug=WebSocket,hg={"http:":"ws:","https:":"wss:"};function dg(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,o=null!=t.port&&!0!==n?.endsWith(`:${t.port}`)?`:${t.port}`:"";e=`${r}//${n}${o}${e}`}const r=new URL(e);for(const[e,t]of Object.entries(hg))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(o)return void t();if(null!=n)return void r(n);const s=t=>{e.removeEventListener("open",i),e.removeEventListener("error",a),t()},i=()=>{s(t)},a=t=>{s((()=>{r(t.error??new Error(`connect ECONNREFUSED ${e.url}`))}))};e.addEventListener("open",i),e.addEventListener("error",a)}))},r=async function*(){const r=new cg.PP((({push:t,stop:r,fail:n})=>{const o=e=>{let r=null;"string"==typeof e.data&&(r=xt(e.data)),lg(e.data)&&(r=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(r=e.data),null!=r&&t(r)},s=e=>{n(e.error??new Error("Socket error"))};return e.addEventListener("message",o),e.addEventListener("error",s),e.addEventListener("close",r),()=>{e.removeEventListener("message",o),e.removeEventListener("error",s),e.removeEventListener("close",r)}}),{highWaterMark:1/0});await t();for await(const e of r)yield lg(e)?new Uint8Array(e):e}();let n,o=1===e.readyState;return e.addEventListener("open",(()=>{o=!0,n=null})),e.addEventListener("close",(()=>{o=!1,n=null})),e.addEventListener("error",(t=>{o||(n=t.error??new Error(`connect ECONNREFUSED ${e.url}`))})),Object.assign(r,{connected:t})})(e);let n=t.remoteAddress,o=t.remotePort;if(null!=e.url)try{const t=new URL(e.url);n=t.hostname,o=parseInt(t.port,10)}catch{}if(null==n||null==o)throw new Error("Remote connection did not have address and/or port");return{sink:ag(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:o,socket:e}})(new ug(r.toString(),t.websocket),t)}class pg extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}}function fg(e){return e.filter((e=>Vp.exactMatch(e)||Hp.exactMatch(e)))}function gg(e){return e.filter((e=>Vp.exactMatch(e)))}class mg{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,null!=e.metrics&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Yf]=!0;[Symbol.toStringTag]="@libp2p/websockets";[Ju]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};const r=function(e,t,r){const n=r.logger.forComponent("libp2p:websockets:maconn"),o=r.metrics,s=r.metricPrefix??"",i={log:n,async sink(t){try{await e.sink(async function*(){for await(const e of t)e instanceof Uint8Array?yield e:yield e.subarray()}())}catch(e){"aborted"!==e.type&&n.error(e)}},source:e.source,remoteAddr:t,timeline:{open:Date.now()},async close(t={}){const r=Date.now();if(null==t.signal){const e=AbortSignal.timeout(500);t={...t,signal:e}}const o=()=>{const{host:e,port:t}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-r),this.abort(new Ks("Socket close timeout"))};t.signal?.addEventListener("abort",o);try{await e.close()}catch(e){n.error("error closing WebSocket gracefully",e),this.abort(e)}finally{t.signal?.removeEventListener("abort",o),i.timeline.close=Date.now()}},abort(t){const{host:r,port:a}=i.remoteAddr.toOptions();n("timeout closing stream to %s:%s due to error",r,a,t),e.destroy(),i.timeline.close=Date.now(),o?.increment({[`${s}error`]:!0})}};return e.socket.addEventListener("close",(()=>{o?.increment({[`${s}close`]:!0}),null==i.timeline.close&&(i.timeline.close=Date.now())}),{once:!0}),i}(await this._connect(e,t),e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",r.remoteAddr);const n=await t.upgrader.upgradeOutbound(r,t);return this.log("outbound connection %s upgraded",r.remoteAddr),n}async _connect(e,t){t?.signal?.throwIfAborted();const r=e.toOptions();this.log("dialing %s:%s",r.host,r.port);const n=$n(),o=dg(function(e){const t=Is(e).stringTuples(),r=t.pop();if(null==r)throw new Error("Unexpected end of multiaddr");const n=os(r[0]),o=sg[n.name];if(null==o)throw new Error(`No interpreter found for ${n.name}`);let s=o(r[1]??"",t);return Qf.includes(r[0])&&(s=s.replace(/^.*:\/\//,""),s="443"===r[1]?`https://${s}`:`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}(e),this.init);o.socket.addEventListener("error",(()=>{const t=new Qs(`Could not connect to ${e.toString()}`);this.log.error("connection error:",t),this.metrics?.dialerEvents.increment({error:!0}),n.reject(t)}));try{t.onProgress?.(new pg("websockets:open-connection")),await ch(Promise.race([o.connected(),n.promise]),t.signal)}catch(e){throw!0===t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch((e=>{this.log.error("error closing raw socket",e)})),e}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),this.init)}listenFilter(e){return e=Array.isArray(e)?e:[e],null!=this.init?.filter?this.init?.filter(e):fg(e)}dialFilter(e){return this.listenFilter(e)}}function yg(e={}){return t=>new mg(t,e)}var bg=__webpack_require__(228);class wg extends Error{constructor(e){super(e),this.name="TimeoutError"}}class vg extends Error{constructor(e){super(),this.name="AbortError",this.message=e}}const Eg=e=>void 0===globalThis.DOMException?new vg(e):new DOMException(e),Sg=e=>{const t=void 0===e.reason?Eg("This operation was aborted."):e.reason;return t instanceof Error?t:Eg(t)};function Ag(e,t){const{milliseconds:r,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t;let i,a;const c=new Promise(((c,l)=>{if("number"!=typeof r||1!==Math.sign(r))throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(t.signal){const{signal:e}=t;e.aborted&&l(Sg(e)),a=()=>{l(Sg(e))},e.addEventListener("abort",a,{once:!0})}if(r===Number.POSITIVE_INFINITY)return void e.then(c,l);const u=new wg;i=s.setTimeout.call(void 0,(()=>{if(n)try{c(n())}catch(e){l(e)}else"function"==typeof e.cancel&&e.cancel(),!1===o?c():o instanceof Error?l(o):(u.message=o??`Promise timed out after ${r} milliseconds`,l(u))}),r),(async()=>{try{c(await e)}catch(e){l(e)}})()})).finally((()=>{c.clear(),a&&t.signal&&t.signal.removeEventListener("abort",a)}));return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}class kg{#s=[];enqueue(e,t){const r={priority:(t={priority:0,...t}).priority,id:t.id,run:e};if(0===this.size||this.#s[this.size-1].priority>=t.priority)return void this.#s.push(r);const n=function(e,t){let r=0,n=e.length;for(;n>0;){const s=Math.trunc(n/2);let i=r+s;o=e[i],t.priority-o.priority<=0?(r=++i,n-=s+1):n=s}var o;return r}(this.#s,r);this.#s.splice(n,0,r)}setPriority(e,t){const r=this.#s.findIndex((t=>t.id===e));if(-1===r)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);const[n]=this.#s.splice(r,1);this.enqueue(n.run,{priority:t,id:e})}dequeue(){const e=this.#s.shift();return e?.run}filter(e){return this.#s.filter((t=>t.priority===e.priority)).map((e=>e.run))}get size(){return this.#s.length}}class Cg extends bg{#i;#a;#c=0;#l;#u;#h=0;#d;#p;#s;#f;#g=0;#m;#y;#b;#w=1n;timeout;constructor(e){if(super(),!("number"==typeof(e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:kg,...e}).intervalCap&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(void 0===e.interval||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#i=e.carryoverConcurrencyCount,this.#a=e.intervalCap===Number.POSITIVE_INFINITY||0===e.interval,this.#l=e.intervalCap,this.#u=e.interval,this.#s=new e.queueClass,this.#f=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#b=!0===e.throwOnTimeout,this.#y=!1===e.autoStart}get#v(){return this.#a||this.#c{this.#k()}),t)),!0;this.#c=this.#i?this.#g:0}return!1}#A(){if(0===this.#s.size)return this.#d&&clearInterval(this.#d),this.#d=void 0,this.emit("empty"),0===this.#g&&this.emit("idle"),!1;if(!this.#y){const e=!this.#x;if(this.#v&&this.#E){const t=this.#s.dequeue();return!!t&&(this.emit("active"),t(),e&&this.#I(),!0)}}return!1}#I(){this.#a||void 0!==this.#d||(this.#d=setInterval((()=>{this.#C()}),this.#u),this.#h=Date.now()+this.#u)}#C(){0===this.#c&&0===this.#g&&this.#d&&(clearInterval(this.#d),this.#d=void 0),this.#c=this.#i?this.#g:0,this.#T()}#T(){for(;this.#A(););}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#_(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}setPriority(e,t){this.#s.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#w++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#b,...t},new Promise(((r,n)=>{this.#s.enqueue((async()=>{this.#g++,this.#c++;try{t.signal?.throwIfAborted();let n=e({signal:t.signal});t.timeout&&(n=Ag(Promise.resolve(n),{milliseconds:t.timeout})),t.signal&&(n=Promise.race([n,this.#_(t.signal)]));const o=await n;r(o),this.emit("completed",o)}catch(e){if(e instanceof wg&&!t.throwOnTimeout)return void r();n(e),this.emit("error",e)}finally{this.#S()}}),t),this.emit("add"),this.#A()}))}async addAll(e,t){return Promise.all(e.map((async e=>this.add(e,t))))}start(){return this.#y?(this.#y=!1,this.#T(),this):this}pause(){this.#y=!0}clear(){this.#s=new this.#f}async onEmpty(){0!==this.#s.size&&await this.#N("empty")}async onSizeLessThan(e){this.#s.sizethis.#s.size{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))}get size(){return this.#s.size}sizeBy(e){return this.#s.filter(e).length}get pending(){return this.#g}get isPaused(){return this.#y}}function Ig(e){const t=[_g.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function xg(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:_g[e.type]}))),Answer:(e.Answer??e.answers??[]).map((e=>({name:e.name,type:_g[e.type],TTL:e.TTL??e.ttl??60,data:e.data instanceof Uint8Array?Zr(e.data):e.data})))}}function Tg(e,t={}){const r=new Cg({concurrency:t.queryConcurrency??4});return async(t,n={})=>{const o=new URLSearchParams;o.set("name",t),Ig(n.types).forEach((e=>{o.append("type",_g[e])})),n.onProgress?.(new pg("dns:query",{detail:t}));const s=await r.add((async()=>{const t=await fetch(`${e}?${o}`,{headers:{accept:"application/dns-json"},signal:n?.signal});if(200!==t.status)throw new Error(`Unexpected HTTP status: ${t.status} - ${t.statusText}`);const r=xg(await t.json());return n.onProgress?.(new pg("dns:response",{detail:r})),r}),{signal:n.signal});if(null==s)throw new Error("No DNS response received");return s}}var _g,Ng=__webpack_require__(194);class Pg{lru;constructor(e){this.lru=Ng(e)}get(e,t){let r=!0;const n=[];for(const o of t){const t=this.getAnswers(e,o);if(0===t.length){r=!1;break}n.push(...t)}if(r)return xg({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:_g[t.type]})));return 0===e.length&&this.lru.remove(r),e}return[]}add(e,t){const r=`${e.toLowerCase()}-${t.type}`,n=this.lru.get(r)??[];n.push({expires:Date.now()+1e3*(t.TTL??60),value:t}),this.lru.set(r,n)}remove(e,t){const r=`${e.toLowerCase()}-${t}`;this.lru.remove(r)}clear(){this.lru.clear()}}class Lg{resolvers;cache;constructor(e){var t;this.resolvers={},this.cache=(t=e.cacheSize??1e3,new Pg(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["."]=[Tg("https://cloudflare-dns.com/dns-query"),Tg("https://dns.google/resolve")])}async query(e,t={}){const r=Ig(t.types),n=!1!==t.cached?this.cache.get(e,r):void 0;if(null!=n)return t.onProgress?.(new pg("dns:cache",{detail:n})),n;const o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),i=[];for(const n of s){if(!0===t.signal?.aborted)break;try{const o=await n(e,{...t,types:r});for(const t of o.Answer)this.cache.add(e,t);return o}catch(e){i.push(e),t.onProgress?.(new pg("dns:error",{detail:e}))}}if(1===i.length)throw i[0];throw new AggregateError(i,`DNS lookup of ${e} ${r} failed`)}}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(_g||(_g={}));const{code:Bg}=os("dnsaddr");class Og extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}}const Rg=async function(e,t={}){const r=t.maxRecursiveDepth??32;if(0===r)throw new Og("Max recursive depth reached");const[,n]=e.stringTuples().find((([e])=>e===Bg))??[],o=t?.dns??function(e={}){return new Lg(e)}(),s=await o.query(`_dnsaddr.${n}`,{signal:t?.signal,types:[_g.TXT]}),i=e.getPeerId(),a=[];for(const e of s.Answer){const n=e.data.replace(/["']/g,"").trim().split("=")[1];if(null==n)continue;if(null!=i&&!n.includes(i))continue;const o=Is(n);if(n.startsWith("/dnsaddr")){const e=await o.resolve({...t,maxRecursiveDepth:r-1});a.push(...e.map((e=>e.toString())))}else a.push(o.toString())}return a},Dg=__webpack_require__(6864),Ug={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Rg}},transportManager:{faultTolerance:Zf.FATAL_ALL}};async function Mg(e){const t=Dg(Ug,e);if(null===t.connectionProtector&&null!=globalThis.process?.env?.LIBP2P_FORCE_PNET)throw new Ws("Private network is enforced, but no protector was provided");return t}const Fg=Symbol.for("@libp2p/content-routing"),$g=Symbol.for("@libp2p/peer-routing"),qg=1e3,Hg=60*qg,jg=60*Hg,Vg=24*jg,zg=7*Vg,Kg=function(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");const t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;const r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return r*zg;case"days":case"day":case"d":return r*Vg;case"hours":case"hour":case"hrs":case"hr":case"h":return r*jg;case"minutes":case"minute":case"mins":case"min":case"m":return r*Hg;case"seconds":case"second":case"secs":case"sec":case"s":return r*qg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error(`The unit ${n} was matched, but no matching case exists.`)}}(e);if("number"==typeof e&&isFinite(e))return t?.long?function(e){const t=Math.abs(e);return t>=Vg?Gg(e,t,Vg,"day"):t>=jg?Gg(e,t,jg,"hour"):t>=Hg?Gg(e,t,Hg,"minute"):t>=qg?Gg(e,t,qg,"second"):`${e} ms`}(e):function(e){const t=Math.abs(e);return t>=Vg?`${Math.round(e/Vg)}d`:t>=jg?`${Math.round(e/jg)}h`:t>=Hg?`${Math.round(e/Hg)}m`:t>=qg?`${Math.round(e/qg)}s`:`${e}ms`}(e);throw new Error("Value is not a string or number.")}catch(t){const r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?`${t.message}. value=${JSON.stringify(e)}`:"An unknown error has occured.";throw new Error(r)}};function Gg(e,t,r,n){const o=t>=1.5*r;return`${Math.round(e/r)} ${n}${o?"s":""}`}const Wg=function(){try{return localStorage}catch(e){}}(),Jg=console.debug??console.log??(()=>{}),Xg=function(e){function t(e){let n,o,s,i=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),s=o-(n||o);r.diff=s,r.prev=n,r.curr=o,n=o,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,o)=>{if("%%"===n)return"%";i++;const s=t.formatters[o];if("function"==typeof s){const t=e[i];n=s.call(r,t),e.splice(i,1),i--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==i?i:(o!==t.namespaces&&(o=t.namespaces,s=t.enabled(e)),s),set:e=>{i=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack??e.message:e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),o=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)},save:function(e){try{e?Wg?.setItem("debug",e):Wg?.removeItem("debug")}catch(e){}},load:function(){let e;try{e=Wg?.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement?.style?.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:Wg,log:Jg}),Yg=Xg;function Zg(){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 Yg.enabled(`${e}:trace`)&&null!=Yg.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Yg(`${e}:trace`)),Object.assign(Yg(e),{error:Yg(`${e}:error`),trace:t})}(e)}}function Qg(e){if(null!=e&&0!==(e=e.trim()).length)return e}function em(e,t){const r={[Symbol.iterator]:()=>r,next:()=>{const r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function tm(e){return sh(st(Se.decode(`z${e}`)))}Yg.formatters.b=e=>null==e?"undefined":Se.baseEncode(e),Yg.formatters.t=e=>null==e?"undefined":he.baseEncode(e),Yg.formatters.m=e=>null==e?"undefined":ke.baseEncode(e),Yg.formatters.p=e=>null==e?"undefined":e.toString(),Yg.formatters.c=e=>null==e?"undefined":e.toString(),Yg.formatters.k=e=>null==e?"undefined":e.toString(),Yg.formatters.a=e=>null==e?"undefined":e.toString(),Yg.formatters.e=e=>null==e?"undefined":Qg(e.stack)??Qg(e.message)??e.toString();class rm{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 em(this.set.entries(),(e=>{const t=tm(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{const r=tm(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return em(this.set.values(),(e=>tm(e)))}intersection(e){const t=new rm;for(const r of e)this.has(r)&&t.add(r);return t}difference(e){const t=new rm;for(const r of this)e.has(r)||t.add(r);return t}union(e){const t=new rm;for(const r of e)t.add(r);for(const e of this)t.add(e);return t}}const nm={},om=e=>{e.addEventListener("message",(t=>{om.dispatchEvent("message",e,t)})),null!=e.port&&e.port.addEventListener("message",(t=>{om.dispatchEvent("message",e,t)}))};om.addEventListener=(e,t)=>{null==nm[e]&&(nm[e]=[]),nm[e].push(t)},om.removeEventListener=(e,t)=>{null!=nm[e]&&(nm[e]=nm[e].filter((e=>e===t)))},om.dispatchEvent=function(e,t,r){null!=nm[e]&&nm[e].forEach((e=>e(t,r)))};const sm=om,im="lock:worker:request-read",am="lock:worker:release-read",cm="lock:master:grant-read",lm="lock:worker:request-write",um="lock:worker:release-write",hm="lock:master:grant-write",dm=(e,t,r,n,o)=>(s,i)=>{if(i.data.type!==r)return;const a={type:i.data.type,name:i.data.name,identifier:i.data.identifier};e.dispatchEvent(new MessageEvent(t,{data:{name:a.name,handler:async()=>{s.postMessage({type:o,name:a.name,identifier:a.identifier}),await new Promise((e=>{const t=r=>{if(null==r?.data)return;const o=r.data.type,i=(r.data.name,r.data.identifier);o===n&&i===a.identifier&&(s.removeEventListener("message",t),e())};s.addEventListener("message",t)}))}}}))},pm=(e,t,r,n)=>async()=>{const o=Math.random().toString().substring(2);return globalThis.postMessage({type:t,identifier:o,name:e}),new Promise((t=>{const s=i=>{if(null==i?.data)return;const a=i.data.type,c=i.data.identifier;a===r&&c===o&&(globalThis.removeEventListener("message",s),t((()=>{globalThis.postMessage({type:n,identifier:o,name:e})})))};globalThis.addEventListener("message",s)}))},fm={singleProcess:!1},gm={};let mm;async function ym(e,t){let r;const n=new Promise((e=>{r=e}));return e.add((async()=>Ag((async()=>{await new Promise((e=>{r((()=>{e()}))}))})(),{milliseconds:t.timeout}))),n}const bm={name:"lock",concurrency:1/0,timeout:846e5,singleProcess:!1};var wm,vm,Em;function Sm(e,t){const r=wm.decode(t);null!=r.publicKey&&null==e.publicKey&&(e=oh(Gu(r.publicKey)));const n=new Map,o=BigInt(Date.now());for(const[e,t]of r.tags.entries())null!=t.expiry&&t.expiry({multiaddr:Is(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,r={})=>{const n={key:"",value:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.key=e.string();break;case 2:n.value=e.bytes();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(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),Em.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t,r={})=>{const n={key:""},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.key=e.string();break;case 2:n.value=Em.codec().decode(e,e.uint32(),{limits:r.limits?.value});break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(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),vm.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,o]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:n,value:o},r);if(null!=t.tags&&0!==t.tags.size)for(const[n,o]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:n,value:o},r);!1!==n.lengthDelimited&&r.ldelim()}),((t,r,n={})=>{const o={addresses:[],protocols:[],metadata:new Map,tags:new Map},s=null==r?t.len:t.pos+r;for(;t.pos>>3){case 1:if(null!=n.limits?.addresses&&o.addresses.length===n.limits.addresses)throw new Er('Decode error - map field "addresses" had too many elements');o.addresses.push(vm.codec().decode(t,t.uint32(),{limits:n.limits?.addresses$}));break;case 2:if(null!=n.limits?.protocols&&o.protocols.length===n.limits.protocols)throw new Er('Decode error - map field "protocols" had too many elements');o.protocols.push(t.string());break;case 4:o.publicKey=t.bytes();break;case 5:o.peerRecordEnvelope=t.bytes();break;case 6:{if(null!=n.limits?.metadata&&o.metadata.size===n.limits.metadata)throw new Sr('Decode error - map field "metadata" had too many elements');const r=e.Peer$metadataEntry.codec().decode(t,t.uint32());o.metadata.set(r.key,r.value);break}case 7:{if(null!=n.limits?.tags&&o.tags.size===n.limits.tags)throw new Sr('Decode error - map field "tags" had too many elements');const r=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:n.limits?.tags$value}});o.tags.set(r.key,r.value);break}default:t.skipType(7&r)}}return o}))),n),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(wm||(wm={})),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,r={})=>{const n={multiaddr:g(0)},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.multiaddr=e.bytes();break;case 2:n.isCertified=e.bool();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(vm||(vm={})),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,r={})=>{const n={value:0},o=null==t?e.len:e.pos+t;for(;e.pos>>3){case 1:n.value=e.uint32();break;case 2:n.expiry=e.uint64();break;default:e.skipType(7&t)}}return n}))),t),e.encode=t=>qt(t,e.codec()),e.decode=(t,r)=>K(t,e.codec(),r)}(Em||(Em={}));const Am="/",km=(new TextEncoder).encode(Am),Cm=km[0];class Im{_buf;constructor(e,t){if("string"==typeof e)this._buf=xt(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]!==Cm)throw new Error("Invalid key")}toString(e="utf8"){return Zr(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new Im(e.join(Am))}static random(){return new Im(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Im(e):"function"==typeof e.uint8Array?new Im(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=km),this._buf[0]!==Cm){const e=new Uint8Array(this._buf.byteLength+1);e.fill(Cm,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Cm;)this._buf=this._buf.subarray(0,-1)}less(e){const t=this.list(),r=e.list();for(let e=0;eo)return!1}return t.lengthe.namespaces())),[].concat(...t))]);var t}}const xm="/peers/";function Tm(e){if(!$o(e)||null==e.type)throw new Ws("Invalid PeerId");const t=e.toCID().toString();return new Im(`${xm}${t}`)}async function _m(e,t,r){const n=new Map;for(const o of r){if(null==o)continue;if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=Is(o.multiaddr)),!Cs(o.multiaddr))throw new Ws("Multiaddr was invalid");if(!await t(e,o.multiaddr))continue;const r=o.isCertified??!1,s=o.multiaddr.toString(),i=n.get(s);null!=i?o.isCertified=i.isCertified||r:n.set(s,{multiaddr:o.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 Nm(e,t,r,n){if(null==t)throw new Ws("Invalid PeerData");if(null!=t.publicKey&&null!=e.publicKey&&!t.publicKey.equals(e.publicKey))throw new Ws("publicKey bytes do not match peer id publicKey bytes");const o=n.existingPeer;if(null!=o&&!e.equals(o.id))throw new Ws("peer id did not match existing peer id");let s,i=o?.addresses??[],a=new Set(o?.protocols??[]),c=o?.metadata??new Map,l=o?.tags??new Map,u=o?.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&&(a=new Set(t.protocols)),null!=t.metadata&&(c=Pm(t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata),{validate:Lm})),null!=t.tags&&(l=Pm(t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),{validate:Bm,map:Om})),null!=t.peerRecordEnvelope&&(u=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&&(a=new Set([...a,...t.protocols])),null!=t.metadata){const e=t.metadata instanceof Map?[...t.metadata.entries()]:Object.entries(t.metadata);for(const[t,r]of e)null==r?c.delete(t):c.set(t,r);c=Pm([...c.entries()],{validate:Lm})}if(null!=t.tags){const e=t.tags instanceof Map?[...t.tags.entries()]:Object.entries(t.tags),r=new Map(l);for(const[t,n]of e)null==n?r.delete(t):r.set(t,n);l=Pm([...r.entries()],{validate:Bm,map:Om})}null!=t.peerRecordEnvelope&&(u=t.peerRecordEnvelope)}null!=o?.id.publicKey?s=Wu(o.id.publicKey):null!=t.publicKey?s=Wu(t.publicKey):null!=e.publicKey&&(s=Wu(e.publicKey));const h={addresses:await _m(e,n.addressFilter??(async()=>!0),i),protocols:[...a.values()].sort(((e,t)=>e.localeCompare(t))),metadata:c,tags:l,publicKey:s,peerRecordEnvelope:u};return"RSA"!==e.type&&delete h.publicKey,h}function Pm(e,t){const r=new Map;for(const[r,n]of e)null!=n&&t.validate(r,n);for(const[n,o]of e.sort((([e],[t])=>e.localeCompare(t))))null!=o&&r.set(n,t.map?.(n,o)??o);return r}function Lm(e,t){if("string"!=typeof e)throw new Ws("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new Ws("Metadata value must be a Uint8Array")}function Bm(e,t){if("string"!=typeof e)throw new Ws("Tag name must be a string");if(null!=t.value){if(parseInt(`${t.value}`,10)!==t.value)throw new Ws("Tag value must be an integer");if(t.value<0||t.value>100)throw new Ws("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt(`${t.ttl}`,10)!==t.ttl)throw new Ws("Tag ttl must be an integer");if(t.ttl<0)throw new Ws("Tag ttl must be between greater than 0")}}function Om(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 Rm(e,t){const r=e.toString().split("/")[2];return Sm(ih(yt.parse(r,he)),t)}class Dm{peerId;datastore;lock;addressFilter;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.lock=function(e){const t=Object.assign({},bm,e);return null==mm&&(mm=(e=>{if(e=Object.assign({},fm,e),Boolean(globalThis.document)||e.singleProcess){const e=new EventTarget;return sm.addEventListener("message",dm(e,"requestReadLock",im,am,cm)),sm.addEventListener("message",dm(e,"requestWriteLock",lm,um,hm)),e}return{isWorker:!0,readLock:e=>pm(e,im,cm,am),writeLock:e=>pm(e,lm,hm,um)}})(t),!0!==mm.isWorker&&(mm.addEventListener("requestReadLock",(e=>{null!=gm[e.data.name]&&gm[e.data.name].readLock().then((async t=>e.data.handler().finally((()=>{t()}))))})),mm.addEventListener("requestWriteLock",(async e=>{null!=gm[e.data.name]&&gm[e.data.name].writeLock().then((async t=>e.data.handler().finally((()=>{t()}))))})))),null==gm[t.name]&&(gm[t.name]=((e,t)=>{if(!0===mm.isWorker)return{readLock:mm.readLock(e,t),writeLock:mm.writeLock(e,t)};const r=new Cg({concurrency:1});let n;return{async readLock(){if(null!=n)return ym(n,t);n=new Cg({concurrency:t.concurrency,autoStart:!1});const e=n,o=ym(n,t);return r.add((async()=>{e.start(),await e.onIdle().then((()=>{n===e&&(n=null)}))})),o},writeLock:async()=>(n=null,ym(r,t))}})(t.name,t)),gm[t.name]}({name:"peer-store",singleProcess:!0})}async has(e){return this.datastore.has(Tm(e))}async delete(e){if(this.peerId.equals(e))throw new Ws("Cannot delete self peer");await this.datastore.delete(Tm(e))}async load(e){return Sm(e,await this.datastore.get(Tm(e)))}async save(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"patch",{addressFilter:this.addressFilter});return this.#L(e,o,r,n)}async patch(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"patch",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,o,r,n)}async merge(e,t){const{existingBuf:r,existingPeer:n}=await this.#P(e),o=await Nm(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:n});return this.#L(e,o,r,n)}async*all(e){for await(const{key:t,value:r}of this.datastore.query(function(e){return null==e?{}:{prefix:xm,filters:(e.filters??[]).map((e=>({key:t,value:r})=>e(Rm(t,r)))),orders:(e.orders??[]).map((e=>(t,r)=>e(Rm(t.key,t.value),Rm(r.key,r.value))))}}(e??{}))){const e=Rm(t,r);e.id.equals(this.peerId)||(yield e)}}async#P(e){try{const t=await this.datastore.get(Tm(e));return{existingBuf:t,existingPeer:Sm(e,t)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}return{}}async#L(e,t,r,n){const o=wm.encode(t);return null!=r&&Cn(o,r)?{peer:Sm(e,o),previous:n,updated:!1}:(await this.datastore.put(Tm(e),o),{peer:Sm(e,o),previous:n,updated:!0})}}class Um{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 Dm(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){this.log.trace("forEach await read lock");const r=await this.store.lock.readLock();this.log.trace("forEach got read lock");try{for await(const r of this.store.all(t))e(r)}finally{this.log.trace("forEach release read lock"),r()}}async all(e){this.log.trace("all await read lock");const t=await this.store.lock.readLock();this.log.trace("all got read lock");try{return await An(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.#B(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.#B(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.#B(e,r),r.peer}finally{this.log.trace("merge release write lock"),r()}}async consumePeerRecord(e,t){const r=await cp.openAndCertify(e,ip.DOMAIN),n=ih(r.publicKey.toCID());if(!1===t?.equals(n))return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",t,n),!1;const o=ip.createFromProtobuf(r.payload);let s;try{s=await this.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=s?.peerRecordEnvelope){const e=await cp.createFromProtobuf(s.peerRecordEnvelope),t=ip.createFromProtobuf(e.payload);if(t.seqNumber>=o.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",t.seqNumber,o.seqNumber),!1}return await this.patch(o.peerId,{peerRecordEnvelope:e,addresses:o.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}#B(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}}Error,Error,Error,Error,Error,Error;class Mm extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=Mm.name;code=Mm.code;constructor(e="Not Found"){super(e)}}Error;const Fm=function(e){if(null!=e[Symbol.asyncIterator])return(async()=>{for await(const t of e);})();for(const t of e);},$m=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:o,done:s}=n.next();if(!0===s)return function*(){}();const i=t(o,r++);if("function"==typeof i.then)return async function*(){await i&&(yield o);for await(const e of n)await t(e,r++)&&(yield e)}();const a=t;return function*(){!0===i&&(yield o);for(const e of n)a(e,r++)&&(yield e)}()},qm=function(e,t){return null!=e[Symbol.asyncIterator]?async function*(){const r=await An(e);yield*r.sort(t)}():function*(){const r=An(e);yield*r.sort(t)}()},Hm=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 jm{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 Fm(this.putMany(e,r)),e=[],await Fm(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=$m(r,(e=>e.key.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>$m(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>qm(e,t)),r)),null!=e.offset){let t=0;const n=e.offset;r=$m(r,(()=>t++>=n))}return null!=e.limit&&(r=Hm(r,e.limit)),r}queryKeys(e,t){let r=this._allKeys(e,t);if(null!=e.prefix){const t=e.prefix;r=$m(r,(e=>e.toString().startsWith(t)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>$m(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>qm(e,t)),r)),null!=e.offset){const t=e.offset;let n=0;r=$m(r,(()=>n++>=t))}return null!=e.limit&&(r=Hm(r,e.limit)),r}}class Vm extends jm{data;constructor(){super(),this.data=new Map}put(e,t){return this.data.set(e.toString(),t),e}get(e){const t=this.data.get(e.toString());if(null==t)throw new Mm;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 Im(e),value:t}}*_allKeys(){for(const e of this.data.keys())yield new Im(e)}}const zm=e=>e;function Km(e,t){const r=e.getPeerId();return null!=r&&nh(r).equals(t)&&(e=e.decapsulate(Is(`/p2p/${t.toString()}`))),e}class Gm{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??zm,this._updatePeerStoreAddresses=function(e){let t;return function(){clearTimeout(t),t=setTimeout((function(){t=void 0,e()}),1e3)}}(this._updatePeerStoreAddresses.bind(this)),e.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),e.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){const e=this.getAnnounceAddrs().concat(this.components.transportManager.getAddrs()).concat([...this.observed.entries()].filter((([e,t])=>t.confident)).map((([e])=>Is(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=>Is(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>Is(e)))}getObservedAddrs(){return Array.from(this.observed).map((([e])=>Is(e)))}addObservedAddr(e){const t=(e=Km(e,this.components.peerId)).toString();this.observed.has(t)||this.observed.set(t,{confident:!1})}confirmObservedAddr(e){const t=(e=Km(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=Km(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=>Is(e)))).map((e=>!0===e.protos().pop()?.path||e.getPeerId()===this.components.peerId.toString()?e:e.encapsulate(`/p2p/${this.components.peerId.toString()}`)))}}function Wm(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}var Jm;!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(Jm||(Jm={}));class Xm extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}}class Ym extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}}class Zm extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}}class Qm extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}}class ey extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}}class ty extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}}class ry extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}}class ny extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}}class oy extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}}class sy extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}}class iy extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}}class ay extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}}class cy extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}}class ly extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}}class uy{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=Zg())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter((e=>Wm(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 hy=["metrics","connectionProtector","dns"],dy=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function py(e){return Array.isArray(e?.[Ju])?e[Ju]:[]}function fy(e){return Array.isArray(e?.[Xu])?e[Xu]:[]}function gy(e){return e?.[Symbol.toStringTag]??e?.toString()??"unknown"}function my(e={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{const t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(pp(`${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}}class yy{map;constructor(e){if(this.map=new Map,null!=e)for(const[t,r]of e.entries())this.map.set(t.toString(),{key:t,value:r})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return em(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach(((t,r)=>{e(t.value,t.key,this)}))}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return em(this.map.values(),(e=>e.key))}values(){return em(this.map.values(),(e=>e.value))}get size(){return this.map.size}}function by(e){if($o(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:nh(r),e.forEach((e=>{if(!Cs(e))throw new si("Invalid multiaddr");const r=e.getPeerId();if(null==r){if(null!=t)throw new Ws("Multiaddrs must all have the same peer id or have no peer id")}else{const e=nh(r);if(!0!==t?.equals(e))throw new Ws("Multiaddrs must all have the same peer id or have no peer id")}}))}return{peerId:t,multiaddrs:e}}const wy=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"],vy={maxConnections:100,allow:[]};class Ey{maxConnections;connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.maxConnections=t.maxConnections??vy.maxConnections,this.allow=t.allow??vy.allow,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}async _maybePruneConnections(){const e=this.connectionManager.getConnections(),t=e.length;if(this.log("checking max connections limit %d/%d",t,this.maxConnections),t<=this.maxConnections)return;const r=new yy;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){"NotFoundError"!==e.name&&this.log.error("error loading peer tags",e)}}}const n=this.sortConnections(e,r),o=Math.max(t-this.maxConnections,0),s=[];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())))||s.push(e),s.length===o)break;await Promise.all(s.map((async e=>{await async function(e,t){const r=e?.streams?.map((e=>e.protocol))??[],n=t?.closableProtocols??wy;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:s})}sortConnections(e,t){return e.sort(((e,t)=>{const r=e.timeline.open,n=t.timeline.open;return rn?-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{const n=t.get(e.remotePeer)??0,o=t.get(r.remotePeer)??0;return n>o?1:n{function a(){r?.removeEventListener("abort",u),e.removeEventListener(t,c),null!=n?.errorEvent&&e.removeEventListener(n.errorEvent,l)}const c=e=>{try{if(!1===n?.filter?.(e))return}catch(e){return a(),void i(e)}a(),s(e)},l=e=>{a(),i(e.detail)},u=()=>{a(),i(o)};r?.addEventListener("abort",u),e.addEventListener(t,c),null!=n?.errorEvent&&e.addEventListener(n.errorEvent,l)}))}class Iy{deferred;signal;constructor(e){this.signal=e,this.deferred=$n(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Ks)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}}class xy{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 Ks),this.cleanup())}async join(e={}){const t=new Iy(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 ch(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 Ty extends xo{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??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{for(let t=0;t(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{e.abort(new Ks)})),this.clear()}async onEmpty(e){0!==this.size&&await Cy(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.sizethis.size{null!=e?this.abort():this.clear(),t.end(e)},n=e=>{null!=e.detail&&t.push(e.detail)},o=e=>{r(e.detail)},s=()=>{r()},i=()=>{r(new Ks("Queue aborted"))};this.addEventListener("completed",n),this.addEventListener("error",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",i);try{yield*t}finally{this.removeEventListener("completed",n),this.removeEventListener("error",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",i),r()}}}class _y extends Ty{constructor(e={}){super({...e,sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority{e.detail.name!==Ks.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){const{peerId:r,multiaddrs:n}=by(e),o=Array.from(this.connections.values()).flat().find((e=>!0!==t.force&&(!!e.remotePeer.equals(r)||n.find((t=>t.equals(e.remoteAddr))))));if("open"===o?.status)return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new pg("dial-queue:already-connected")),o;const s=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!=s){this.log("joining existing dial target for %p",r);for(const e of n)s.options.multiaddrs.add(e.toString());return t.onProgress?.(new pg("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new pi("Dial queue is full");return this.log("creating dial target for %p",r,n.map((e=>e.toString()))),t.onProgress?.(new pg("dial-queue:add-to-dial-queue")),this.queue.add((async e=>{e?.onProgress?.(new pg("dial-queue:start-dial"));const t=this.createDialAbortController(e?.signal);let n;try{n=await this.calculateMultiaddrs(r,e?.multiaddrs,{...e,signal:t}),e?.onProgress?.(new pg("dial-queue:calculated-addresses",n)),n.map((({multiaddr:e})=>e.toString())).forEach((t=>{e?.multiaddrs.add(t)}))}catch(e){throw t.clear(),e}try{let o=0;const s=[];for(const i of n){if(o===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",o,r),new pi("Peer had more than maxPeerAddrsToDial");o++;try{const n=await this.components.transportManager.dial(i.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",i.multiaddr);try{await this.components.peerStore.merge(n.remotePeer,{multiaddrs:[n.remoteAddr],metadata:{[Ay]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}return n}catch(e){if(this.log.error("dial failed to %a",i.multiaddr,e),null!=r)try{await this.components.peerStore.merge(r,{metadata:{[Sy]:xt(Date.now().toString())}})}catch(e){this.log.error("could not update last dial failure key for %p",r,e)}if(t.aborted)throw new hi(e.message);s.push(e)}}if(1===s.length)throw s[0];throw new AggregateError(s,"All multiaddr dials failed")}finally{t.clear()}}),{peerId:r,priority:t.priority??zy,multiaddrs:new Set(n.map((e=>e.toString()))),signal:t.signal,onProgress:t.onProgress})}createDialAbortController(e){return Ny([AbortSignal.timeout(this.dialTimeout),this.shutDownController.signal,e])}async calculateMultiaddrs(e,t=new Set,r={}){const n=[...t].map((e=>({multiaddr:Is(e),isCertified:!1})));if(null!=e){if(this.components.peerId.equals(e))throw new pi("Tried to dial self");if(!0===await(this.components.connectionGater.denyDialPeer?.(e)))throw new ny("The dial request is blocked by gater.allowDialPeer");if(0===n.length){this.log("loading multiaddrs for %p",e);try{const t=await this.components.peerStore.get(e);n.push(...t.addresses),this.log("loaded multiaddrs for %p",e,n.map((({multiaddr:e})=>e.toString())))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===n.length){this.log("looking up multiaddrs for %p in the peer routing",e);try{const t=await this.components.peerRouting.findPeer(e);this.log("found multiaddrs for %p in the peer routing",e,n.map((({multiaddr:e})=>e.toString()))),n.push(...t.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(t){"NoPeerRoutersError"!==t.name&&this.log.error("looking up multiaddrs for %p in the peer routing failed",e,t)}}}let o=(await Promise.all(n.map((async e=>{const t=await async function(e,t){let r=!1;for(const t of ks.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()}`;o=o.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 s=o.filter((t=>{if(null==this.components.transportManager.dialTransportForMultiaddr(t.multiaddr))return!1;const r=t.multiaddr.getPeerId();return null==e||null==r||e.equals(r)})),i=new Map;for(const e of s){const t=e.multiaddr.toString(),r=i.get(t);null==r?i.set(t,e):r.isCertified=r.isCertified||e.isCertified||!1}const a=[...i.values()];if(0===a.length)throw new oy("The dial request has no valid addresses");const c=[];for(const e of a)null!=this.components.connectionGater.denyDialMultiaddr&&await this.components.connectionGater.denyDialMultiaddr(e.multiaddr)||c.push(e);const l=null==this.addressSorter?c.sort(Py).sort(By).sort(Oy).sort(Ly):c.sort(this.addressSorter);if(0===l.length)throw new ny("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map((({multiaddr:e})=>e.toString()))),this.log.trace("addresses for %p after filtering",e??"unknown peer",l.map((({multiaddr:e})=>e.toString()))),l}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{const r=await this.calculateMultiaddrs(void 0,new Set(e.map((e=>e.toString()))),t);return!1!==t.runOnLimitedConnection||null!=r.find((e=>!Xp.matches(e.multiaddr)))}catch(e){this.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}}const Dy="keep-alive";class Uy extends Ty{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}var My=__webpack_require__(5617);const Fy=Object.prototype.toString,$y=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);class qy extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const Hy=(e,t,r)=>{const n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};class jy{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Uy({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}async maybeReconnect(e){if(!this.started)return;const t=await this.peerStore.get(e);Vy(t)&&(this.queue.has(e)||this.queue.add((async t=>{await async function(e,t){return new Promise(((r,n)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const o=My.operation(t),s=()=>{o.stop(),n(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",s,{once:!0});const i=()=>{t.signal?.removeEventListener("abort",s),o.stop()};o.attempt((async s=>{try{const t=await e(s);i(),r(t)}catch(e){try{if(!(e instanceof Error))throw new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(e instanceof qy)throw e.originalError;if(e instanceof TypeError&&!function(e){var t;return!(!e||(t=e,"[object Error]"!==Fy.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:$y.has(e.message))}(e))throw e;if(Hy(e,s,t),await t.shouldRetry(e)||(o.stop(),n(e)),await t.onFailedAttempt(e),!o.retry(e))throw o.mainError()}catch(e){Hy(e,s,t),i(),n(e)}}}))}))}((async r=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:t?.signal})}catch(t){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,r,this.retries,t),t}}),{signal:t?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})}),{peerId:e}).catch((async r=>{this.log.error("failed to reconnect to %p - %e",e,r);const n={};[...t.tags.keys()].forEach((e=>{e.startsWith(Dy)&&(n[e]=void 0)})),await this.peerStore.merge(e,{tags:n}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})})).catch((async t=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,t)})))}start(){this.started=!0}async afterStart(){Promise.resolve().then((async()=>{const e=await this.peerStore.all({filters:[e=>Vy(e)]});await Promise.all(e.map((async e=>{await this.connectionManager.openConnection(e.id).catch((e=>{this.log.error(e)}))})))})).catch((e=>{this.log.error(e)}))}stop(){this.started=!1,this.queue.abort()}}function Vy(e){for(const t of e.tags.keys())if(t.startsWith(Dy))return!0;return!1}const zy=50;class Ky{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??100,this.maxConnections<1)throw new Ws("Connection Manager maxConnections must be greater than 0");this.connections=new yy,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map((e=>Is(e))),this.deny=(t.deny??[]).map((e=>Is(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??10,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new xf({points:t.inboundConnectionThreshold??5,duration:1}),this.connectionPruner=new Ey({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{maxConnections:this.maxConnections,allow:this.allow}),this.dialQueue=new Ry(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??50,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??5e3,resolvers:t.resolvers??{dnsaddr:Rg},connections:this.connections}),this.reconnectQueue=new jy({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{const e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(const t of this.connections.values())for(const r of t)e[r.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t)for(const t of r.streams){const r=`${t.direction} ${t.protocol??"unnegotiated"}`;e[r]=(e[r]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{const e={};for(const t of this.connections.values())for(const r of t){const t={};for(const e of r.streams){const r=`${e.direction} ${e.protocol??"unnegotiated"}`;t[r]=(t[r]??0)+1}for(const[r,n]of Object.entries(t))e[r]=e[r]??[],e[r].push(n)}const t={};for(let[r,n]of Object.entries(e)){n=n.sort(((e,t)=>e-t));const e=Math.floor(.9*n.length);t[r]=n[e]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Wm(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStart&&await e.beforeStart()}))),await Promise.all(t.map((async e=>{await e.start()}))),await Promise.all(t.map((async e=>{null!=e.afterStart&&await e.afterStart()})))}(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await async function(...e){const t=[];for(const r of e)Wm(r)&&t.push(r);await Promise.all(t.map((async e=>{null!=e.beforeStop&&await e.beforeStop()}))),await Promise.all(t.map((async e=>{await e.stop()}))),await Promise.all(t.map((async e=>{null!=e.afterStop&&await e.afterStop()})))}(this.reconnectQueue,this.dialQueue,this.connectionPruner);const e=[];for(const t of this.connections.values())for(const r of t)e.push((async()=>{try{await r.close()}catch(e){this.log.error(e)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}async _onConnect(e){const{detail:t}=e;if(!this.started)return void await t.close();if("open"!==t.status)return;const r=t.remotePeer,n=!this.connections.has(r),o=this.connections.get(r)??[];o.push(t),this.connections.set(r,o),null!=r.publicKey&&"RSA"===r.type&&await this.peerStore.patch(r,{publicKey:r.publicKey}),n&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){const{detail:t}=e,r=t.remotePeer,n=(this.connections.get(r)??[]).filter((e=>e.id!==t.id));this.connections.set(r,n),0===n.length&&(this.log("onDisconnect remove all connections for peer %p",r),this.connections.delete(r),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(null!=e)return this.connections.get(e)??[];let t=[];for(const e of this.connections.values())t=t.concat(e);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new di("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();const{peerId:r}=by(e);if(this.peerId.equals(r))throw new oi("Can not dial self");if(null!=r&&!0!==t.force){this.log("dial %p",r);const e=this.getConnections(r).find((e=>null==e.limits));if(null!=e)return this.log("had an existing non-limited connection to %p",r),t.onProgress?.(new pg("dial-queue:already-connected")),e}const n=await this.dialQueue.dial(e,{...t,priority:t.priority??zy});if("open"!==n.status)throw new Zs("Remote closed connection during opening");let o=this.connections.get(n.remotePeer);null==o&&(o=[],this.connections.set(n.remotePeer,o));let s=!1;for(const e of o)if(e.id===n.id&&(s=!0),!0!==t.force&&e.id!==n.id&&e.remoteAddr.equals(n.remoteAddr))return n.abort(new si("Duplicate multiaddr connection")),e;return s||o.push(n),n}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){const r=this.connections.get(e)??[];await Promise.all(r.map((async e=>{try{await e.close(t)}catch(t){e.abort(t)}})))}async acceptIncomingConnection(e){if(this.deny.some((t=>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({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>Is(e)))})))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}}class Gy{movingAverage;variance;deviation;forecast;timespan;previousTime;constructor(e){this.timespan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timespan)}push(e,t=Date.now()){if(null!=this.previousTime){const r=this.alpha(t,this.previousTime),n=e-this.movingAverage,o=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class Wy{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;constructor(e={}){this.success=new Gy(e.interval??5e3),this.failure=new Gy(e.interval??5e3),this.next=new Gy(e.interval??5e3),this.failureMultiplier=e.failureMultiplier??2,this.timeoutMultiplier=e.timeoutMultiplier??1.2,this.minTimeout=e.minTimeout??2e3,null!=e.metricName&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){const t=Math.max(Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier)),this.minTimeout),r=AbortSignal.timeout(t),n=Ny([e.signal,r]);return n.start=Date.now(),n.timeout=t,n}cleanUp(e){const t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}}class Jy{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??"ipfs"}/ping/1.0.0`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??1e4,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??!0,this.timeout=new Wy({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[Ju]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((e=>{Promise.resolve().then((async()=>{let t=Date.now();try{const r=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),n=ph(await e.newStream(this.protocol,{signal:r,runOnLimitedConnection:!0}));t=Date.now(),await Promise.all([n.write(Wf(32),{signal:r}),n.read(32,{signal:r})]),e.rtt=Date.now()-t,await n.unwrap().close({signal:r})}catch(r){if("UnsupportedProtocolError"!==r.name)throw r;e.rtt=(Date.now()-t)/2}})).catch((t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){this.abortController?.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class Xy{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(0===this.routers.length)throw new Zm("No content routers available");const r=this,n=new rm;for await(const o of zn(...r.routers.map((r=>r.findProviders(e,t)))))null!=o&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),n.has(o.id)||(n.add(o.id),yield o))}async provide(e,t={}){if(0===this.routers.length)throw new Zm("No content 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 di;await Promise.all(this.routers.map((async n=>{await n.put(e,t,r)})))}async get(e,t){if(!this.isStarted())throw new di;return Promise.any(this.routers.map((async r=>r.get(e,t))))}}class Yy{fp;h;seed;constructor(e,t,r,n=2){if(n>64)throw new TypeError("Invalid Fingerprint Size");const o=t.hashV(e,r),s=g(n);for(let e=0;ee.equals(t)))}add(e){if(!(e instanceof Yy))throw new TypeError("Invalid Fingerprint");for(let t=0;te.equals(t)));return t>-1&&(this.contents[t]=null,!0)}}const eb={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},tb={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},rb=new globalThis.TextEncoder;__webpack_require__(8437);const nb={hash:e=>Number(function(e,{size:t=32,utf8Buffer:r}={}){if(!eb[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=eb[t];let o=tb[t],s=e;for(;s.length>0;){const e=rb.encodeInto(s,r);s=s.slice(e.read);for(let s=0;sfunction(e){let t=e.toString(16);return t.length%2==1&&(t=`0${t}`),xt(t,"base16")}(nb.hash(e,t))};class ob{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??nb,this.seed=e.seed??Zy(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=xt(e));const t=new Yy(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 Qy(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new Qy(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;const o=[r,n];let s=o[Zy(0,o.length-1)];null==this.buckets[s]&&(this.buckets[s]=new Qy(this.bucketSize));for(let e=0;e<500;e++){const e=this.buckets[s].swap(t);if(null!=e&&(s=(s^e.hash())%this.filterSize,null==this.buckets[s]&&(this.buckets[s]=new Qy(this.bucketSize)),this.buckets[s].add(e)))return this.count++,!0}return!1}has(e){"string"==typeof e&&(e=xt(e));const t=new Yy(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 o=(r^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){"string"==typeof e&&(e=xt(e));const t=new Yy(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 o=(r^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}const sb={1:.5,2:.84,4:.95,8:.98};function ib(e,t=.001){const r=function(e=.001){return e>.002?2:e>1e-5?4:8}(t),n=sb[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}class ab{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??nb,this.seed=e.seed??Zy(0,Math.pow(2,10)),this.filterSeries=[new ob({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=xt(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 ob({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=xt(e));for(let t=0;te+t.count),0)}}const cb=globalThis.CustomEvent??Event;class lb{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[]}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(0===this.routers.length)throw new Qm("No peer routers available");if(e.toString()===this.peerId.toString())throw new ey("Should not try to find self");const r=this,n=zn(...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 ni}async*getClosestPeers(e,t={}){if(0===this.routers.length)throw new Qm("No peer routers available");const r=this,n=function(e,t=.001,r){return new ab({...ib(1024,t),...r??{}})}();for await(const o of async function*(e,t={}){let r=t.concurrency??1/0;r<1&&(r=1/0);const n=null!=t.ordered&&t.ordered,o=new EventTarget,s=[];let i,a=$n(),c=$n(),l=!1,u=!1;function h(){return n?s[0]?.done:Boolean(s.find((e=>e.done)))}function*d(){for(;s.length>0&&s[0].done;){const e=s[0];if(s.shift(),!e.ok)throw u=!0,a.resolve(),e.err;yield e.value,a.resolve()}}function*p(){for(;h();)for(let e=0;e{c.resolve()})),Promise.resolve().then((async()=>{try{for await(const t of e){if(s.length===r&&(a=$n(),await a.promise),u)break;const e={done:!1};s.push(e),t().then((t=>{e.done=!0,e.ok=!0,e.value=t,o.dispatchEvent(new cb("task-complete"))}),(t=>{e.done=!0,e.err=t,o.dispatchEvent(new cb("task-complete"))}))}l=!0,o.dispatchEvent(new cb("task-complete"))}catch(e){i=e,o.dispatchEvent(new cb("task-complete"))}}));;){if(h()||(c=$n(),await c.promise),null!=i)throw i;if(n?yield*d():yield*p(),l&&0===s.length)break}}(async function*(){const n=zn(...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!=o&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs}),n.has(o.id.toMultihash().bytes)||(n.add(o.id.toMultihash().bytes),yield o))}}class ub extends xo{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;const t=Ny([this.shutdownController.signal,e?.signal]);try{for(;;){this.needNext?.resolve(),this.needNext=$n();const e=await Cy(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=Ny([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=Wf(32);let n=Date.now();for await(const o 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",o.id,Date.now()-n,this.walkers),r++,this.safeDispatchEvent("walk:peer",{detail:o}),1===this.walkers&&null!=this.needNext&&(this.log("wait for need next"),await ch(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 hb{log;topologies;handlers;components;constructor(e){this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=e,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){const t=this.handlers.get(e);if(null==t)throw new ty(`No handler registered for protocol ${e}`);return t}getTopologies(e){const t=this.topologies.get(e);return null==t?[]:[...t.values()]}async handle(e,t,r){if(this.handlers.has(e))throw new ry(`Handler already registered for protocol ${e}`);const n=Dg.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 Ws("invalid topology");const r=`${(1e9*Math.random()).toString(36)}${Date.now()}`;let n=this.topologies.get(e);return null==n&&(n=new Map,this.topologies.set(e,n)),n.set(r,t),r}unregister(e){for(const[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){const t=e.detail;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=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){const{peer:t,previous:r}=e.detail,n=(r?.protocols??[]).filter((e=>!t.protocols.includes(e)));for(const e of n){const r=this.topologies.get(e);if(null!=r)for(const e of r.values())!1!==e.filter?.has(t.id)&&(e.filter?.remove(t.id),e.onDisconnect?.(t.id))}}_onPeerIdentify(e){const t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(const e of t){const t=this.topologies.get(e);if(null!=t)for(const e of t.values())null!=r.limits&&!0!==e.notifyOnLimitedConnection||!0!==e.filter?.has(n)&&(e.filter?.add(n),e.onConnect?.(n,r))}}}class db 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 pb{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 db({name:t,metrics:r}):new Map,n}({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??Zf.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){const t=e[Symbol.toStringTag];if(null==t)throw new Ws("Transport must have a valid tag");if(this.transports.has(t))throw new Ws(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){const e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){const e=[];for(const[t,r]of this.listeners)for(this.log("closing listeners for %s",t);r.length>0;){const t=r.pop();null!=t&&e.push(t.close())}await Promise.all(e),this.log("all listeners closed");for(const e of this.listeners.keys())this.listeners.set(e,[]);this.started=!1}async dial(e,t){const r=this.dialTransportForMultiaddr(e);if(null==r)throw new ly(`No transport available for address ${String(e)}`);return t?.onProgress?.(new pg("transport-manager:selected-transport",r[Symbol.toStringTag])),r.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(const t of this.listeners.values())for(const r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(const t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(const t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new di("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 o=n.listenFilter(e),s=[];for(const e of o){this.log("creating listener for %s on %a",r,e);const t=n.createListener({upgrader:this.components.upgrader});let o=this.listeners.get(r)??[];null==o&&(o=[],this.listeners.set(r,o)),o.push(t),t.addEventListener("listening",(()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:t})})),t.addEventListener("close",(()=>{const e=o.findIndex((e=>e===t));o.splice(e,1),this.components.events.safeDispatchEvent("transport:close",{detail:t})})),s.push(t.listen(e))}if(0!==s.length){if(null==(await Promise.allSettled(s)).find((e=>"fulfilled"===e.status))&&this.faultTolerance!==Zf.NO_FATAL)throw new oy(`Transport (${r}) could not listen on any available address`)}else t.push(r)}if(t.length===this.transports.size){const e=`no valid addresses were provided for transports [${t.join(", ")}]`;if(this.faultTolerance===Zf.FATAL_ALL)throw new oy(e);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 fb="/multistream/1.0.0",gb=1024,mb=xt("\n");async function yb(e,t,r){await e.write(t,r)}async function bb(e,t){const r=await async function(e,t){const r=await e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==mb[0])throw t.log.error("Invalid mss message - missing newline",r),new li("Missing newline");return r.sublist(0,-1)}(e,t);return Zr(r.subarray())}async function wb(e,t,r){t=Array.isArray(t)?t:[t],r.log.trace("handle: available protocols %s",t);const n=yh(e,{...r,maxDataLength:gb,maxLengthLength:2});for(;;){r.log.trace("handle: reading incoming string");const e=await bb(n,r);if(r.log.trace('handle: read "%s"',e),e!==fb){if(t.includes(e))return r.log.trace('handle: respond with "%s" for "%s"',e,e),await yb(n,xt(`${e}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',e,e),{stream:n.unwrap(),protocol:e};if("ls"!==e)r.log.trace('handle: respond with "na" for "%s"',e),await yb(n,xt("na\n"),r),r.log('handle: responded with "na" for "%s"',e);else{const o=new _n(...t.map((e=>Ln.single(xt(`${e}\n`)))),xt("\n"));r.log.trace('handle: respond with "%s" for %s',t,e),await yb(n,o,r),r.log.trace('handle: responded with "%s" for %s',t,e)}}else r.log.trace('handle: respond with "%s" for "%s"',fb,e),await yb(n,xt(`${fb}\n`),r),r.log.trace('handle: responded with "%s" for "%s"',fb,e)}}async function vb(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),o=e.source;let s=!1,i=!1;const a=$n();let c=!1,l=!1;const u=$n();let h=!1,d=!1;const p=$n(),f=yh({sink:n,source:o},{...r,maxDataLength:gb});async function g(){if(i)return r.log.trace("optimistic: already negotiating %s stream",t),void await a.promise;i=!0;try{c||(r.log.trace("optimistic: doing send protocol for %s stream",t),await async function(){if(l)await u.promise;else{l=!0;try{r.log.trace('optimistic: write ["%s", "%s", data] in source',fb,t),await f.writeV([xt(`${fb}\n`),xt(`${t}\n`)]),r.log.trace('optimistic: wrote ["%s", "%s", data] in source',fb,t)}finally{c=!0,l=!1,u.resolve()}}}()),h||(r.log.trace("optimistic: doing read protocol for %s stream",t),await async function(){if(d)await p.promise;else{d=!0;try{r.log.trace("optimistic: reading multistream select header");let e=await bb(f,r);if(r.log.trace('optimistic: read multistream select header "%s"',e),e===fb&&(e=await bb(f,r)),r.log.trace('optimistic: read protocol "%s", expecting "%s"',e,t),e!==t)throw new ci("protocol selection failed")}finally{h=!0,d=!1,p.resolve()}}}())}finally{i=!1,s=!0,a.resolve()}}if(e.sink=async e=>{const{sink:n}=f.unwrap();await n(async function*(){let n=!1;for await(const o of e){if(l&&await u.promise,c)yield o;else{l=!0,r.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',fb,t,o.byteLength);const e=`${t}\n`;yield new _n(Uint8Array.from([19]),xt(`${fb}\n`),_(e.length),xt(e),o).subarray(),r.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',fb,t,o.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=>{s||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=>{s||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 ch(Promise.all(r),e?.signal):(s=!0,i=!1,a.resolve()),await t(e)}}return{stream:e,protocol:t}}(e,t[0],r);const n=yh(e,{...r,maxDataLength:gb}),o=t.shift();if(null==o)throw new Error("At least one protocol must be specified");r.log.trace('select: write ["%s", "%s"]',fb,o);const s=xt(`${fb}\n`),i=xt(`${o}\n`);await async function(e,t,r){await e.writeV(t,r)}(n,[s,i],r),r.log.trace("select: reading multistream-select header");let a=await bb(n,r);if(r.log.trace('select: read "%s"',a),a===fb&&(r.log.trace("select: reading protocol response"),a=await bb(n,r),r.log.trace('select: read "%s"',a)),a===o)return{stream:n.unwrap(),protocol:o};for(const e of t){r.log.trace('select: write "%s"',e),await yb(n,xt(`${e}\n`),r),r.log.trace("select: reading protocol response");const t=await bb(n,r);if(r.log.trace('select: read "%s" for "%s"',t,e),t===e)return{stream:n.unwrap(),protocol:e}}throw new ci("protocol selection failed")}const Eb=Symbol.for("@libp2p/connection");class Sb{id;remoteAddr;remotePeer;direction;timeline;multiplexer;encryption;status;limits;log;tags;_newStream;_close;_abort;_getStreams;constructor(e){const{remoteAddr:t,remotePeer:r,newStream:n,close:o,abort:s,getStreams:i}=e;this.id=`${parseInt(String(1e9*Math.random())).toString(36)}${Date.now()}`,this.remoteAddr=t,this.remotePeer=r,this.direction=e.direction,this.status="open",this.timeline=e.timeline,this.multiplexer=e.multiplexer,this.encryption=e.encryption,this.limits=e.limits,this.log=e.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),this._newStream=n,this._close=o,this._abort=s,this._getStreams=i,this.tags=[]}[Symbol.toStringTag]="Connection";[Eb]=!0;get streams(){return this._getStreams()}async newStream(e,t){if("closing"===this.status)throw new Ys("the connection is being closed");if("closed"===this.status)throw new Zs("the connection is closed");if(Array.isArray(e)||(e=[e]),null!=this.limits&&!0!==t?.runOnLimitedConnection)throw new fi("Cannot open protocol stream on limited connection");const r=await this._newStream(e,t);return r.direction="outbound",r}async close(e={}){if("closed"!==this.status&&"closing"!==this.status){if(this.log("closing connection to %a",this.remoteAddr),this.status="closing",null==e.signal){const t=AbortSignal.timeout(500);e={...e,signal:t}}try{this.log.trace("closing underlying transport"),await this._close(e),this.log.trace("updating timeline with close time"),this.status="closed",this.timeline.close=Date.now()}catch(e){this.log.error("error encountered during graceful close of connection to %a",this.remoteAddr,e),this.abort(e)}}}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function Ab(e,t,r){let n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class kb{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;outboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;constructor(e,t){this.components=e,this.connectionEncrypters=new Map,t.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=new Map,t.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??3e3,this.outboundUpgradeTimeout=t.outboundUpgradeTimeout??3e3,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??2e3,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??2e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){const r=this.components.connectionGater[e];if(null!=r&&!0===await r.apply(this.components.connectionGater,t))throw new sy(`The multiaddr connection is blocked by gater.${e}`)}async upgradeInbound(e,t={}){try{if(this.metrics.dials?.increment({inbound:!0}),!await this.components.connectionManager.acceptIncomingConnection(e))throw new iy("connection denied");return await this.shouldBlockConnection("denyInboundConnection",e),await this._performUpgrade(e,"inbound",t)}catch(e){throw this.metrics.errors?.increment({inbound:!0}),e}finally{this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t={}){try{this.metrics.dials?.increment({outbound:!0});const r=e.remoteAddr.getPeerId();let n;return null!=r&&(n=nh(r),await this.shouldBlockConnection("denyOutboundConnection",n,e)),await this._performUpgrade(e,"outbound",t)}catch(e){throw this.metrics.errors?.increment({outbound:!0}),e}}async _performUpgrade(e,t,r){let n,o,s,i,a;const c=Ny([AbortSignal.timeout("inbound"===t?this.inboundUpgradeTimeout:this.outboundUpgradeTimeout),r.signal]);r.signal=c,this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t);let l=e;if(!0!==r?.skipProtection){const n=this.components.connectionProtector;null!=n&&(e.log("protecting the %s connection",t),l=await n.protect(e,r))}try{if(n=l,!0!==r?.skipEncryption){r?.onProgress?.(new pg(`upgrader:encrypt-${t}-connection`)),({conn:n,remotePeer:o,protocol:a}=await("inbound"===t?this._encryptInbound(l,{...r,signal:c}):this._encryptOutbound(l,{...r,signal:c})));const e={...l,...n};await this.shouldBlockConnection("inbound"===t?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",o,e)}else{const r=e.remoteAddr.getPeerId();if(null==r)throw new si(`${t} connection that skipped encryption must have a peer id`);const n=nh(r);a="native",o=n}if(o.equals(this.components.peerId)){const t=new oi("Can not dial self");throw e.abort(t),t}if(s=n,null!=r?.muxerFactory)i=r.muxerFactory;else if(this.streamMuxers.size>0){r?.onProgress?.(new pg(`upgrader:multiplex-${t}-connection`));const e=await("inbound"===t?this._multiplexInbound({...l,...n},this.streamMuxers,r):this._multiplexOutbound({...l,...n},this.streamMuxers,r));i=e.muxerFactory,s=e.stream}}catch(r){throw e.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===t?"from":"to",e.remoteAddr,r),r}finally{c.clear()}return await this.shouldBlockConnection("inbound"===t?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",o,e),e.log("successfully upgraded %s connection",t),this._createConnection({cryptoProtocol:a,direction:t,maConn:e,upgradedConn:s,muxerFactory:i,remotePeer:o,limits:r?.limits})}_createConnection(e){const{cryptoProtocol:t,direction:r,maConn:n,upgradedConn:o,remotePeer:s,muxerFactory:i,limits:a}=e;let c,l,u;null!=i&&(c=i.createStreamMuxer({direction:r,onIncomingStream:e=>{null!=u&&Promise.resolve().then((async()=>{const t=this.components.registrar.getProtocols(),r=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout),{stream:n,protocol:o}=await wb(e,t,{signal:r,log:e.log,yieldBytes:!1});if(null==u)return;u.log("incoming stream opened on %s",o);const i=function(e,t){try{const{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(o,this.components.registrar);if(Ab(o,"inbound",u)===i){const t=new gi(`Too many inbound protocol streams for protocol "${o}" - limit ${i}`);throw e.abort(t),t}e.source=n.source,e.sink=n.sink,e.protocol=o,null!=n.closeWrite&&(e.closeWrite=n.closeWrite),null!=n.closeRead&&(e.closeRead=n.closeRead),null!=n.close&&(e.close=n.close),await this.components.peerStore.merge(s,{protocols:[o]}),this.components.metrics?.trackProtocolStream(e,u),this._onStream({connection:u,stream:e,protocol:o})})).catch((async t=>{u.log.error("error handling incoming stream id %s - %e",e.id,t),null==e.timeline.close&&await e.close()}))}}),l=async(t,n={})=>{if(null==c)throw new ay("Connection is not multiplexed");u.log.trace("starting new stream for protocols %s",t);const o=await c.newStream();u.log.trace("started new stream %s for protocols %s",o.id,t);try{if(null==n.signal){o.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",t);const e=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);n={...n,signal:e}}o.log.trace("selecting protocol from protocols %s",t);const{stream:e,protocol:r}=await vb(o,t,{...n,log:o.log,yieldBytes:!0});o.log.trace("selected protocol %s",r);const i=function(e,t,r={}){try{const{options:r}=t.getHandler(e);if(null!=r.maxOutboundStreams)return r.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return r.maxOutboundStreams??64}(r,this.components.registrar,n),a=Ab(r,"outbound",u);if(a>=i){const e=new mi(`Too many outbound protocol streams for protocol "${r}" - ${a}/${i}`);throw o.abort(e),e}return await this.components.peerStore.merge(s,{protocols:[r]}),o.source=e.source,o.sink=e.sink,o.protocol=r,null!=e.closeWrite&&(o.closeWrite=e.closeWrite),null!=e.closeRead&&(o.closeRead=e.closeRead),null!=e.close&&(o.close=e.close),this.components.metrics?.trackProtocolStream(o,u),o}catch(n){throw u.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===r?"from":"to",e.maConn.remoteAddr,t,n),null==o.timeline.close&&o.abort(n),n}},Promise.all([c.sink(o.source),o.sink(c.source)]).catch((e=>{u.log.error("error piping data through muxer - %e",e)})));const h=n.timeline;var d;return n.timeline=new Proxy(h,{set:(...e)=>("close"===e[1]&&null!=e[2]&&null==h.close&&(async()=>{try{"open"===u.status&&await u.close()}catch(e){u.log.error("error closing connection after timeline close %e",e)}finally{this.events.safeDispatchEvent("connection:close",{detail:u})}})().catch((e=>{u.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...e))}),n.timeline.upgraded=Date.now(),d={remoteAddr:n.remoteAddr,remotePeer:s,status:"open",direction:r,timeline:n.timeline,multiplexer:c?.protocol,encryption:t,limits:a,logger:this.components.logger,newStream:l??(()=>{throw new ay("Connection is not multiplexed")}),getStreams:()=>c?.streams??[],close:async e=>{await(c?.close(e)),await n.close(e)},abort:e=>{n.abort(e),c?.abort(e)}},u=new Sb(d),this.events.safeDispatchEvent("connection:open",{detail:u}),u.__maConnTimeline=h,u}_onStream(e){const{connection:t,stream:r,protocol:n}=e,{handler:o,options:s}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==s.runOnLimitedConnection)throw new fi("Cannot open protocol stream on limited connection");o({connection:t,stream:r})}async _encryptInbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{const{stream:n,protocol:o}=await wb(e,r,{...t,log:e.log}),s=this.connectionEncrypters.get(o);if(null==s)throw new cy(`no crypto module found for ${o}`);return e.log("encrypting inbound connection to %a using %s",e.remoteAddr,o),{...await s.secureInbound(n,t),protocol:o}}catch(t){throw e.log.error("encrypting inbound connection from %a failed",e.remoteAddr,t),new cy(t.message)}}async _encryptOutbound(e,t){const r=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",r);const{stream:n,protocol:o}=await vb(e,r,{...t,log:e.log,yieldBytes:!0}),s=this.connectionEncrypters.get(o);if(null==s)throw new cy(`no crypto module found for ${o}`);return e.log("encrypting outbound connection to %a using %s",e.remoteAddr,o),{...await s.secureOutbound(n,t),protocol:o}}catch(t){throw e.log.error("encrypting outbound connection to %a failed",e.remoteAddr,t),new cy(t.message)}}async _multiplexOutbound(e,t,r){const n=Array.from(t.keys());e.log("outbound selecting muxer %s",n);try{e.log.trace("selecting stream muxer from %s",n);const{stream:o,protocol:s}=await vb(e,n,{...r,log:e.log,yieldBytes:!0});return e.log("selected %s as muxer protocol",s),{stream:o,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing outbound connection",t),new ay(String(t))}}async _multiplexInbound(e,t,r){const n=Array.from(t.keys());e.log("inbound handling muxers %s",n);try{const{stream:o,protocol:s}=await wb(e,n,{...r,log:e.log});return{stream:o,muxerFactory:t.get(s)}}catch(t){throw e.log.error("error multiplexing inbound connection",t),new ay(String(t))}}}class Cb extends xo{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";const t=new xo,r=t.dispatchEvent.bind(t);t.dispatchEvent=e=>{const t=r(e),n=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||n},this.peerId=e.peerId,this.logger=e.logger??Zg(),this.log=this.logger.forComponent("libp2p"),this.services={};const n=this.components=function(e={}){const t=new uy(e);return new Proxy(t,{get(e,r,n){if("string"==typeof r&&!dy.includes(r)){const e=t.components[r];if(null==e&&!hy.includes(r))throw new Xm(`${r} not set`);return e}return Reflect.get(e,r,n)},set:(e,r,n)=>("string"==typeof r?t.components[r]=n:Reflect.set(e,r,n),!0)})}({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:e.nodeInfo??{name:"libp2p",version:"2.1.8"},logger:this.logger,events:t,datastore:e.datastore??new Vm,connectionGater:my(e.connectionGater),dns:e.dns});this.peerStore=this.configureComponent("peerStore",function(e,t={}){return new Um(e,t)}(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 kb(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map(((e,t)=>this.configureComponent(`connection-encryption-${t}`,e(this.components)))),streamMuxers:(e.streamMuxers??[]).map(((e,t)=>this.configureComponent(`stream-muxers-${t}`,e(this.components)))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,outboundUpgradeTimeout:e.connectionManager?.outboundUpgradeTimeout}),this.configureComponent("transportManager",new pb(this.components,e.transportManager)),this.configureComponent("connectionManager",new Ky(this.components,e.connectionManager)),!1!==e.connectionMonitor?.enabled&&this.configureComponent("connectionMonitor",new Jy(this.components,e.connectionMonitor)),this.configureComponent("registrar",new hb(this.components)),this.configureComponent("addressManager",new Gm(this.components,e.addresses));const o=(e.peerRouters??[]).map(((e,t)=>this.configureComponent(`peer-router-${t}`,e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new lb(this.components,{routers:o}));const s=(e.contentRouters??[]).map(((e,t)=>this.configureComponent(`content-router-${t}`,e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new Xy(this.components,{routers:s})),this.configureComponent("randomWalk",new ub(this.components)),(e.peerDiscovery??[]).forEach(((e,t)=>{this.configureComponent(`peer-discovery-${t}`,e(this.components)).addEventListener("peer",(e=>{this.#O(e)}))})),e.transports?.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent(`transport-${t}`,e(this.components)))})),null!=e.services)for(const t of Object.keys(e.services)){const r=(0,e.services[t])(this.components);null!=r?(this.services[t]=r,this.configureComponent(t,r),null!=r[Fg]&&(this.log("registering service %s for content routing",t),s.push(r[Fg])),null!=r[$g]&&(this.log("registering service %s for peer routing",t),o.push(r[$g])),null!=r[Ad]&&(this.log("registering service %s for peer discovery",t),r[Ad].addEventListener?.("peer",(e=>{this.#O(e)})))):this.log.error("service factory %s returned null or undefined instance",t)}!function(e){const t={};for(const r of Object.values(e.components))for(const e of py(r))t[e]=!0;for(const r of Object.values(e.components))for(const e of fy(r))if(!0!==t[e])throw new Ym(`Service "${gy(r)}" required capability "${e}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}(n)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if("stopped"===this.status){this.status="starting",this.log("libp2p is starting");try{await(this.components.beforeStart?.()),await this.components.start(),await(this.components.afterStart?.()),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started")}catch(e){throw this.log.error("An error occurred starting libp2p",e),this.status="started",await this.stop(),e}}}async stop(){"started"===this.status&&(this.log("libp2p is stopping"),this.status="stopping",await(this.components.beforeStop?.()),await this.components.stop(),await(this.components.afterStop?.()),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){const e=new rm;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 Ws("no protocols were provided to open a stream");if(0===(t=Array.isArray(t)?t:[t]).length)throw new Ws("no protocols were provided to open a stream");return(await this.dial(e,r)).newStream(t,r)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){Cs(e)&&(e=nh(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("NotFoundError"!==e.name)throw e}const r=kn([xt("/pk/"),e.toMultihash().bytes]),n=Gu(await this.contentRouting.get(r,t));return await this.peerStore.patch(e,{publicKey:n}),n}async handle(e,t,r){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.handle(e,t,r)})))}async unhandle(e){Array.isArray(e)||(e=[e]),await Promise.all(e.map((async e=>{await this.components.registrar.unhandle(e)})))}async register(e,t){return this.components.registrar.register(e,t)}unregister(e){this.components.registrar.unregister(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#O(e){const{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}}const Ib="bootstrap",xb={store:1,filter:2,lightPush:2};var Tb=__webpack_require__(495),_b=__webpack_require__.t(Tb,2);const Nb=BigInt(0),Pb=BigInt(1),Lb=BigInt(2),Bb=BigInt(3),Ob=BigInt(8),Rb=Object.freeze({a:Nb,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:Pb,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")}),Db=(e,t)=>(e+t/Lb)/t,Ub={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(e){const{n:t}=Rb,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Pb*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,i=BigInt("0x100000000000000000000000000000000"),a=Db(s*e,t),c=Db(-n*e,t);let l=aw(e-a*r-c*o,t),u=aw(-a*n-c*s,t);const h=l>i,d=u>i;if(h&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalarEndo: Endomorphism failed, k="+e);return{k1neg:h,k1:l,k2neg:d,k2:u}}};function Mb(e){const{a:t,b:r}=Rb,n=aw(e*e),o=aw(n*e);return aw(o+t*e+r)}const Fb=Rb.a===Nb;class $b extends Error{constructor(e){super(e)}}function qb(e){if(!(e instanceof Hb))throw new TypeError("JacobianPoint expected")}class Hb{constructor(e,t,r){this.x=e,this.y=t,this.z=r}static fromAffine(e){if(!(e instanceof zb))throw new TypeError("JacobianPoint#fromAffine: expected Point");return e.equals(zb.ZERO)?Hb.ZERO:new Hb(e.x,e.y,Pb)}static toAffineBatch(e){const t=function(e,t=Rb.P){const r=new Array(e.length),n=lw(e.reduce(((e,n,o)=>n===Nb?e:(r[o]=e,aw(e*n,t))),Pb),t);return e.reduceRight(((e,n,o)=>n===Nb?e:(r[o]=aw(e*r[o],t),aw(e*n,t))),n),r}(e.map((e=>e.z)));return e.map(((e,r)=>e.toAffine(t[r])))}static normalizeZ(e){return Hb.toAffineBatch(e).map(Hb.fromAffine)}equals(e){qb(e);const{x:t,y:r,z:n}=this,{x:o,y:s,z:i}=e,a=aw(n*n),c=aw(i*i),l=aw(t*c),u=aw(o*a),h=aw(aw(r*i)*c),d=aw(aw(s*n)*a);return l===u&&h===d}negate(){return new Hb(this.x,aw(-this.y),this.z)}double(){const{x:e,y:t,z:r}=this,n=aw(e*e),o=aw(t*t),s=aw(o*o),i=e+o,a=aw(Lb*(aw(i*i)-n-s)),c=aw(Bb*n),l=aw(c*c),u=aw(l-Lb*a),h=aw(c*(a-u)-Ob*s),d=aw(Lb*t*r);return new Hb(u,h,d)}add(e){qb(e);const{x:t,y:r,z:n}=this,{x:o,y:s,z:i}=e;if(o===Nb||s===Nb)return this;if(t===Nb||r===Nb)return e;const a=aw(n*n),c=aw(i*i),l=aw(t*c),u=aw(o*a),h=aw(aw(r*i)*c),d=aw(aw(s*n)*a),p=aw(u-l),f=aw(d-h);if(p===Nb)return f===Nb?this.double():Hb.ZERO;const g=aw(p*p),m=aw(p*g),y=aw(l*g),b=aw(f*f-m-Lb*y),w=aw(f*(y-b)-h*m),v=aw(n*i*p);return new Hb(b,w,v)}subtract(e){return this.add(e.negate())}multiplyUnsafe(e){const t=Hb.ZERO;if("bigint"==typeof e&&e===Nb)return t;let r=iw(e);if(r===Pb)return this;if(!Fb){let e=t,n=this;for(;r>Nb;)r&Pb&&(e=e.add(n)),n=n.double(),r>>=Pb;return e}let{k1neg:n,k1:o,k2neg:s,k2:i}=Ub.splitScalar(r),a=t,c=t,l=this;for(;o>Nb||i>Nb;)o&Pb&&(a=a.add(l)),i&Pb&&(c=c.add(l)),l=l.double(),o>>=Pb,i>>=Pb;return n&&(a=a.negate()),s&&(c=c.negate()),c=new Hb(aw(c.x*Ub.beta),c.y,c.z),a.add(c)}precomputeWindow(e){const t=Fb?128/e+1:256/e+1,r=[];let n=this,o=n;for(let s=0;s>=u,i>a&&(i-=l,e+=Pb);const h=r,d=r+Math.abs(i)-1,p=t%2!=0,f=i<0;0===i?s=s.add(jb(p,n[h])):o=o.add(jb(f,n[d]))}return{p:o,f:s}}multiply(e,t){let r,n,o=iw(e);if(Fb){const{k1neg:e,k1:s,k2neg:i,k2:a}=Ub.splitScalar(o);let{p:c,f:l}=this.wNAF(s,t),{p:u,f:h}=this.wNAF(a,t);c=jb(e,c),u=jb(i,u),u=new Hb(aw(u.x*Ub.beta),u.y,u.z),r=c.add(u),n=l.add(h)}else{const{p:e,f:s}=this.wNAF(o,t);r=e,n=s}return Hb.normalizeZ([r,n])[0]}toAffine(e){const{x:t,y:r,z:n}=this,o=this.equals(Hb.ZERO);null==e&&(e=o?Ob:lw(n));const s=e,i=aw(s*s),a=aw(i*s),c=aw(t*i),l=aw(r*a),u=aw(n*s);if(o)return zb.ZERO;if(u!==Pb)throw new Error("invZ was invalid");return new zb(c,l)}}function jb(e,t){const r=t.negate();return e?r:t}Hb.BASE=new Hb(Rb.Gx,Rb.Gy,Pb),Hb.ZERO=new Hb(Nb,Pb,Nb);const Vb=new WeakMap;class zb{constructor(e,t){this.x=e,this.y=t}_setWindowSize(e){this._WINDOW_SIZE=e,Vb.delete(this)}hasEvenY(){return this.y%Lb===Nb}static fromCompressedHex(e){const t=32===e.length,r=ow(t?e:e.subarray(1));if(!gw(r))throw new Error("Point is not on curve");let n=function(e){const{P:t}=Rb,r=BigInt(6),n=BigInt(11),o=BigInt(22),s=BigInt(23),i=BigInt(44),a=BigInt(88),c=e*e*e%t,l=c*c*e%t,u=cw(l,Bb)*l%t,h=cw(u,Bb)*l%t,d=cw(h,Lb)*c%t,p=cw(d,n)*d%t,f=cw(p,o)*p%t,g=cw(f,i)*f%t,m=cw(g,a)*g%t,y=cw(m,i)*f%t,b=cw(y,Bb)*l%t,w=cw(b,s)*p%t,v=cw(w,r)*c%t,E=cw(v,Lb);if(E*E%t!==e)throw new Error("Cannot find square root");return E}(Mb(r));const o=(n&Pb)===Pb;t?o&&(n=aw(-n)):!(1&~e[0])!==o&&(n=aw(-n));const s=new zb(r,n);return s.assertValidity(),s}static fromUncompressedHex(e){const t=ow(e.subarray(1,33)),r=ow(e.subarray(33,65)),n=new zb(t,r);return n.assertValidity(),n}static fromHex(e){const t=sw(e),r=t.length,n=t[0];if(32===r)return this.fromCompressedHex(t);if(33===r&&(2===n||3===n))return this.fromCompressedHex(t);if(65===r&&4===n)return this.fromUncompressedHex(t);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${r}`)}static fromPrivateKey(e){return zb.BASE.multiply(yw(e))}static fromSignature(e,t,r){const{r:n,s:o}=bw(t);if(![0,1,2,3].includes(r))throw new Error("Cannot recover: invalid recovery bit");const s=uw(sw(e)),{n:i}=Rb,a=2===r||3===r?n+i:n,c=lw(a,i),l=aw(-s*c,i),u=aw(o*c,i),h=1&r?"03":"02",d=zb.fromHex(h+Qb(a)),p=zb.BASE.multiplyAndAddUnsafe(d,l,u);if(!p)throw new Error("Cannot recover signature: point at infinify");return p.assertValidity(),p}toRawBytes(e=!1){return nw(this.toHex(e))}toHex(e=!1){const t=Qb(this.x);return e?`${this.hasEvenY()?"02":"03"}${t}`:`04${t}${Qb(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(!gw(t)||!gw(r))throw new Error(e);const n=aw(r*r);if(aw(n-Mb(t))!==Nb)throw new Error(e)}equals(e){return this.x===e.x&&this.y===e.y}negate(){return new zb(this.x,aw(-this.y))}double(){return Hb.fromAffine(this).double().toAffine()}add(e){return Hb.fromAffine(this).add(Hb.fromAffine(e)).toAffine()}subtract(e){return this.add(e.negate())}multiply(e){return Hb.fromAffine(this).multiply(e,this).toAffine()}multiplyAndAddUnsafe(e,t,r){const n=Hb.fromAffine(this),o=t===Nb||t===Pb||this!==zb.BASE?n.multiplyUnsafe(t):n.multiply(t),s=Hb.fromAffine(e).multiplyUnsafe(r),i=o.add(s);return i.equals(Hb.ZERO)?void 0:i.toAffine()}}function Kb(e){return Number.parseInt(e[0],16)>=8?"00"+e:e}function Gb(e){if(e.length<2||2!==e[0])throw new Error(`Invalid signature integer tag: ${Yb(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:ow(r),left:e.subarray(t+2)}}zb.BASE=new zb(Rb.Gx,Rb.Gy),zb.ZERO=new zb(Nb,Nb);class Wb{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?Yb(e):e;if(128!==n.length)throw new Error(`${r}: Expected 64-byte hex`);return new Wb(rw(n.slice(0,64)),rw(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: ${Yb(e)}`);if(e[1]!==e.length-2)throw new Error("Invalid signature: incorrect length");const{data:t,left:r}=Gb(e.subarray(2)),{data:n,left:o}=Gb(r);if(o.length)throw new Error(`Invalid signature: left bytes after parsing: ${Yb(o)}`);return{r:t,s:n}}(t?e:nw(e));return new Wb(r,n)}static fromHex(e){return this.fromDER(e)}assertValidity(){const{r:e,s:t}=this;if(!fw(e))throw new Error("Invalid Signature: r must be 0 < r < n");if(!fw(t))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const e=Rb.n>>Pb;return this.s>e}normalizeS(){return this.hasHighS()?new Wb(this.r,aw(-this.s,Rb.n)):this}toDERRawBytes(){return nw(this.toDERHex())}toDERHex(){const e=Kb(tw(this.s)),t=Kb(tw(this.r)),r=e.length/2,n=t.length/2,o=tw(r),s=tw(n);return`30${tw(n+r+4)}02${s}${t}02${o}${e}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return nw(this.toCompactHex())}toCompactHex(){return Qb(this.r)+Qb(this.s)}}function Jb(...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;tt.toString(16).padStart(2,"0")));function Yb(e){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");let t="";for(let r=0;r0)return BigInt(e);if("bigint"==typeof e&&fw(e))return e;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function aw(e,t=Rb.P){const r=e%t;return r>=Nb?r:t+r}function cw(e,t){const{P:r}=Rb;let n=e;for(;t-- >Nb;)n*=n,n%=r;return n}function lw(e,t=Rb.P){if(e===Nb||t<=Nb)throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`);let r=aw(e,t),n=t,o=Nb,s=Pb,i=Pb,a=Nb;for(;r!==Nb;){const e=n/r,t=n%r,c=o-i*e,l=s-a*e;n=r,r=t,o=i,s=a,i=c,a=l}if(n!==Pb)throw new Error("invert: does not exist");return aw(o,t)}function uw(e,t=!1){const r=function(e){const t=8*e.length-256,r=ow(e);return t>0?r>>BigInt(t):r}(e);if(t)return r;const{n}=Rb;return r>=n?r-n:r}let hw,dw;class pw{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 Cw.hmacSha256(this.k,...e)}hmacSync(...e){return dw(this.k,...e)}checkSync(){if("function"!=typeof dw)throw new $b("hmacSha256Sync needs to be set")}incr(){if(this.counter>=1e3)throw new Error("Tried 1,000 k values for sign(), all were invalid");this.counter+=1}async reseed(e=new Uint8Array){this.k=await this.hmac(this.v,Uint8Array.from([0]),e),this.v=await this.hmac(this.v),0!==e.length&&(this.k=await this.hmac(this.v,Uint8Array.from([1]),e),this.v=await this.hmac(this.v))}reseedSync(e=new Uint8Array){this.checkSync(),this.k=this.hmacSync(this.v,Uint8Array.from([0]),e),this.v=this.hmacSync(this.v),0!==e.length&&(this.k=this.hmacSync(this.v,Uint8Array.from([1]),e),this.v=this.hmacSync(this.v))}async generate(){this.incr();let e=0;const t=[];for(;e0)t=BigInt(e);else if("string"==typeof e){if(64!==e.length)throw new Error("Expected 32 bytes of private key");t=rw(e)}else{if(!(e instanceof Uint8Array))throw new TypeError("Expected valid private key");if(32!==e.length)throw new Error("Expected 32 bytes of private key");t=ow(e)}if(!fw(t))throw new Error("Expected private key: 0 < key < n");return t}function bw(e){if(e instanceof Wb)return e.assertValidity(),e;try{return Wb.fromDER(e)}catch(t){return Wb.fromCompact(e)}}function ww(e){return ow(e.length>32?e.slice(0,32):e)}function vw(e){const t=ww(e),r=aw(t,Rb.n);return Ew(r{if((e=sw(e)).length<40||e.length>1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return ew(aw(ow(e),Rb.n-Pb)+Pb)},randomBytes:(e=32)=>{if(Aw.web)return Aw.web.getRandomValues(new Uint8Array(e));if(Aw.node){const{randomBytes:t}=Aw.node;return Uint8Array.from(t(e))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>Cw.hashToPrivateKey(Cw.randomBytes(40)),precompute(e=8,t=zb.BASE){const r=t===zb.BASE?t:new zb(t.x,t.y);return r._setWindowSize(e),r.multiply(Bb),r},sha256:async(...e)=>{if(Aw.web){const t=await Aw.web.subtle.digest("SHA-256",Jb(...e));return new Uint8Array(t)}if(Aw.node){const{createHash:t}=Aw.node,r=t("sha256");return e.forEach((e=>r.update(e))),Uint8Array.from(r.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(e,...t)=>{if(Aw.web){const r=await Aw.web.subtle.importKey("raw",e,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),n=Jb(...t),o=await Aw.web.subtle.sign("HMAC",r,n);return new Uint8Array(o)}if(Aw.node){const{createHmac:r}=Aw.node,n=r("sha256",e);return t.forEach((e=>n.update(e))),Uint8Array.from(n.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(e,...t)=>{let r=kw[e];if(void 0===r){const t=await Cw.sha256(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Jb(t,t),kw[e]=r}return Cw.sha256(r,...t)},taggedHashSync:(e,...t)=>{if("function"!=typeof hw)throw new $b("sha256Sync is undefined, you need to set it");let r=kw[e];if(void 0===r){const t=hw(Uint8Array.from(e,(e=>e.charCodeAt(0))));r=Jb(t,t),kw[e]=r}return hw(r,...t)},_JacobianPoint:Hb};Object.defineProperties(Cw,{sha256Sync:{configurable:!1,get:()=>hw,set(e){hw||(hw=e)}},hmacSha256Sync:{configurable:!1,get:()=>dw,set(e){dw||(dw=e)}}});var Iw=__webpack_require__(1176);function xw(e){return new Uint8Array(Iw.keccak256.arrayBuffer(e))}function Tw(e,t,r){try{return function(e,t,r,n=Sw){let o;try{o=bw(e),t=sw(t)}catch(e){return!1}const{r:s,s:i}=o;if(n.strict&&o.hasHighS())return!1;const a=uw(t);let c;try{c=function(e){return e instanceof zb?(e.assertValidity(),e):zb.fromHex(e)}(r)}catch(e){return!1}const{n:l}=Rb,u=lw(i,l),h=aw(a*u,l),d=aw(s*u,l),p=zb.BASE.multiplyAndAddUnsafe(c,h,d);return!!p&&aw(p.x,l)===s}(Wb.fromCompact(e.slice(0,64)),t,r)}catch{return!1}}const _w="Invalid record id";function Nw(e,t){switch(t){case"udp":return Nw(e,"udp4")||Nw(e,"udp6");case"tcp":return Nw(e,"tcp4")||Nw(e,"tcp6")}const r=t.endsWith("6"),n=e.get(r?"ip6":"ip");if(!n)return;const o=t.slice(0,3);let s;switch(o){case"udp":s=r?e.get("udp6"):e.get("udp");break;case"tcp":s=r?e.get("tcp6"):e.get("tcp");break;default:return}return s?function(e,t,r,n){let o=Is("/"+e+"/"+ss(e,r));return o=o.encapsulate(Is("/"+t+"/"+ss(t,n))),o}(r?"ip6":"ip4",o,n,s):void 0}function Pw(e){const t=e.reduce(((e,t)=>e+2+t.bytes.length),0),r=new Uint8Array(t),n=new DataView(r.buffer);let o=0;return e.forEach((e=>{if(e.getPeerId())throw new Error("`multiaddr` field MUST not contain peer id");n.setUint16(o,e.bytes.length),o+=2,r.set(e.bytes,o),o+=e.bytes.length})),r}function Lw(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 Bw 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 tn(e)}get publicKey(){if("v4"===this.id)return this.get("secp256k1");throw new Error(_w)}get rs(){const e=this.get("rs");if(e)return hn(e)}get rsv(){const e=this.get("rsv");if(e)return hn(e)}get ip(){return Ow(this,"ip","ip4")}set ip(e){Dw(this,"ip","ip4",e)}get tcp(){return Rw(this,"tcp","tcp")}set tcp(e){Uw(this,"tcp","tcp",e)}get udp(){return Rw(this,"udp","udp")}set udp(e){Uw(this,"udp","udp",e)}get ip6(){return Ow(this,"ip6","ip6")}set ip6(e){Dw(this,"ip6","ip6",e)}get tcp6(){return Rw(this,"tcp6","tcp")}set tcp6(e){Uw(this,"tcp6","tcp",e)}get udp6(){return Rw(this,"udp6","udp")}set udp6(e){Uw(this,"udp6","udp",e)}get multiaddrs(){const e=this.get("multiaddrs");if(e)return function(e){const t=[];let r=0;for(;r>=1)%2&&(t.store=!0),(e>>=1)%2&&(t.filter=!0),(e>>=1)%2&&(t.lightPush=!0),t}(e[0])}set waku2(e){Mw(this,"waku2",e,(e=>new Uint8Array([Lw(e)])))}}function Ow(e,t,r){const n=e.get(t);if(n)return ss(r,n)}function Rw(e,t,r){const n=e.get(t);if(n)return Number(ss(r,n))}function Dw(e,t,r,n){Mw(e,t,n,is.bind({},r))}function Uw(e,t,r,n){Dw(e,t,r,n?.toString(10))}function Mw(e,t,r,n){void 0!==r?e.set(t,n(r)):e.delete(t)}async function Fw(e,t){return async function(e,t,r={}){const{seed:n,m:o,d:s}=function(e,t,r){if(null==e)throw new Error(`sign: expected valid message hash, not "${e}"`);const n=sw(e),o=yw(t),s=[Ew(o),vw(n)];if(null!=r){!0===r&&(r=Cw.randomBytes(32));const e=sw(r);if(32!==e.length)throw new Error("sign: Expected 32 bytes of extra data");s.push(e)}return{seed:Jb(...s),m:ww(n),d:o}}(e,t,r.extraEntropy),i=new pw(32,32);let a;for(await i.reseed(n);!(a=mw(await i.generate(),o,s,r.canonical));)await i.reseed();return function(e,t){const{sig:r,recovery:n}=e,{der:o,recovered:s}=Object.assign({canonical:!0,der:!0},t),i=o?r.toDERRawBytes():r.toCompactRawBytes();return s?[i,n]:i}(a,r)}(xw(t),e,{der:!1})}const $w=new gn("enr");var qw,Hw;!function(e){e.TCP="tcp",e.UDP="udp"}(qw||(qw={})),function(e){e.TCP4="tcp4",e.UDP4="udp4",e.TCP6="tcp6",e.UDP6="udp6"}(Hw||(Hw={}));class jw extends Bw{static RECORD_PREFIX="enr:";peerId;static create(e={},t=BigInt(1),r){const n=new jw(e,t,r);try{const e=n.publicKey;e&&(n.peerId=function(e){const t=32===(r=e).byteLength?rc(r):33===r.byteLength?Vu(r):Eu(r);var r;if("secp256k1"!==t.type)throw new Error("Keypair type not implemented");return oh(t)}(e))}catch(e){$w.error("Could not calculate peer id for ENR",e)}return n}get nodeId(){if("v4"===this.id)return this.publicKey?function(e){const t=zb.fromHex(e).toRawBytes(!1);return en(xw(t.slice(1)))}(this.publicKey):void 0;throw new Error(_w)}getLocationMultiaddr=Nw.bind({},this);get shardInfo(){return this.rs&&this.rsv&&$w.warn("ENR contains both `rs` and `rsv` fields."),this.rs||this.rsv}setLocationMultiaddr(e){const t=e.protoNames();if(2!==t.length&&"udp"!==t[1]&&"tcp"!==t[1])throw new Error("Invalid multiaddr");const r=e.tuples();if(!r[0][1]||!r[1][1])throw new Error("Invalid multiaddr");4===r[0][0]?(this.set("ip",r[0][1]),this.set(t[1],r[1][1])):(this.set("ip6",r[0][1]),this.set(t[1]+"6",r[1][1]))}getAllLocationMultiaddrs(){const e=[];for(const t of Object.values(Hw)){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(_w);if(!this.publicKey)throw new Error("Failed to verify ENR: No public key");return Tw(t,xw(e),this.publicKey)}async sign(e,t){if("v4"!==this.id)throw new Error(_w);return this.signature=await Fw(t,e),this.signature}}let Vw=!1,zw=!1;const Kw={debug:1,default:2,info:2,warning:3,error:4,off:5};let Gw=Kw.default,Ww=null;const Jw=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 Xw,Yw;!function(e){e.DEBUG="DEBUG",e.INFO="INFO",e.WARNING="WARNING",e.ERROR="ERROR",e.OFF="OFF"}(Xw||(Xw={})),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"}(Yw||(Yw={}));const Zw="0123456789abcdef";class Qw{constructor(e){Object.defineProperty(this,"version",{enumerable:!0,value:e,writable:!1})}_log(e,t){const r=e.toLowerCase();null==Kw[r]&&this.throwArgumentError("invalid log level name","logLevel",e),Gw>Kw[r]||console.log.apply(console,t)}debug(...e){this._log(Qw.levels.DEBUG,e)}info(...e){this._log(Qw.levels.INFO,e)}warn(...e){this._log(Qw.levels.WARNING,e)}makeError(e,t,r){if(zw)return this.makeError("censored error",t,{});t||(t=Qw.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>4],r+=Zw[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 o=e;let s="";switch(t){case Yw.NUMERIC_FAULT:{s="NUMERIC_FAULT";const t=e;switch(t){case"overflow":case"underflow":case"division-by-zero":s+="-"+t;break;case"negative-power":case"negative-width":s+="-unsupported";break;case"unbound-bitwise-result":s+="-unbound-result"}break}case Yw.CALL_EXCEPTION:case Yw.INSUFFICIENT_FUNDS:case Yw.MISSING_NEW:case Yw.NONCE_EXPIRED:case Yw.REPLACEMENT_UNDERPRICED:case Yw.TRANSACTION_REPLACED:case Yw.UNPREDICTABLE_GAS_LIMIT:s=t}s&&(e+=" [ See: https://links.ethers.org/v5-errors-"+s+" ]"),n.length&&(e+=" ("+n.join(", ")+")");const i=new Error(e);return i.reason=o,i.code=t,Object.keys(r).forEach((function(e){i[e]=r[e]})),i}throwError(e,t,r){throw this.makeError(e,t,r)}throwArgumentError(e,t,r){return this.throwError(e,Qw.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"),Jw&&this.throwError("platform missing String.prototype.normalize",Qw.errors.UNSUPPORTED_OPERATION,{operation:"String.prototype.normalize",form:Jw})}checkSafeUint53(e,t){"number"==typeof e&&(null==t&&(t="value not safe"),(e<0||e>=9007199254740991)&&this.throwError(t,Qw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"out-of-safe-range",value:e}),e%1&&this.throwError(t,Qw.errors.NUMERIC_FAULT,{operation:"checkSafeInteger",fault:"non-integer",value:e}))}checkArgumentCount(e,t,r){r=r?": "+r:"",et&&this.throwError("too many arguments"+r,Qw.errors.UNEXPECTED_ARGUMENT,{count:e,expectedCount:t})}checkNew(e,t){e!==Object&&null!=e||this.throwError("missing new",Qw.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",Qw.errors.UNSUPPORTED_OPERATION,{name:e.name,operation:"new"}):e!==Object&&null!=e||this.throwError("missing new",Qw.errors.MISSING_NEW,{name:t.name})}static globalLogger(){return Ww||(Ww=new Qw("logger/5.7.0")),Ww}static setCensorship(e,t){if(!e&&t&&this.globalLogger().throwError("cannot permanently disable censorship",Qw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"}),Vw){if(!e)return;this.globalLogger().throwError("error censorship permanent",Qw.errors.UNSUPPORTED_OPERATION,{operation:"setCensorship"})}zw=!!e,Vw=!!t}static setLogLevel(e){const t=Kw[e.toLowerCase()];null!=t?Gw=t:Qw.globalLogger().warn("invalid log level - "+e)}static from(e){return new Qw(e)}}Qw.errors=Yw,Qw.levels=Xw;const ev=new Qw("bytes/5.7.0");function tv(e){return!!e.toHexString}function rv(e){return e.slice||(e.slice=function(){const t=Array.prototype.slice.call(arguments);return rv(new Uint8Array(Array.prototype.slice.apply(e,t)))}),e}function nv(e){return"number"==typeof e&&e==e&&e%1==0}function ov(e){if(null==e)return!1;if(e.constructor===Uint8Array)return!0;if("string"==typeof e)return!1;if(!nv(e.length)||e.length<0)return!1;for(let t=0;t=256)return!1}return!0}function sv(e,t){if(t||(t={}),"number"==typeof e){ev.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),rv(new Uint8Array(t))}if(t.allowMissingPrefix&&"string"==typeof e&&"0x"!==e.substring(0,2)&&(e="0x"+e),tv(e)&&(e=e.toHexString()),iv(e)){let r=e.substring(2);r.length%2&&("left"===t.hexPad?r="0"+r:"right"===t.hexPad?r+="0":ev.throwArgumentError("hex data is odd-length","value",e));const n=[];for(let e=0;e>4]+av[15&n]}return t}return ev.throwArgumentError("invalid hexlify value","value",e)}const lv=new Qw("rlp/5.7.0");function uv(e){const t=[];for(;e;)t.unshift(255&e),e>>=8;return t}function hv(e,t,r){let n=0;for(let o=0;ot+1+n&&lv.throwError("child data too short",Qw.errors.BUFFER_OVERRUN,{})}return{consumed:1+n,result:o}}function fv(e,t){if(0===e.length&&lv.throwError("data too short",Qw.errors.BUFFER_OVERRUN,{}),e[t]>=248){const r=e[t]-247;t+1+r>e.length&&lv.throwError("data short segment too short",Qw.errors.BUFFER_OVERRUN,{});const n=hv(e,t+1,r);return t+1+r+n>e.length&&lv.throwError("data long segment too short",Qw.errors.BUFFER_OVERRUN,{}),pv(e,t,t+1+r,r+n)}if(e[t]>=192){const r=e[t]-192;return t+1+r>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{}),pv(e,t,t+1,r)}if(e[t]>=184){const r=e[t]-183;t+1+r>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{});const n=hv(e,t+1,r);return t+1+r+n>e.length&&lv.throwError("data array too short",Qw.errors.BUFFER_OVERRUN,{}),{consumed:1+r+n,result:cv(e.slice(t+1+r,t+1+r+n))}}if(e[t]>=128){const r=e[t]-128;return t+1+r>e.length&&lv.throwError("data too short",Qw.errors.BUFFER_OVERRUN,{}),{consumed:1+r,result:cv(e.slice(t+1,t+1+r))}}return{consumed:1,result:cv(e[t])}}const gv=new gn("enr:decoder");class mv{static fromString(e){if(!e.startsWith(jw.RECORD_PREFIX))throw new Error(`"string encoded ENR must start with '${jw.RECORD_PREFIX}'`);return mv.fromRLP(xt(e.slice(4),"base64url"))}static fromRLP(e){const t=function(e){const t=sv(e),r=fv(t,0);return r.consumed!==t.length&&lv.throwArgumentError("invalid rlp data","data",e),r.result}(e).map(Qr);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),o={};for(let e=0;eyv.test(e),encode(e,t,r){r=~~r,t=t||new Uint8Array(r+4);const n=e.length;let o=0;for(let s=0;s(t=~~t,`${e[t++]}.${e[t++]}.${e[t++]}.${e[t]}`)},vv={name:"v6",size:16,isFormat:e=>e.length>0&&bv.test(e),encode(e,t,r){let n=16+(r=~~r),o=-1,s=0,i=0,a=!0,c=!1;t=t||new Uint8Array(r+16);for(let l=0;l>8),r=97?u-=87:u>=65?u-=55:(u-=48,i=10*i+u),s=(s<<4)+u)}if(!1===a)!0===c?(r>8),r=o+2;e--)t[e]=t[e-2];t[o]=0,t[o+1]=0,o=r}if(o!==r&&-1!==o)for(r>n-2&&(r=n-2);n>o;)t[--n]=ro?t[--r]:0;else for(;r=Nv||(64512&e.charCodeAt(s))!==Nv?t+=3:(n=s,t+=4)}}return t}function Lv(e,t,r){const n=e.length;null==r&&(r=0),void 0===t&&(t=new Uint8Array(Pv(e)+r));let o=r;for(let r=0;r>6,t[o++]=128|63&s;else if((63488&s)!==_v)t[o++]=224|(61440&s)>>12,t[o++]=128|(4032&s)>>6,t[o++]=128|63&s;else{const i=r+1;if(i===n||s>=Nv)t[o++]=239,t[o++]=191,t[o++]=189;else{const n=e.charCodeAt(i);(64512&n)!==Nv?(t[o++]=239,t[o++]=191,t[o++]=189):(r=i,s=65536|(1023&s)<<10|1023&n,t[o++]=240|(1835008&s)>>18,t[o++]=128|(258048&s)>>12,t[o++]=128|(4032&s)>>6,t[o++]=128|63&s)}}}return Lv.bytes=o-r,t}function Bv(e,t,r){let n="";null==t&&(t=0),null==r&&(r=e.length);for(let o=t;o191&&t<224)r=(31&t)<<6|63&e[o++];else if(t>239&&t<365){r=((7&t)<<18|(63&e[o++])<<12|(63&e[o++])<<6|63&e[o++])-65536;const s=_v|r>>10&1023;n+=String.fromCharCode(s),r=Nv|1023&r}else r=(15&t)<<12|(63&e[o++])<<6|63&e[o++];n+=String.fromCharCode(r)}return Bv.bytes=r-t,n}Lv.bytes=0,Bv.bytes=0;const Ov=e=>e instanceof Uint8Array;function Rv(e){return"string"==typeof e?Pv(e):e.byteLength}function Dv(e){return e instanceof Uint8Array?e:Array.isArray(e)?new Uint8Array(e):Lv(e)}function Uv(e,t,r){if("string"!=typeof t)throw new Error("unknown input type");return Lv(t,e,r),Lv.bytes}const Mv=Math.pow(2,24),Fv=Math.pow(2,16),$v=Math.pow(2,8),qv=(e,t)=>e[t]*Mv+e[t+1]*Fv+e[t+2]*$v+e[t+3],Hv=(e,t)=>e[t]<<8|e[t+1],jv=(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),Vv=(e,t,r)=>(e[r]=t>>8,e[r+1]=255&t,r+2);function zv(e,t,r,n,o){return r<0&&(n-=r,r=0),n<0&&(n=0),o<0?new Uint8Array(0):r>=t.length||n>=o?0:function(e,t,r,n,o){o-n>t.length-r&&(o=n+t.length-r);let s=o-n;const i=e.length-n;return s>i&&(s=i),(0!==n||oe)}}const Gv=Kv({encode(e,t,r){t||(t=new Uint8Array(Gv.encodingLength(e))),r||(r=0);const n=r,o=e.replace(/^\.|\.$/gm,"");if(o.length){const e=o.split(".");for(let n=0;n=e.length)throw new Error("Cannot decode name (buffer overflow)");const a=e[t++];if(s+=i?0:1,0===a)break;if(192&a){if(192&~a)throw new Error("Cannot decode name (bad label)");{if(t+1>e.length)throw new Error("Cannot decode name (buffer overflow)");const r=Hv(e,t-1)-49152;if(r>=n)throw new Error("Cannot decode name (bad pointer)");t=r,n=r,s+=i?0:1,i=!0}}else{if(t+a>e.length)throw new Error("Cannot decode name (buffer overflow)");if(o+=a+1,o>254)throw new Error("Cannot decode name (name too long)");r.push(Bv(e,t,t+a)),t+=a,s+=i?0:a}}return Gv.decode.bytes=s,0===r.length?".":r.join(".")},encodingLength:e=>"."===e||".."===e?1:Rv(e.replace(/^\.|\.$/gm,""))+2}),Wv=Kv({encode(e,t,r){t||(t=new Uint8Array(Wv.encodingLength(e))),r||(r=0);const n=Uv(t,e,r+1);return t[r]=n,Wv.encode.bytes=n+1,t},decode(e,t){t||(t=0);const r=e[t],n=Bv(e,t+1,t+1+r);return Wv.decode.bytes=r+1,n},encodingLength:e=>Rv(e)+1}),Jv=Kv({bytes:12,encode(e,t,r){t||(t=new Uint8Array(Jv.encodingLength(e))),r||(r=0);const n=32767&(e.flags||0),o="response"===e.type?32768:0;return Vv(t,e.id||0,r),Vv(t,n|o,r+2),Vv(t,e.questions.length,r+4),Vv(t,e.answers.length,r+6),Vv(t,e.authorities.length,r+8),Vv(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=Hv(e,t+2);return{id:Hv(e,t),type:32768&r?"response":"query",flags:32767&r,flag_qr:1==(r>>15&1),opcode:Cv(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:kv(15&r),questions:new Array(Hv(e,t+4)),answers:new Array(Hv(e,t+6)),authorities:new Array(Hv(e,t+8)),additionals:new Array(Hv(e,t+10))}},encodingLength:()=>12}),Xv=Kv({encode(e,t,r){t||(t=new Uint8Array(Xv.encodingLength(e))),r||(r=0);const n=e.length;return Vv(t,n,r),zv(e,t,r+2,0,n),Xv.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Hv(e,t),n=e.slice(t+2,t+2+r);return Xv.decode.bytes=r+2,n},encodingLength:e=>e.length+2}),Yv=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(Yv.encodingLength(e))),r||(r=0),Gv.encode(e,t,r+2),Vv(t,Gv.encode.bytes,r),Yv.encode.bytes=Gv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Hv(e,t),n=Gv.decode(e,t+2);return Yv.decode.bytes=r+2,n},encodingLength:e=>Gv.encodingLength(e)+2}),Zv=Kv({encode(e,t,r){t||(t=new Uint8Array(Zv.encodingLength(e))),r||(r=0);const n=r;return r+=2,Gv.encode(e.mname,t,r),r+=Gv.encode.bytes,Gv.encode(e.rname,t,r),r+=Gv.encode.bytes,jv(t,e.serial||0,r),r+=4,jv(t,e.refresh||0,r),r+=4,jv(t,e.retry||0,r),r+=4,jv(t,e.expire||0,r),r+=4,jv(t,e.minimum||0,r),Vv(t,(r+=4)-n-2,n),Zv.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mname=Gv.decode(e,t),t+=Gv.decode.bytes,n.rname=Gv.decode(e,t),t+=Gv.decode.bytes,n.serial=qv(e,t),t+=4,n.refresh=qv(e,t),t+=4,n.retry=qv(e,t),t+=4,n.expire=qv(e,t),t+=4,n.minimum=qv(e,t),t+=4,Zv.decode.bytes=t-r,n},encodingLength:e=>22+Gv.encodingLength(e.mname)+Gv.encodingLength(e.rname)}),Qv=Kv({encode(e,t,r){Array.isArray(e)||(e=[e]);for(let t=0;t0;){const r=e[t++];if(--n,ne?(Ov(e)?e.length:Rv(e))+2:2}),tE=Kv({encode(e,t,r){t||(t=new Uint8Array(tE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Wv.encode(e.cpu,t,r),r+=Wv.encode.bytes,Wv.encode(e.os,t,r),r+=Wv.encode.bytes,Vv(t,r-n-2,n),tE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.cpu=Wv.decode(e,t),t+=Wv.decode.bytes,n.os=Wv.decode(e,t),t+=Wv.decode.bytes,tE.decode.bytes=t-r,n},encodingLength:e=>Wv.encodingLength(e.cpu)+Wv.encodingLength(e.os)+2}),rE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(rE.encodingLength(e))),r||(r=0),Gv.encode(e,t,r+2),Vv(t,Gv.encode.bytes,r),rE.encode.bytes=Gv.encode.bytes+2,t),decode(e,t){t||(t=0);const r=Gv.decode(e,t+2);return rE.decode.bytes=Gv.decode.bytes+2,r},encodingLength:e=>Gv.encodingLength(e)+2}),nE=Kv({encode(e,t,r){t||(t=new Uint8Array(nE.encodingLength(e))),r||(r=0),Vv(t,e.priority||0,r+2),Vv(t,e.weight||0,r+4),Vv(t,e.port||0,r+6),Gv.encode(e.target,t,r+8);const n=Gv.encode.bytes+6;return Vv(t,n,r),nE.encode.bytes=n+2,t},decode(e,t){t||(t=0);const r=Hv(e,t),n={};return n.priority=Hv(e,t+2),n.weight=Hv(e,t+4),n.port=Hv(e,t+6),n.target=Gv.decode(e,t+8),nE.decode.bytes=r+2,n},encodingLength:e=>8+Gv.encodingLength(e.target)}),oE=Kv({encode(e,t,r){const n=oE.encodingLength(e);return t||(t=new Uint8Array(oE.encodingLength(e))),r||(r=0),e.issuerCritical&&(e.flags=oE.ISSUER_CRITICAL),Vv(t,n-2,r),t[r+=2]=e.flags||0,r+=1,Wv.encode(e.tag,t,r),r+=Wv.encode.bytes,Uv(t,e.value,r),r+=Rv(e.value),oE.encode.bytes=n,t},decode(e,t){t||(t=0);const r=Hv(e,t),n=t+=2,o={};return o.flags=e[t],t+=1,o.tag=Wv.decode(e,t),t+=Wv.decode.bytes,o.value=Bv(e,t,n+r),o.issuerCritical=!!(o.flags&oE.ISSUER_CRITICAL),oE.decode.bytes=r+2,o},encodingLength:e=>Wv.encodingLength(e.tag)+Wv.encodingLength(e.value)+2});oE.ISSUER_CRITICAL=128;const sE=Kv({encode(e,t,r){t||(t=new Uint8Array(sE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Vv(t,e.preference||0,r),r+=2,Gv.encode(e.exchange,t,r),r+=Gv.encode.bytes,Vv(t,r-n-2,n),sE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.preference=Hv(e,t),t+=2,n.exchange=Gv.decode(e,t),t+=Gv.decode.bytes,sE.decode.bytes=t-r,n},encodingLength:e=>4+Gv.encodingLength(e.exchange)}),iE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(iE.encodingLength(e))),r||(r=0),Vv(t,4,r),r+=2,wv.encode(e,t,r),t),decode:(e,t)=>(t||(t=0),t+=2,wv.decode(e,t)),bytes:6}),aE=Kv({encode:(e,t,r)=>(t||(t=new Uint8Array(aE.encodingLength(e))),r||(r=0),Vv(t,16,r),r+=2,vv.encode(e,t,r),aE.encode.bytes=18,t),decode(e,t){t||(t=0),t+=2;const r=vv.decode(e,t);return aE.decode.bytes=18,r},bytes:18}),cE=e=>new Uint8Array(e),lE=Kv({encode(e,t,r){t||(t=new Uint8Array(lE.encodingLength(e))),r||(r=0);const n=r,o=Tv(e.code);if(Vv(t,o,r),r+=2,e.data)Vv(t,e.data.length,r),r+=2,zv(e.data,t,r),r+=e.data.length;else switch(o){case 8:{const n=e.sourcePrefixLength||0,o=e.family||function(e){return Ev(e)===wv.size?1:2}(e.ip),s=function(e,t,r){r=~~r;const n=Ev(e);return"function"==typeof t&&(t=t(r+n)),n===wv.size?wv.encode(e,t,r):vv.encode(e,t,r)}(e.ip,cE),i=Math.ceil(n/8);Vv(t,i+4,r),Vv(t,o,r+=2),r+=2,t[r++]=n,t[r++]=e.scopePrefixLength||0,zv(s,t,r,0,i),r+=i}break;case 11:e.timeout?(Vv(t,2,r),r+=2,Vv(t,e.timeout,r),r+=2):(Vv(t,0,r),r+=2);break;case 12:{const n=e.length||0;Vv(t,n,r),r+=2,t.fill(0,r,r+n),r+=n}break;case 14:{const n=2*e.tags.length;Vv(t,n,r),r+=2;for(const n of e.tags)Vv(t,n,r),r+=2}break;default:throw new Error(`Unknown roption code: ${e.code}`)}return lE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={};r.code=Hv(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=Hv(e,t+=2);switch(t+=2,r.data=e.slice(t,t+n),r.code){case 8:r.family=Hv(e,t),t+=2,r.sourcePrefixLength=e[t++],r.scopePrefixLength=e[t++];{const o=new Uint8Array(1===r.family?4:16);zv(e,o,0,t,t+n-4),r.ip=function(e,t,r){if(t=~~t,(r=r||e.length-t)===wv.size)return wv.decode(e,t,r);if(r===vv.size)return vv.decode(e,t,r);throw Error(`Invalid buffer size needs to be ${wv.size} for v4 or ${vv.size} for v6.`)}(o)}break;case 11:n>0&&(r.timeout=Hv(e,t),t+=2);break;case 14:r.tags=[];for(let o=0;o0;)n[s++]=lE.decode(e,t),t+=lE.decode.bytes,o-=lE.decode.bytes;return uE.decode.bytes=t-r,n},encodingLength:e=>2+TE(e||[],lE)}),hE=Kv({encode(e,t,r){t||(t=new Uint8Array(hE.encodingLength(e))),r||(r=0);const n=r,o=e.key;if(!Ov(o))throw new Error("Key must be a Buffer");return r+=2,Vv(t,e.flags,r),t[r+=2]=hE.PROTOCOL_DNSSEC,t[r+=1]=e.algorithm,zv(o,t,r+=1,0,o.length),r+=o.length,hE.encode.bytes=r-n,Vv(t,hE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);if(t+=2,n.flags=Hv(e,t),e[t+=2]!==hE.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return t+=1,n.algorithm=e[t],t+=1,n.key=e.slice(t,r+o+2),t+=n.key.length,hE.decode.bytes=t-r,n},encodingLength:e=>6+Rv(e.key)});hE.PROTOCOL_DNSSEC=3,hE.ZONE_KEY=128,hE.SECURE_ENTRYPOINT=32768;const dE=Kv({encode(e,t,r){t||(t=new Uint8Array(dE.encodingLength(e))),r||(r=0);const n=r,o=e.signature;if(!Ov(o))throw new Error("Signature must be a Buffer");return r+=2,Vv(t,Av(e.typeCovered),r),t[r+=2]=e.algorithm,t[r+=1]=e.labels,r+=1,jv(t,e.originalTTL,r),r+=4,jv(t,e.expiration,r),r+=4,jv(t,e.inception,r),r+=4,Vv(t,e.keyTag,r),r+=2,Gv.encode(e.signersName,t,r),zv(o,t,r+=Gv.encode.bytes,0,o.length),r+=o.length,dE.encode.bytes=r-n,Vv(t,dE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);return t+=2,n.typeCovered=Sv(Hv(e,t)),t+=2,n.algorithm=e[t],t+=1,n.labels=e[t],t+=1,n.originalTTL=qv(e,t),t+=4,n.expiration=qv(e,t),t+=4,n.inception=qv(e,t),t+=4,n.keyTag=Hv(e,t),t+=2,n.signersName=Gv.decode(e,t),t+=Gv.decode.bytes,n.signature=e.slice(t,r+o+2),t+=n.signature.length,dE.decode.bytes=t-r,n},encodingLength:e=>20+Gv.encodingLength(e.signersName)+Rv(e.signature)}),pE=Kv({encode(e,t,r){t||(t=new Uint8Array(pE.encodingLength(e))),r||(r=0);const n=r;return r+=2,Gv.encode(e.mbox||".",t,r),r+=Gv.encode.bytes,Gv.encode(e.txt||".",t,r),r+=Gv.encode.bytes,pE.encode.bytes=r-n,Vv(t,pE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={};return t+=2,n.mbox=Gv.decode(e,t)||".",t+=Gv.decode.bytes,n.txt=Gv.decode(e,t)||".",t+=Gv.decode.bytes,pE.decode.bytes=t-r,n},encodingLength:e=>2+Gv.encodingLength(e.mbox||".")+Gv.encodingLength(e.txt||".")}),fE=Kv({encode(e,t,r){t||(t=new Uint8Array(fE.encodingLength(e))),r||(r=0);const n=r,o=[];for(let t=0;t>8]&&(o[r>>8]=[]),o[r>>8][r>>3&31]|=1<<7-(7&r)}for(let e=0;e>8]=Math.max(t[n>>8]||0,255&n)}let r=0;for(let e=0;e2+Gv.encodingLength(e.nextDomain)+fE.encodingLength(e.rrtypes)}),mE=Kv({encode(e,t,r){t||(t=new Uint8Array(mE.encodingLength(e))),r||(r=0);const n=r,o=e.salt;if(!Ov(o))throw new Error("salt must be a Buffer");const s=e.nextDomain;if(!Ov(s))throw new Error("nextDomain must be a Buffer");return t[r+=2]=e.algorithm,t[r+=1]=e.flags,r+=1,Vv(t,e.iterations,r),t[r+=2]=o.length,zv(o,t,r+=1,0,o.length),t[r+=o.length]=s.length,zv(s,t,r+=1,0,s.length),r+=s.length,fE.encode(e.rrtypes,t,r),r+=fE.encode.bytes,mE.encode.bytes=r-n,Vv(t,mE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);t+=2,n.algorithm=e[t],t+=1,n.flags=e[t],t+=1,n.iterations=Hv(e,t);const s=e[t+=2];t+=1,n.salt=e.slice(t,t+s);const i=e[t+=s];return t+=1,n.nextDomain=e.slice(t,t+i),t+=i,n.rrtypes=fE.decode(e,t,o-(t-r)),t+=fE.decode.bytes,mE.decode.bytes=t-r,n},encodingLength:e=>8+e.salt.length+e.nextDomain.length+fE.encodingLength(e.rrtypes)}),yE=Kv({encode(e,t,r){t||(t=new Uint8Array(yE.encodingLength(e))),r||(r=0);const n=r,o=e.digest;if(!Ov(o))throw new Error("Digest must be a Buffer");return r+=2,Vv(t,e.keyTag,r),t[r+=2]=e.algorithm,t[r+=1]=e.digestType,zv(o,t,r+=1,0,o.length),r+=o.length,yE.encode.bytes=r-n,Vv(t,yE.encode.bytes-2,n),t},decode(e,t){t||(t=0);const r=t,n={},o=Hv(e,t);return t+=2,n.keyTag=Hv(e,t),t+=2,n.algorithm=e[t],t+=1,n.digestType=e[t],t+=1,n.digest=e.slice(t,r+o+2),t+=n.digest.length,yE.decode.bytes=t-r,n},encodingLength:e=>6+Rv(e.digest)});function bE(e){switch(e.toUpperCase()){case"A":return iE;case"PTR":case"CNAME":case"DNAME":return rE;case"TXT":return Qv;case"NULL":return eE;case"AAAA":return aE;case"SRV":return nE;case"HINFO":return tE;case"CAA":return oE;case"NS":return Yv;case"SOA":return Zv;case"MX":return sE;case"OPT":return uE;case"DNSKEY":return hE;case"RRSIG":return dE;case"RP":return pE;case"NSEC":return gE;case"NSEC3":return mE;case"DS":return yE}return Xv}const wE=Kv({encode(e,t,r){t||(t=new Uint8Array(wE.encodingLength(e))),r||(r=0);const n=r;if(Gv.encode(e.name,t,r),r+=Gv.encode.bytes,Vv(t,Av(e.type),r),"OPT"===e.type.toUpperCase()){if("."!==e.name)throw new Error("OPT name must be root.");Vv(t,e.udpPayloadSize||4096,r+2),t[r+4]=e.extendedRcode||0,t[r+5]=e.ednsVersion||0,Vv(t,e.flags||0,r+6),r+=8,uE.encode(e.options||[],t,r),r+=uE.encode.bytes}else{let n=xv(void 0===e.class?"IN":e.class);e.flush&&(n|=32768),Vv(t,n,r+2),jv(t,e.ttl||0,r+4),r+=8;const o=bE(e.type);o.encode(e.data,t,r),r+=o.encode.bytes}return wE.encode.bytes=r-n,t},decode(e,t){t||(t=0);const r={},n=t;if(r.name=Gv.decode(e,t),t+=Gv.decode.bytes,r.type=Sv(Hv(e,t)),"OPT"===r.type)r.udpPayloadSize=Hv(e,t+2),r.extendedRcode=e[t+4],r.ednsVersion=e[t+5],r.flags=Hv(e,t+6),r.flag_do=1==(r.flags>>15&1),r.options=uE.decode(e,t+8),t+=8+uE.decode.bytes;else{const n=Hv(e,t+2);r.ttl=qv(e,t+4),r.class=Iv(-32769&n),r.flush=!!(32768&n);const o=bE(r.type);r.data=o.decode(e,t+8),t+=8+o.decode.bytes}return wE.decode.bytes=t-n,r},encodingLength(e){const t=null!==e.data&&void 0!==e.data?e.data:e.options;return Gv.encodingLength(e.name)+8+bE(e.type).encodingLength(t)}}),vE=Kv({encode(e,t,r){t||(t=new Uint8Array(vE.encodingLength(e))),r||(r=0);const n=r;return Gv.encode(e.name,t,r),r+=Gv.encode.bytes,Vv(t,Av(e.type),r),r+=2,Vv(t,xv(void 0===e.class?"IN":e.class),r),r+=2,vE.encode.bytes=r-n,e},decode(e,t){t||(t=0);const r=t,n={};return n.name=Gv.decode(e,t),t+=Gv.decode.bytes,n.type=Sv(Hv(e,t)),t+=2,n.class=Iv(Hv(e,t)),t+=2,!!(32768&n.class)&&(n.class&=-32769),vE.decode.bytes=t-r,n},encodingLength:e=>Gv.encodingLength(e.name)+4}),EE={encode:function(e,t,r){const n=!t;n&&(t=new Uint8Array(xE(e))),r||(r=0);const o=r;return e.questions||(e.questions=[]),e.answers||(e.answers=[]),e.authorities||(e.authorities=[]),e.additionals||(e.additionals=[]),Jv.encode(e,t,r),r+=Jv.encode.bytes,r=_E(e.questions,vE,t,r),r=_E(e.answers,wE,t,r),r=_E(e.authorities,wE,t,r),r=_E(e.additionals,wE,t,r),EE.encode.bytes=r-o,n&&CE.bytes!==t.length?t.slice(0,CE.bytes):t},decode:function(e,t){t||(t=0);const r=t,n=Jv.decode(e,t);return t+=Jv.decode.bytes,t=NE(n.questions,vE,e,t),t=NE(n.answers,wE,e,t),t=NE(n.authorities,wE,e,t),t=NE(n.additionals,wE,e,t),EE.decode.bytes=t-r,n},encodingLength:function(e){return Jv.encodingLength(e)+TE(e.questions||[],vE)+TE(e.answers||[],wE)+TE(e.authorities||[],wE)+TE(e.additionals||[],wE)}};function SE(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}EE.encode.bytes=0,EE.decode.bytes=0;const AE={encode:function(e,t,r){return t=EE.encode(SE(e,"query"),t,r),AE.encode.bytes=EE.encode.bytes,t},decode:function(e,t){const r=EE.decode(e,t);return AE.decode.bytes=EE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return EE.encodingLength(SE(e,"query"))}};AE.encode.bytes=0,AE.decode.bytes=0;const kE={encode:function(e,t,r){return t=EE.encode(SE(e,"response"),t,r),kE.encode.bytes=EE.encode.bytes,t},decode:function(e,t){const r=EE.decode(e,t);return kE.decode.bytes=EE.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(e){return EE.encodingLength(SE(e,"response"))}};kE.encode.bytes=0,kE.decode.bytes=0;const CE=EE.encode,IE=EE.decode,xE=EE.encodingLength;function TE(e,t){let r=0;for(let n=0;n255)throw new Error(`Character #${e} in charset [code=${r}, char=${t.charAt(e)}] is too high! (max=255)`);if(0!==o[r])throw new Error(`Character [code=${r}, char=${t.charAt(e)}] is more than once in the charset!`);o[r]=e,s[e]=r}const i=r.charCodeAt(0),a={name:e,encodingLength(e){const t=e.length,r=.75*t|0;return e.charCodeAt(t-1)===i?e.charCodeAt(t-2)===i?r-2:r-1:r},encode(e,t,r){null==t&&(t=new Uint8Array(a.encodingLength(e))),null==r&&(r=0);let n=e.length;e.charCodeAt(n-1)===i&&(e.charCodeAt(n-2)===i?n-=2:n-=1);const s=n%4,c=n-s;let l=r,u=0;for(;u>16,t[l++]=r>>8,t[l++]=r,u+=4}if(3===s){const r=o[e.charCodeAt(u)]<<10|o[e.charCodeAt(u+1)]<<4|o[e.charCodeAt(u+2)]>>2;t[l++]=r>>8,t[l++]=r}else 2===s&&(t[l++]=o[e.charCodeAt(u)]<<2|o[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 o=r-t,c=o%3,l=t+o-c,u=[];for(let r=t;r>18&63],s[t>>12&63],s[t>>6&63],s[63&t])}if(2===c){const t=(e[r-2]<<8)+e[r-1];u.push(s[t>>10],s[t>>4&63],s[t<<2&63]),1===n&&u.push(i)}else if(1===c){const t=e[r-1];u.push(s[t>>2],s[t<<4&63]),1===n&&u.push(i,i)}return a.decode.bytes=o,String.fromCharCode.apply(String,u)}};return a}PE("base64","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/","=",1);const LE=PE("base64-url","ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_","=",2);let BE="undefined"!=typeof global?global.AbortError:"undefined"!=typeof window?window.AbortError:null;BE||(BE=class extends Error{constructor(e="Request aborted."){super(e)}}),BE.prototype.name="AbortError",BE.prototype.code="ABORT_ERR";const OE="undefined"!=typeof globalThis&&globalThis.URL||require("url").URL;class RE 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}}}RE.prototype.name="HTTPStatusError",RE.prototype.code="HTTP_STATUS";class DE extends Error{constructor(e,t){super(e),this.cause=t}toJSON(){return{message:this.message,endpoint:this.endpoint,code:this.code,cause:$E(this.cause)}}}DE.prototype.name="ResponseError",DE.prototype.code="RESPONSE_ERR";class UE extends Error{constructor(e){super("Timeout (t="+e+")."),this.timeout=e}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}UE.prototype.name="TimeoutError",UE.prototype.code="ETIMEOUT";const ME=/^((\d{1,3}\.){3,3}\d{1,3})(:(\d{2,5}))?$/,FE=/^((::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\d{2,5}))?$/i;function $E(e){if("string"==typeof e)return{message:e};try{const t=JSON.stringify(e);if("{}"!==t)return JSON.parse(t)}catch(e){}const t={message:String(e.message||e)};return void 0!==e.code&&(t.code=String(e.code)),t}const qE=/^(([a-z0-9]+:)\/\/)?([^/[\s:]+|\[[^\]]+\])?(:([^/\s]+))?(\/[^\s]*)?(.*)$/,HE=/\[(post|get|((ipv4|ipv6|name)=([^\]]+)))\]/gi,jE=/\[(((pk|name)=([^\]]+)))\]/gi;function VE(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 zE extends Error{constructor(e,t){super(`Invalid Endpoint: unsupported protocol "${e}" for endpoint: ${t}, supported protocols: ${KE.join(", ")}`),this.protocol=e,this.endpoint=t}toJSON(){return{code:this.code,endpoint:this.endpoint,timeout:this.timeout}}}zE.prototype.name="InvalidProtocolError",zE.prototype.code="EPROTOCOL";const KE=["http:","https:","udp4:","udp6:"];class GE{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 WE extends GE{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 JE extends WE{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 XE extends WE{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 YE(e){return FE.test(e)&&!ME.test(e)?`[${e}]`:e}class ZE extends GE{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=FE.exec(this.host);e&&(this.ipv6=e[1])}this.ipv4||ME.test(this.host)&&(this.ipv4=this.host);const t=`${this.protocol}//${YE(this.host)}:${this.port}${this.path}`;try{this.url=new OE(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,o=this.name?` [name=${this.name}]`:"",s=this.ipv4&&this.ipv4!==this.host?` [ipv4=${this.ipv4}]`:"",i=this.ipv6&&this.ipv6!==this.host?` [ipv6=${this.ipv6}]`:"";return`${e}${YE(this.host)}${t}${n}${r}${s}${i}${o}`}}function QE(e){let t;if("string"==typeof e)t=function(e){const t=qE.exec(e),r=t[2]||"https:",n=t[3],o=t[5],s=t[6],i=t[7];if("https:"===r||"http:"===r){const e=VE(i,HE);return{name:e.name,protocol:r,ipv4:e.ipv4,ipv6:e.ipv6,host:n,port:o,path:s,method:e.post?"POST":"GET"}}if("udp:"===r||"udp4:"===r||"udp6:"===r){const t=VE(i,jE),s=/^\[(.*)\]$/.exec(n);if(s&&"udp4:"===r)throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${e})`);if(!s&&"udp6:"===r)throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${e})`);return s?new XE({protocol:"udp6:",ipv6:s[1],port:o,pk:t.pk,name:t.name}):new JE({protocol:"udp4:",ipv4:n,port:o,pk:t.pk,name:t.name})}throw new zE(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 GE)return e;t=e}null!==t.protocol&&void 0!==t.protocol||(t.protocol="https:");const r=t.protocol;if("udp4:"===r)return new JE(t);if("udp6:"===r)return new XE(t);if("https:"===r||"http:"===r)return new ZE(t);throw new zE(r,JSON.stringify(t))}const eS="application/dns-message";function tS(){}function rS(e,t,r,n,o){return new Promise(((s,i)=>{const a=new OE(e);"GET"===t&&r&&(a.search="?dns="+LE.decode(r));const c=a.toString(),l=new XMLHttpRequest;l.open(t,c,!0),l.setRequestHeader("Accept",eS),"POST"===t&&l.setRequestHeader("Content-Type",eS),l.responseType="arraybuffer",l.timeout=n,l.ontimeout=function(){u(new UE(n));try{l.abort()}catch(e){}},l.onreadystatechange=function(){if(l.readyState>1&&200!==l.status&&0!==l.status){u(new RE(c,l.status,t));try{l.abort()}catch(e){}}},l.onerror=function(){u(200===l.status?new Error("Inexplicable XHR Error"):new RE(c,l.status,t))},l.onload=function(){if(200!==l.status)u(new RE(c,l.status,t));else{let e;if("string"==typeof l.response)e=Lv(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(),o&&o.addEventListener("abort",h);let u=function(e,t){u=tS,o&&o.removeEventListener("abort",h),s(e?{error:e,response:l}:{data:t,response:l})};function h(){u(new BE);try{l.abort()}catch(e){}}}))}function nS(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=QE(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 oS=nS({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 sS=new OE("https://martinheidegger.github.io/dns-query/resolvers.json");function iS(e){return/^@/.test(e)}const aS=new class{constructor(e){this.opts=Object.assign({timeout:5e3,update:!0,updateURL:sS,persist:!1,localStoragePrefix:"dnsquery_",maxAge:3e5},e),this._dataP=null}_data(e,t){return e||null===this._dataP?(this._dataP=this.opts.update?async function(e,t,r){const n=t?t.localStoragePrefix+t.name:null;if(n)try{const e=JSON.parse(localStorage.getItem(n));if(e&&e.time>t.maxTime)return e}catch(e){}const{data:o}=await rS(e,"GET",null,r,void 0),s={time:Date.now(),data:JSON.parse(Bv(o))};if(n)try{localStorage.setItem(n,JSON.stringify(s))}catch(e){s.time=null}return s}(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=>nS({data:e.data.resolvers,time:e.time}))).catch((()=>t||oS)):Promise.resolve(oS),this._dataP):this._dataP.then((e=>e.timee.data))}endpoints(e){if(null==e)return this.data().then((e=>e.endpoints));if("doh"===e&&(e=uS),"dns"===e&&(e=hS),"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(iS))try{return Promise.resolve(e.map(QE))}catch(e){return Promise.reject(e)}return this.data().then((t=>e.map((e=>{if(iS(e)){const r=t.endpointByName[e.substring(1)];if(!r)throw new Error(`Endpoint ${e} is not known.`);return r}return QE(e)}))))}};function cS(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 lS(r.map(QE),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 lS(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 BE):"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,o){return rS(e,t,r,n,o)}(e.url,e.method,CE(Object.assign({flags:256},t)),r,n).then((function(e){const t=e.data,r=e.response;let n=e.error;if(void 0===n)if(0===t.length)n=new DE("Empty.");else try{const e=IE(t);return e.response=r,e}catch(e){n=new DE("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)),(o=>{if("AbortError"===o.name||0===r.retries)throw o.endpoint=n.toString(),o;return r.retries>0&&(r.retries-=1),lS(e,t,r)}))}function uS(e){return"https:"===e.protocol||"http:"===e.protocol}function hS(e){return"udp4:"===e.protocol||"udp6:"===e.protocol}const dS=new gn("dns-over-https");class pS{endpoints;retries;static async create(e,t){const r=e??await aS.endpoints("doh");return new pS(r,t)}constructor(e,t=3){this.endpoints=e,this.retries=t}async resolveTXT(e){let t;try{t=(await cS({question:{type:"TXT",name:e}},{endpoints:this.endpoints,retries:this.retries})).answers}catch(e){throw dS.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(tn(e))})):n.push(tn(e))})),n}}var fS=__webpack_require__(5818);class gS{static RECORD_PREFIX=jw.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=gS.parseRootValues(e),n=fS.decode.asBytes(t),o=e.split(" sig")[0],s=rn(o);if(!Tw(xt(r.signature,"base64url").slice(0,64),xw(s),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,o,s]=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(!o)throw new Error("Could not parse 'seq' value from ENRTree root entry");if(!s)throw new Error("Could not parse 'sig' value from ENRTree root entry");return{eRoot:r,lRoot:n,seq:Number(o),signature:s}}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 mS=new gn("discovery:fetch_nodes");function yS(e,t){return t.relay>=e.relay&&t.store>=e.store&&t.filter>=e.filter&&t.lightPush>=e.lightPush}function bS(e,t){if(!e.nodeId)return!1;for(const r of t)if(e.nodeId===r.nodeId)return!1;return!0}function wS(e,t){e.relay&&(t.relay+=1),e.store&&(t.store+=1),e.filter&&(t.filter+=1),e.lightPush&&(t.lightPush+=1)}function vS(e,t,r){if(yS(t,r))throw"Internal Error: Waku2 wanted capabilities are already fulfilled";const n=function(e,t){return{relay:t.relaythis._search(o,s)));return ES.info("retrieved peers: ",i.map((e=>({id:e.peerId?.toString(),multiaddrs:e.multiaddrs?.map((e=>e.toString()))})))),i}constructor(e){this._DNSTreeCache={},this.dns=e}async*getNextPeer(e,t){const r=Math.floor(Math.random()*e.length),{publicKey:n,domain:o}=gS.parseTree(e[r]),s={domain:o,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},o=n.relay+n.store+n.filter+n.lightPush,s={relay:0,store:0,filter:0,lightPush:0};let i=0;const a=new Set;for(;!yS(n,s)&&ithis._search(o,s))))yield e}async _search(e,t){try{const r=await this._getTXTRecord(e,t);let n,o;t.visits[e]=!0;const s=function(e){return e.startsWith(gS.ROOT_PREFIX)?gS.ROOT_PREFIX:e.startsWith(gS.BRANCH_PREFIX)?gS.BRANCH_PREFIX:e.startsWith(gS.RECORD_PREFIX)?gS.RECORD_PREFIX:""}(r);try{switch(s){case gS.ROOT_PREFIX:return n=gS.parseAndVerifyRoot(r,t.publicKey),await this._search(n,t);case gS.BRANCH_PREFIX:return o=gS.parseBranch(r),n=function(e,t){const r={};for(const[n,o]of e.entries())t.visits[o]&&(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]}(o,t),await this._search(n,t);case gS.RECORD_PREFIX:return mv.fromString(r);default:return null}}catch(t){return ES.error(`Failed to search DNS tree ${s} at subdomain ${e}: ${t}`),null}}catch(t){return ES.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 o=n.join("");return this._DNSTreeCache[e]=o,o}}const AS=new gn("peer-discovery-dns");class kS extends xo{nextPeer;_started;_components;_options;constructor(e,t){super(),this._started=!1,this._components=e,this._options=t;const{enrUrls:r}=t;AS.info("Use following EIP-1459 ENR Tree URLs: ",r)}async start(){AS.info("Starting peer discovery via dns"),this._started=!0,await this.findPeers()}async findPeers(){if(!this.nextPeer){let{enrUrls:e}=this._options;Array.isArray(e)||(e=[e]);const{wantedNodeCapabilityCount:t}=this._options,r=await SS.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={[Ib]:{value:this._options.tagValue??50,ttl:this._options.tagTTL??1e8}};let o=!1;await this._components.peerStore.has(t.id)?(await this._components.peerStore.get(t.id)).tags.has(Ib)||(o=!0,await this._components.peerStore.merge(t.id,{tags:n})):(o=!0,await this._components.peerStore.save(t.id,{tags:n,...r&&{metadata:{shardInfo:dn(r)}}})),o&&this.dispatchEvent(new CustomEvent("peer",{detail:t}))}}stop(){this._started=!1}get[Ad](){return!0}get[Symbol.toStringTag](){return Jr}}function CS(e,t=xb){return r=>new kS(r,{enrUrls:e,wantedNodeCapabilityCount:t})}function IS(e){return e.filter((e=>"open"===e.status)).sort(((e,t)=>t.timeline.open-e.timeline.open)).at(0)}const xS="consumed";class TS{multicodec;getConnections;addEventListener;log;ongoingCreation=new Set;streamPool=new Map;constructor(e,t,r){this.multicodec=e,this.getConnections=t,this.addEventListener=r,this.log=new gn(`stream-manager:${e}`),this.addEventListener("peer:update",this.handlePeerUpdateStreamPool)}async getStream(e){const t=e.id.toString(),r=this.streamPool.get(t);r&&(this.streamPool.delete(t),await r);let n=this.getOpenStreamForCodec(e.id);return n?(this.log.info(`Found existing stream peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.lockStream(e.id.toString(),n),n):(n=await this.createStream(e),this.lockStream(e.id.toString(),n),n)}async createStream(e,t=0){const r=IS(this.getConnections(e.id));if(!r)throw new Error(`Failed to get a connection to the peer peerId=${e.id.toString()} multicodec=${this.multicodec}`);let n,o;for(let s=0;s{const{peer:t}=e.detail;t.protocols.includes(this.multicodec)&&(this.getOpenStreamForCodec(t.id)||this.scheduleNewStream(t))};scheduleNewStream(e){this.log.info(`Scheduling creation of a stream for peerId=${e.id.toString()} multicodec=${this.multicodec}`),this.streamPool.has(e.id.toString())&&this.streamPool.delete(e.id.toString()),this.streamPool.set(e.id.toString(),this.createStreamWithLock(e))}getOpenStreamForCodec(e){const t=IS(this.getConnections(e));if(!t)return;const r=t.streams.find((e=>e.protocol===this.multicodec));return r?["done","closed","closing"].includes(r.writeStatus||"")||this.isStreamLocked(r)?void 0:r:void 0}lockStream(e,t){this.log.info(`Locking stream for peerId:${e}\tstreamId:${t.id}`),t.metadata[xS]=!0}isStreamLocked(e){return!!e.metadata[xS]}}class _S{multicodec;components;pubsubTopics;addLibp2pEventListener;removeLibp2pEventListener;streamManager;constructor(e,t,r){this.multicodec=e,this.components=t,this.pubsubTopics=r,this.addLibp2pEventListener=t.events.addEventListener.bind(t.events),this.removeLibp2pEventListener=t.events.removeEventListener.bind(t.events),this.streamManager=new TS(e,t.connectionManager.getConnections.bind(t.connectionManager),this.addLibp2pEventListener)}async getStream(e){return this.streamManager.getStream(e)}}class NS{proto;constructor(e){this.proto=e}static createRequest(e){const{numPeers:t}=e;return new NS({query:{numPeers:t},response:void 0})}encode(){return gr.encode(this.proto)}static decode(e){const t=gr.decode(e);return new NS(t)}get query(){return this.proto.query}get response(){return this.proto.response}}const PS="/vac/waku/peer-exchange/2.0.0-alpha1",LS=new gn("peer-exchange");class BS extends _S{constructor(e,t){super(PS,e,t)}async query(e){const{numPeers:t,peerId:r}=e,n=NS.createRequest({numPeers:BigInt(t)}),o=await this.components.peerStore.get(r);if(!o)return{peerInfos:null,error:zr.NO_PEER_AVAILABLE};let s;try{s=await this.getStream(o)}catch(e){return LS.error("Failed to get stream",e),{peerInfos:null,error:zr.NO_STREAM_AVAILABLE}}const i=await Kn([n.encode()],Ln,s,Fn,(async e=>await An(e)));try{const e=new _n;i.forEach((t=>{e.append(t)}));const{response:t}=NS.decode(e);return t?{peerInfos:await Promise.all(t.peerInfos.map((e=>e.enr)).filter(Ar).map((async e=>({ENR:await mv.fromRLP(e)})))),error:null}:(LS.error("PeerExchangeRPC message did not contains a `response` field"),{peerInfos:null,error:zr.EMPTY_PAYLOAD})}catch(e){return LS.error("Failed to decode push reply",e),{peerInfos:null,error:zr.DECODE_FAILED}}}}const OS=new gn("peer-exchange-discovery"),RS=1e4,DS=3,US=Kr.PEER_EXCHANGE;class MS extends xo{components;peerExchange;options;isStarted;queryingPeers=new Set;queryAttempts=new Map;handleDiscoveredPeer=e=>{const{protocols:t,peerId:r}=e.detail;t.includes(PS)&&!this.queryingPeers.has(r.toString())&&(this.queryingPeers.add(r.toString()),this.startRecurringQueries(r).catch((e=>OS.error(`Error querying peer ${e}`))))};constructor(e,t,r={}){super(),this.components=e,this.peerExchange=new BS(e,t),this.options=r,this.isStarted=!1}start(){this.isStarted||(this.dispatchEvent(new CustomEvent("waku:peer-exchange:started",{detail:!0})),OS.info("Starting peer exchange node discovery, discovering peers"),this.components.events.addEventListener("peer:identify",this.handleDiscoveredPeer))}stop(){this.isStarted&&(OS.info("Stopping peer exchange node discovery"),this.isStarted=!1,this.queryingPeers.clear(),this.components.events.removeEventListener("peer:identify",this.handleDiscoveredPeer))}get[Ad](){return!0}get[Symbol.toStringTag](){return"@waku/peer-exchange"}startRecurringQueries=async e=>{const t=e.toString(),{queryInterval:r=RS,maxRetries:n=DS}=this.options;OS.info(`Querying peer: ${t} (attempt ${this.queryAttempts.get(t)??1})`),await this.query(e);const o=this.queryAttempts.get(t)??1;o>n?this.abortQueriesForPeer(t):setTimeout((()=>{this.queryAttempts.set(t,o+1),this.startRecurringQueries(e).catch((e=>{OS.error(`Error in startRecurringQueries: ${e}`)}))}),r*o)};async query(e){const{error:t,peerInfos:r}=await this.peerExchange.query({numPeers:10,peerId:e});if(t)return OS.error("Peer exchange query failed",t),{error:t,peerInfos:null};for(const e of r){const{ENR:t}=e;if(!t){OS.warn("No ENR in peerInfo object, skipping");continue}const{peerId:r,peerInfo:n,shardInfo:o}=t;if(r&&n){if(await this.components.peerStore.has(r)){const{hasMultiaddrDiff:e,hasShardDiff:t}=await this.checkPeerInfoDiff(n,o);if(e||t){OS.info(`Peer ${r.toString()} has updated multiaddrs or shardInfo, updating`),e&&(OS.info(`Peer ${r.toString()} has updated multiaddrs, updating`),await this.components.peerStore.patch(r,{multiaddrs:n.multiaddrs})),t&&o&&(OS.info(`Peer ${r.toString()} has updated shardInfo, updating`),await this.components.peerStore.merge(r,{metadata:{shardInfo:dn(o)}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}})));continue}}await this.components.peerStore.save(r,{tags:{[US]:{value:this.options.tagValue??50,ttl:this.options.tagTTL??1e8}},...o&&{metadata:{shardInfo:dn(o)}},...n.multiaddrs&&{multiaddrs:n.multiaddrs}}),OS.info(`Discovered peer: ${r.toString()}`),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:n.multiaddrs}}))}}return{error:null,peerInfos:r}}abortQueriesForPeer(e){OS.info(`Aborting queries for peer: ${e}`),this.queryingPeers.delete(e),this.queryAttempts.delete(e)}async checkPeerInfoDiff(e,t){const{id:r}=e,n=await this.components.peerStore.get(r),o=n.addresses.map((e=>e.multiaddr.toString())),s=e.multiaddrs.map((e=>e.toString())),i=o.some((e=>!s.includes(e)));let a=!1;const c=n.metadata.get("shardInfo");if(c){const e=hn(c);(e||t)&&(a=e.clusterId!==t?.clusterId||e.shards.some((e=>!t?.shards.includes(e))))}return{hasMultiaddrDiff:i,hasShardDiff:a}}}function FS(e){return t=>new MS(t,e)}const $S=new gn("peer-exchange-discovery"),qS=Kr.LOCAL;class HS extends xo{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){$S.info("Starting Local Storage Discovery"),this.components.events.addEventListener("peer:identify",this.handleNewPeers);for(const{id:e,address:t}of this.peers){const r=nh(e);await this.components.peerStore.has(r)||(await this.components.peerStore.save(r,{multiaddrs:[Is(t)],tags:{[this.options?.tagName??qS]:{value:this.options?.tagValue??50,ttl:this.options?.tagTTL??1e8}}}),this.dispatchEvent(new CustomEvent("peer",{detail:{id:r,multiaddrs:[Is(t)]}})))}$S.info(`Discovered ${this.peers.length} peers`),this.isStarted=!0}}stop(){this.isStarted&&($S.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),o=this.getPeersFromLocalStorage(),s=o.findIndex((e=>e.id===t.toString()));s>=0?o[s].address=n.toString():o.push({id:t.toString(),address:n.toString()}),this.peers=o,this.savePeersToLocalStorage()};getPeersFromLocalStorage(){try{const e=localStorage.getItem("waku:peers");return e?JSON.parse(e).filter(jS):[]}catch(e){return $S.error("Error parsing peers from local storage:",e),[]}}savePeersToLocalStorage(){try{localStorage.setItem("waku:peers",JSON.stringify(this.peers))}catch(e){$S.error("Error saving peers to local storage:",e)}}}function jS(e){return e&&"object"==typeof e&&"string"==typeof e.id&&"string"==typeof e.address}const VS=new gn("sdk:create");async function zS(e,t,r){t?.hideWebSocketInfo||(console.info("%cIgnore WebSocket connection failures","background: gray; color: white; font-size: x-large"),console.info("%cWaku tries to discover peers and some of them are expected to fail","background: gray; color: white; font-size: x-large"));const n=e?{metadata:Mo(e)}:{};return async function(e={}){e.privateKey??=await zu("Ed25519");const t=new Cb({...await Mg(e),peerId:(r=e.privateKey,oh(r.publicKey))});var r;return!1!==e.start&&await t.start(),t}({transports:[yg({filter:!1===t?.filterMultiaddrs?fg:gg})],streamMuxers:[Gf()],connectionEncrypters:[Sd()],...t,services:{identify:vf({agentVersion:r??"js-waku"}),ping:Xf({maxInboundStreams:t?.pingMaxInboundStreams??10}),...n,...t?.services}})}async function KS(e={}){const{libp2p:t,pubsubTopics:r}=await async function(e){const{networkConfig:t}=e,r=function(e){if("clusterId"in(t=e)&&"shards"in t&&!("contentTopics"in t)){if(0===e.shards.length)throw new Error("Invalid shards configuration: please provide at least one shard");return on(e)}if(function(e){return"contentTopics"in e}(e)){if(0===e.contentTopics.length)throw new Error("Invalid content topics configuration: please provide at least one content topic");return e.contentTopics.map((t=>ln(t,e.clusterId)))}throw new Error("Unknown shard config. Please use ShardInfo or ContentTopicInfo");var t}(t??Xr);VS.info("Creating Waku node with pubsub topics",r);const n=e?.libp2p??{},o=n.peerDiscovery??[];var s;return e?.defaultBootstrap&&o.push(...function(e){return[CS(["enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im","enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"]),(e,t)=>new HS(e,t),FS(e)]}(r)),e?.bootstrapPeers&&o.push((s={list:e.bootstrapPeers},e=>new rp(e,s))),n.peerDiscovery=o,{libp2p:await zS(r,n,e?.userAgent),pubsubTopics:r}}(e);return new zs(r,e,t,{store:!0,lightpush:!0,filter:!0})}var GS,WS=__webpack_require__(2549),JS=function(e,t,r,n){return new(r||(r=Promise))((function(o,s){function i(e){try{c(n.next(e))}catch(e){s(e)}}function a(e){try{c(n.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))},XS=function(e,t){var r,n,o,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((o=(o=s.trys).length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]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 JS(this,void 0,void 0,(function(){var t,r,n,o=this;return XS(this,(function(s){switch(s.label){case 0:if(!window.location.hostname.includes("lab.waku.org"))return[2];t=e.map((function(e){return{id:++o.requestId,telemetryType:e.type.toString(),telemetryData:e}})),s.label=1;case 1:return s.trys.push([1,3,,4]),[4,fetch(this.url,{method:"POST",body:JSON.stringify(t)})];case 2:return 201!==(r=s.sent()).status?(console.log("DEBUG: Error sending messages to telemetry service: ",r.status,r.statusText,r.json),[2,!1]):[2,!0];case 3:return n=s.sent(),console.log("DEBUG: Error sending messages to telemetry service",n),[2,!1];case 4:return[2]}}))}))},e}(),ZS=function(){return ZS=Object.assign||function(e){for(var t,r=1,n=arguments.length;r0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]0&&o[o.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(\"@protobufjs/aspromise\"),\r\n inquire = require(\"@protobufjs/inquire\");\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","'use strict';\n\n/**\n * @typedef {{ [key: string]: any }} Extensions\n * @typedef {Error} Err\n * @property {string} message\n */\n\n/**\n *\n * @param {Error} obj\n * @param {Extensions} props\n * @returns {Error & Extensions}\n */\nfunction assign(obj, props) {\n for (const key in props) {\n Object.defineProperty(obj, key, {\n value: props[key],\n enumerable: true,\n configurable: true,\n });\n }\n\n return obj;\n}\n\n/**\n *\n * @param {any} err - An Error\n * @param {string|Extensions} code - A string code or props to set on the error\n * @param {Extensions} [props] - Props to set on the error\n * @returns {Error & Extensions}\n */\nfunction createError(err, code, props) {\n if (!err || typeof err === 'string') {\n throw new TypeError('Please pass an Error to err-code');\n }\n\n if (!props) {\n props = {};\n }\n\n if (typeof code === 'object') {\n props = code;\n code = '';\n }\n\n if (code) {\n props.code = code;\n }\n\n try {\n return assign(err, props);\n } catch (_) {\n props.message = err.message;\n props.stack = err.stack;\n\n const ErrClass = function () {};\n\n ErrClass.prototype = Object.create(Object.getPrototypeOf(err));\n\n // @ts-ignore\n const output = assign(new ErrClass(), props);\n\n return output;\n }\n}\n\nmodule.exports = createError;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst event_iterator_1 = require(\"./event-iterator\");\nexports.EventIterator = event_iterator_1.EventIterator;\nfunction subscribe(event, options, evOptions) {\n return new event_iterator_1.EventIterator(({ push }) => {\n this.addEventListener(event, push, options);\n return () => this.removeEventListener(event, push, options);\n }, evOptions);\n}\nexports.subscribe = subscribe;\nexports.default = event_iterator_1.EventIterator;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass EventQueue {\n constructor() {\n this.pullQueue = [];\n this.pushQueue = [];\n this.eventHandlers = {};\n this.isPaused = false;\n this.isStopped = false;\n }\n push(value) {\n if (this.isStopped)\n return;\n const resolution = { value, done: false };\n if (this.pullQueue.length) {\n const placeholder = this.pullQueue.shift();\n if (placeholder)\n placeholder.resolve(resolution);\n }\n else {\n this.pushQueue.push(Promise.resolve(resolution));\n if (this.highWaterMark !== undefined &&\n this.pushQueue.length >= this.highWaterMark &&\n !this.isPaused) {\n this.isPaused = true;\n if (this.eventHandlers.highWater) {\n this.eventHandlers.highWater();\n }\n else if (console) {\n console.warn(`EventIterator queue reached ${this.pushQueue.length} items`);\n }\n }\n }\n }\n stop() {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n for (const placeholder of this.pullQueue) {\n placeholder.resolve({ value: undefined, done: true });\n }\n this.pullQueue.length = 0;\n }\n fail(error) {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n if (this.pullQueue.length) {\n for (const placeholder of this.pullQueue) {\n placeholder.reject(error);\n }\n this.pullQueue.length = 0;\n }\n else {\n const rejection = Promise.reject(error);\n /* Attach error handler to avoid leaking an unhandled promise rejection. */\n rejection.catch(() => { });\n this.pushQueue.push(rejection);\n }\n }\n remove() {\n Promise.resolve().then(() => {\n if (this.removeCallback)\n this.removeCallback();\n });\n }\n [Symbol.asyncIterator]() {\n return {\n next: (value) => {\n const result = this.pushQueue.shift();\n if (result) {\n if (this.lowWaterMark !== undefined &&\n this.pushQueue.length <= this.lowWaterMark &&\n this.isPaused) {\n this.isPaused = false;\n if (this.eventHandlers.lowWater) {\n this.eventHandlers.lowWater();\n }\n }\n return result;\n }\n else if (this.isStopped) {\n return Promise.resolve({ value: undefined, done: true });\n }\n else {\n return new Promise((resolve, reject) => {\n this.pullQueue.push({ resolve, reject });\n });\n }\n },\n return: () => {\n this.isStopped = true;\n this.pushQueue.length = 0;\n this.remove();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n }\n}\nclass EventIterator {\n constructor(listen, { highWaterMark = 100, lowWaterMark = 1 } = {}) {\n const queue = new EventQueue();\n queue.highWaterMark = highWaterMark;\n queue.lowWaterMark = lowWaterMark;\n queue.removeCallback =\n listen({\n push: value => queue.push(value),\n stop: () => queue.stop(),\n fail: error => queue.fail(error),\n on: (event, fn) => {\n queue.eventHandlers[event] = fn;\n },\n }) || (() => { });\n this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();\n Object.freeze(this);\n }\n}\nexports.EventIterator = EventIterator;\nexports.default = EventIterator;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n","/*\n * [hi-base32]{@link https://github.com/emn178/hi-base32}\n *\n * @version 0.5.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var root = typeof window === 'object' ? window : {};\n var NODE_JS = !root.HI_BASE32_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n }\n var COMMON_JS = !root.HI_BASE32_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var BASE32_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('');\n var BASE32_DECODE_CHAR = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16,\n 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,\n 'Z': 25, '2': 26, '3': 27, '4': 28, '5': 29, '6': 30, '7': 31\n };\n\n var blocks = [0, 0, 0, 0, 0, 0, 0, 0];\n\n var throwInvalidUtf8 = function (position, partial) {\n if (partial.length > 10) {\n partial = '...' + partial.substr(-10);\n }\n var err = new Error('Decoded data is not valid UTF-8.'\n + ' Maybe try base32.decode.asBytes()?'\n + ' Partial data after reading ' + position + ' bytes: ' + partial + ' <-');\n err.position = position;\n throw err;\n };\n\n var toUtf8String = function (bytes) {\n var str = '', length = bytes.length, i = 0, followingChars = 0, b, c;\n while (i < length) {\n b = bytes[i++];\n if (b <= 0x7F) {\n str += String.fromCharCode(b);\n continue;\n } else if (b > 0xBF && b <= 0xDF) {\n c = b & 0x1F;\n followingChars = 1;\n } else if (b <= 0xEF) {\n c = b & 0x0F;\n followingChars = 2;\n } else if (b <= 0xF7) {\n c = b & 0x07;\n followingChars = 3;\n } else {\n throwInvalidUtf8(i, str);\n }\n\n for (var j = 0; j < followingChars; ++j) {\n b = bytes[i++];\n if (b < 0x80 || b > 0xBF) {\n throwInvalidUtf8(i, str);\n }\n c <<= 6;\n c += b & 0x3F;\n }\n if (c >= 0xD800 && c <= 0xDFFF) {\n throwInvalidUtf8(i, str);\n }\n if (c > 0x10FFFF) {\n throwInvalidUtf8(i, str);\n }\n\n if (c <= 0xFFFF) {\n str += String.fromCharCode(c);\n } else {\n c -= 0x10000;\n str += String.fromCharCode((c >> 10) + 0xD800);\n str += String.fromCharCode((c & 0x3FF) + 0xDC00);\n }\n }\n return str;\n };\n\n var decodeAsBytes = function (base32Str) {\n if (base32Str === '') {\n return [];\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n base32Str = base32Str.replace(/=/g, '');\n var v1, v2, v3, v4, v5, v6, v7, v8, bytes = [], index = 0, length = base32Str.length;\n\n // 4 char to 3 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n bytes[index++] = (v7 << 5 | v8) & 255;\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n }\n return bytes;\n };\n\n var encodeAscii = function (str) {\n var v1, v2, v3, v4, v5, base32Str = '', length = str.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i++);\n v5 = str.charCodeAt(i++);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encodeUtf8 = function (str) {\n var v1, v2, v3, v4, v5, code, end = false, base32Str = '',\n index = 0, i, start = 0, bytes = 0, length = str.length;\n if (str === '') {\n return base32Str;\n }\n do {\n blocks[0] = blocks[5];\n blocks[1] = blocks[6];\n blocks[2] = blocks[7];\n for (i = start; index < length && i < 5; ++index) {\n code = str.charCodeAt(index);\n if (code < 0x80) {\n blocks[i++] = code;\n } else if (code < 0x800) {\n blocks[i++] = 0xc0 | (code >> 6);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i++] = 0xe0 | (code >> 12);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++index) & 0x3ff));\n blocks[i++] = 0xf0 | (code >> 18);\n blocks[i++] = 0x80 | ((code >> 12) & 0x3f);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n }\n }\n bytes += i - start;\n start = i - 5;\n if (index === length) {\n ++index;\n }\n if (index > length && i < 6) {\n end = true;\n }\n v1 = blocks[0];\n if (i > 4) {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n v5 = blocks[4];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n } else if (i === 1) {\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (i === 2) {\n v2 = blocks[1];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (i === 3) {\n v2 = blocks[1];\n v3 = blocks[2];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n } while (!end);\n return base32Str;\n };\n\n var encodeBytes = function (bytes) {\n var v1, v2, v3, v4, v5, base32Str = '', length = bytes.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i++];\n v5 = bytes[i++];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = bytes[i++];\n v2 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encode = function (input, asciiOnly) {\n var notString = typeof(input) !== 'string';\n if (notString && input.constructor === ArrayBuffer) {\n input = new Uint8Array(input);\n }\n if (notString) {\n return encodeBytes(input);\n } else if (asciiOnly) {\n return encodeAscii(input);\n } else {\n return encodeUtf8(input);\n }\n };\n\n var decode = function (base32Str, asciiOnly) {\n if (!asciiOnly) {\n return toUtf8String(decodeAsBytes(base32Str));\n }\n if (base32Str === '') {\n return '';\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n var v1, v2, v3, v4, v5, v6, v7, v8, str = '', length = base32Str.indexOf('=');\n if (length === -1) {\n length = base32Str.length;\n }\n\n // 8 char to 5 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255) +\n String.fromCharCode((v7 << 5 | v8) & 255);\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255);\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255);\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255);\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255);\n }\n return str;\n };\n\n var exports = {\n encode: encode,\n decode: decode\n };\n decode.asBytes = decodeAsBytes;\n\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n root.base32 = exports;\n if (AMD) {\n define(function() {\n return exports;\n });\n }\n }\n})();\n","// https://github.com/electron/electron/issues/2288\nfunction isElectron() {\n // Renderer process\n if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {\n return true;\n }\n\n // Main process\n if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {\n return true;\n }\n\n // Detect the user agent when the `nodeIntegration` option is set to false\n if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = isElectron;\n","'use strict';\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n};\n","/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.9.3\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2023\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n\n var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray\n ? function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n }\n : Array.isArray;\n\n var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))\n ? function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n }\n : ArrayBuffer.isView;\n\n // [message: string, isString: bool]\n var formatMessage = function (message) {\n var type = typeof message;\n if (type === 'string') {\n return [message, true];\n }\n if (type !== 'object' || message === null) {\n throw new Error(INPUT_ERROR);\n }\n if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n return [new Uint8Array(message), false];\n }\n if (!isArray(message) && !isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n return [message, false];\n }\n\n var empty = function (message) {\n return formatMessage(message)[0].length === 0;\n };\n\n var cloneArray = function (array) {\n var newArray = [];\n for (var i = 0; i < array.length; ++i) {\n newArray[i] = array[i];\n }\n return newArray;\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (empty(n) && empty(s)) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var result = formatMessage(message);\n message = result[0];\n var isString = result[1];\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (isString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var result = formatMessage(str);\n str = result[0];\n var isString = result[1];\n var bytes = 0, length = str.length;\n if (isString) {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n } else {\n bytes = length;\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = (w - bytes % w) % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n array[j] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n define(function () {\n return methods;\n });\n }\n }\n})();\n","'use strict';\nconst isOptionObject = require('is-plain-obj');\n\nconst {hasOwnProperty} = Object.prototype;\nconst {propertyIsEnumerable} = Object;\nconst defineProperty = (object, name, value) => Object.defineProperty(object, name, {\n\tvalue,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true\n});\n\nconst globalThis = this;\nconst defaultMergeOptions = {\n\tconcatArrays: false,\n\tignoreUndefined: false\n};\n\nconst getEnumerableOwnPropertyKeys = value => {\n\tconst keys = [];\n\n\tfor (const key in value) {\n\t\tif (hasOwnProperty.call(value, key)) {\n\t\t\tkeys.push(key);\n\t\t}\n\t}\n\n\t/* istanbul ignore else */\n\tif (Object.getOwnPropertySymbols) {\n\t\tconst symbols = Object.getOwnPropertySymbols(value);\n\n\t\tfor (const symbol of symbols) {\n\t\t\tif (propertyIsEnumerable.call(value, symbol)) {\n\t\t\t\tkeys.push(symbol);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys;\n};\n\nfunction clone(value) {\n\tif (Array.isArray(value)) {\n\t\treturn cloneArray(value);\n\t}\n\n\tif (isOptionObject(value)) {\n\t\treturn cloneOptionObject(value);\n\t}\n\n\treturn value;\n}\n\nfunction cloneArray(array) {\n\tconst result = array.slice(0, 0);\n\n\tgetEnumerableOwnPropertyKeys(array).forEach(key => {\n\t\tdefineProperty(result, key, clone(array[key]));\n\t});\n\n\treturn result;\n}\n\nfunction cloneOptionObject(object) {\n\tconst result = Object.getPrototypeOf(object) === null ? Object.create(null) : {};\n\n\tgetEnumerableOwnPropertyKeys(object).forEach(key => {\n\t\tdefineProperty(result, key, clone(object[key]));\n\t});\n\n\treturn result;\n}\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {string[]} keys keys to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nconst mergeKeys = (merged, source, keys, config) => {\n\tkeys.forEach(key => {\n\t\tif (typeof source[key] === 'undefined' && config.ignoreUndefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Do not recurse into prototype chain of merged\n\t\tif (key in merged && merged[key] !== Object.getPrototypeOf(merged)) {\n\t\t\tdefineProperty(merged, key, merge(merged[key], source[key], config));\n\t\t} else {\n\t\t\tdefineProperty(merged, key, clone(source[key]));\n\t\t}\n\t});\n\n\treturn merged;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n *\n * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat)\n */\nconst concatArrays = (merged, source, config) => {\n\tlet result = merged.slice(0, 0);\n\tlet resultIndex = 0;\n\n\t[merged, source].forEach(array => {\n\t\tconst indices = [];\n\n\t\t// `result.concat(array)` with cloning\n\t\tfor (let k = 0; k < array.length; k++) {\n\t\t\tif (!hasOwnProperty.call(array, k)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tindices.push(String(k));\n\n\t\t\tif (array === merged) {\n\t\t\t\t// Already cloned\n\t\t\t\tdefineProperty(result, resultIndex++, array[k]);\n\t\t\t} else {\n\t\t\t\tdefineProperty(result, resultIndex++, clone(array[k]));\n\t\t\t}\n\t\t}\n\n\t\t// Merge non-index keys\n\t\tresult = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config);\n\t});\n\n\treturn result;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nfunction merge(merged, source, config) {\n\tif (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) {\n\t\treturn concatArrays(merged, source, config);\n\t}\n\n\tif (!isOptionObject(source) || !isOptionObject(merged)) {\n\t\treturn clone(source);\n\t}\n\n\treturn mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config);\n}\n\nmodule.exports = function (...options) {\n\tconst config = merge(clone(defaultMergeOptions), (this !== globalThis && this) || {}, defaultMergeOptions);\n\tlet merged = {_: {}};\n\n\tfor (const option of options) {\n\t\tif (option === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isOptionObject(option)) {\n\t\t\tthrow new TypeError('`' + option + '` is not an Option Object');\n\t\t}\n\n\t\tmerged = merge(merged, {_: option}, config);\n\t}\n\n\treturn merged._;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","module.exports = require('./lib/murmurHash3js');\n","/* jshint -W086: true */\n// +----------------------------------------------------------------------+\n// | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js\n// | A javascript implementation of MurmurHash3's x86 hashing algorithms. |\n// |----------------------------------------------------------------------|\n// | Copyright (c) 2012-2015 Karan Lyons |\n// | https://github.com/karanlyons/murmurHash3.js/blob/c1778f75792abef7bdd74bc85d2d4e1a3d25cfe9/murmurHash3.js |\n// | Freely distributable under the MIT license. |\n// +----------------------------------------------------------------------+\n\n;(function (root, undefined) {\n 'use strict';\n\n // Create a local object that'll be exported or referenced globally.\n var library = {\n 'version': '3.0.0',\n 'x86': {},\n 'x64': {},\n 'inputValidation': true\n };\n\n // PRIVATE FUNCTIONS\n // -----------------\n\n function _validBytes(bytes) {\n // check the input is an array or a typed array\n if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) {\n return false;\n }\n\n // check all bytes are actually bytes\n for (var i = 0; i < bytes.length; i++) {\n if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {\n return false;\n }\n }\n return true;\n }\n\n function _x86Multiply(m, n) {\n //\n // Given two 32bit ints, returns the two multiplied together as a\n // 32bit int.\n //\n\n return ((m & 0xffff) * n) + ((((m >>> 16) * n) & 0xffff) << 16);\n }\n\n function _x86Rotl(m, n) {\n //\n // Given a 32bit int and an int representing a number of bit positions,\n // returns the 32bit int rotated left by that number of positions.\n //\n\n return (m << n) | (m >>> (32 - n));\n }\n\n function _x86Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x86 mix of that block.\n //\n\n h ^= h >>> 16;\n h = _x86Multiply(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = _x86Multiply(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h;\n }\n\n function _x64Add(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // added together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] + n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] + n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] + n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += m[0] + n[0];\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Multiply(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // multiplied together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] * n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] * n[3];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[2] += m[3] * n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] * n[3];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[2] * n[2];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[3] * n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Rotl(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) rotated left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 32) {\n return [m[1], m[0]];\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];\n } else {\n n -= 32;\n return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];\n }\n }\n\n function _x64LeftShift(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) shifted left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 0) {\n return m;\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];\n } else {\n return [m[1] << (n - 32), 0];\n }\n }\n\n function _x64Xor(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // xored together as a 64bit int (as an array of two 32bit ints).\n //\n\n return [m[0] ^ n[0], m[1] ^ n[1]];\n }\n\n function _x64Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x64 mix of that block.\n // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the\n // only place where we need to right shift 64bit ints.)\n //\n\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xff51afd7, 0xed558ccd]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n\n return h;\n }\n\n // PUBLIC FUNCTIONS\n // ----------------\n\n library.x86.hash32 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 32 bit hash\n // using the x86 flavor of MurmurHash3, as an unsigned int.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 4;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n\n var k1 = 0;\n\n var c1 = 0xcc9e2d51;\n var c2 = 0x1b873593;\n\n for (var i = 0; i < blocks; i = i + 4) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n\n h1 ^= k1;\n h1 = _x86Rotl(h1, 13);\n h1 = _x86Multiply(h1, 5) + 0xe6546b64;\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h1 = _x86Fmix(h1);\n\n return h1 >>> 0;\n };\n\n library.x86.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x86 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n\n seed = seed || 0;\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n var h2 = seed;\n var h3 = seed;\n var h4 = seed;\n\n var k1 = 0;\n var k2 = 0;\n var k3 = 0;\n var k4 = 0;\n\n var c1 = 0x239b961b;\n var c2 = 0xab0e9789;\n var c3 = 0x38b34ae5;\n var c4 = 0xa1e38b93;\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n k2 = (bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24);\n k3 = (bytes[i + 8]) | (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24);\n k4 = (bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n\n h1 = _x86Rotl(h1, 19);\n h1 += h2;\n h1 = _x86Multiply(h1, 5) + 0x561ccd1b;\n\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n h2 = _x86Rotl(h2, 17);\n h2 += h3;\n h2 = _x86Multiply(h2, 5) + 0x0bcaa747;\n\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n h3 = _x86Rotl(h3, 15);\n h3 += h4;\n h3 = _x86Multiply(h3, 5) + 0x96cd1c35;\n\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n h4 = _x86Rotl(h4, 13);\n h4 += h1;\n h4 = _x86Multiply(h4, 5) + 0x32ac3b17;\n }\n\n k1 = 0;\n k2 = 0;\n k3 = 0;\n k4 = 0;\n\n switch (remainder) {\n case 15:\n k4 ^= bytes[i + 14] << 16;\n\n case 14:\n k4 ^= bytes[i + 13] << 8;\n\n case 13:\n k4 ^= bytes[i + 12];\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n case 12:\n k3 ^= bytes[i + 11] << 24;\n\n case 11:\n k3 ^= bytes[i + 10] << 16;\n\n case 10:\n k3 ^= bytes[i + 9] << 8;\n\n case 9:\n k3 ^= bytes[i + 8];\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n case 8:\n k2 ^= bytes[i + 7] << 24;\n\n case 7:\n k2 ^= bytes[i + 6] << 16;\n\n case 6:\n k2 ^= bytes[i + 5] << 8;\n\n case 5:\n k2 ^= bytes[i + 4];\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n case 4:\n k1 ^= bytes[i + 3] << 24;\n\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h2 ^= bytes.length;\n h3 ^= bytes.length;\n h4 ^= bytes.length;\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n h1 = _x86Fmix(h1);\n h2 = _x86Fmix(h2);\n h3 = _x86Fmix(h3);\n h4 = _x86Fmix(h4);\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n return (\"00000000\" + (h1 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h3 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h4 >>> 0).toString(16)).slice(-8);\n };\n\n library.x64.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x64 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = [0, seed];\n var h2 = [0, seed];\n\n var k1 = [0, 0];\n var k2 = [0, 0];\n\n var c1 = [0x87c37b91, 0x114253d5];\n var c2 = [0x4cf5ad43, 0x2745937f];\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = [(bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24), (bytes[i]) |\n (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)];\n k2 = [(bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24), (bytes[i + 8]) |\n (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24)];\n\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n\n h1 = _x64Rotl(h1, 27);\n h1 = _x64Add(h1, h2);\n h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 0x52dce729]);\n\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n h2 = _x64Rotl(h2, 31);\n h2 = _x64Add(h2, h1);\n h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);\n }\n\n k1 = [0, 0];\n k2 = [0, 0];\n\n switch (remainder) {\n case 15:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 14]], 48));\n\n case 14:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 13]], 40));\n\n case 13:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 12]], 32));\n\n case 12:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 11]], 24));\n\n case 11:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 10]], 16));\n\n case 10:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 9]], 8));\n\n case 9:\n k2 = _x64Xor(k2, [0, bytes[i + 8]]);\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n case 8:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 7]], 56));\n\n case 7:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 6]], 48));\n\n case 6:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 5]], 40));\n\n case 5:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 4]], 32));\n\n case 4:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 3]], 24));\n\n case 3:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 2]], 16));\n\n case 2:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 1]], 8));\n\n case 1:\n k1 = _x64Xor(k1, [0, bytes[i]]);\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n }\n\n h1 = _x64Xor(h1, [0, bytes.length]);\n h2 = _x64Xor(h2, [0, bytes.length]);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n h1 = _x64Fmix(h1);\n h2 = _x64Fmix(h2);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n return (\"00000000\" + (h1[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h1[1] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[1] >>> 0).toString(16)).slice(-8);\n };\n\n // INITIALIZATION\n // --------------\n\n // Export murmurHash3 for CommonJS, either as an AMD module or just as part\n // of the global object.\n if (typeof exports !== 'undefined') {\n\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = library;\n }\n\n exports.murmurHash3 = library;\n\n } else if (typeof define === 'function' && define.amd) {\n\n define([], function () {\n return library;\n });\n } else {\n\n // Use murmurHash3.noConflict to restore `murmurHash3` back to its\n // original value. Returns a reference to the library object, to allow\n // it to be used under a different name.\n library._murmurHash3 = root.murmurHash3;\n\n library.noConflict = function () {\n root.murmurHash3 = library._murmurHash3;\n library._murmurHash3 = undefined;\n library.noConflict = undefined;\n\n return library;\n };\n\n root.murmurHash3 = library;\n }\n})(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n var Netmask, atob, chr, chr0, chrA, chra, ip2long, long2ip;\n\n long2ip = function(long) {\n var a, b, c, d;\n a = (long & (0xff << 24)) >>> 24;\n b = (long & (0xff << 16)) >>> 16;\n c = (long & (0xff << 8)) >>> 8;\n d = long & 0xff;\n return [a, b, c, d].join('.');\n };\n\n ip2long = function(ip) {\n var b, c, i, j, n, ref;\n b = [];\n for (i = j = 0; j <= 3; i = ++j) {\n if (ip.length === 0) {\n break;\n }\n if (i > 0) {\n if (ip[0] !== '.') {\n throw new Error('Invalid IP');\n }\n ip = ip.substring(1);\n }\n ref = atob(ip), n = ref[0], c = ref[1];\n ip = ip.substring(c);\n b.push(n);\n }\n if (ip.length !== 0) {\n throw new Error('Invalid IP');\n }\n switch (b.length) {\n case 1:\n if (b[0] > 0xFFFFFFFF) {\n throw new Error('Invalid IP');\n }\n return b[0] >>> 0;\n case 2:\n if (b[0] > 0xFF || b[1] > 0xFFFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1]) >>> 0;\n case 3:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;\n case 4:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;\n default:\n throw new Error('Invalid IP');\n }\n };\n\n chr = function(b) {\n return b.charCodeAt(0);\n };\n\n chr0 = chr('0');\n\n chra = chr('a');\n\n chrA = chr('A');\n\n atob = function(s) {\n var base, dmax, i, n, start;\n n = 0;\n base = 10;\n dmax = '9';\n i = 0;\n if (s.length > 1 && s[i] === '0') {\n if (s[i + 1] === 'x' || s[i + 1] === 'X') {\n i += 2;\n base = 16;\n } else if ('0' <= s[i + 1] && s[i + 1] <= '9') {\n i++;\n base = 8;\n dmax = '7';\n }\n }\n start = i;\n while (i < s.length) {\n if ('0' <= s[i] && s[i] <= dmax) {\n n = (n * base + (chr(s[i]) - chr0)) >>> 0;\n } else if (base === 16) {\n if ('a' <= s[i] && s[i] <= 'f') {\n n = (n * base + (10 + chr(s[i]) - chra)) >>> 0;\n } else if ('A' <= s[i] && s[i] <= 'F') {\n n = (n * base + (10 + chr(s[i]) - chrA)) >>> 0;\n } else {\n break;\n }\n } else {\n break;\n }\n if (n > 0xFFFFFFFF) {\n throw new Error('too large');\n }\n i++;\n }\n if (i === start) {\n throw new Error('empty octet');\n }\n return [n, i];\n };\n\n Netmask = (function() {\n function Netmask(net, mask) {\n var error, i, j, ref;\n if (typeof net !== 'string') {\n throw new Error(\"Missing `net' parameter\");\n }\n if (!mask) {\n ref = net.split('/', 2), net = ref[0], mask = ref[1];\n }\n if (!mask) {\n mask = 32;\n }\n if (typeof mask === 'string' && mask.indexOf('.') > -1) {\n try {\n this.maskLong = ip2long(mask);\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid mask: \" + mask);\n }\n for (i = j = 32; j >= 0; i = --j) {\n if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) {\n this.bitmask = i;\n break;\n }\n }\n } else if (mask || mask === 0) {\n this.bitmask = parseInt(mask, 10);\n this.maskLong = 0;\n if (this.bitmask > 0) {\n this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0;\n }\n } else {\n throw new Error(\"Invalid mask: empty\");\n }\n try {\n this.netLong = (ip2long(net) & this.maskLong) >>> 0;\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid net address: \" + net);\n }\n if (!(this.bitmask <= 32)) {\n throw new Error(\"Invalid mask for ip4: \" + mask);\n }\n this.size = Math.pow(2, 32 - this.bitmask);\n this.base = long2ip(this.netLong);\n this.mask = long2ip(this.maskLong);\n this.hostmask = long2ip(~this.maskLong);\n this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;\n this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);\n this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;\n }\n\n Netmask.prototype.contains = function(ip) {\n if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) {\n ip = new Netmask(ip);\n }\n if (ip instanceof Netmask) {\n return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);\n } else {\n return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;\n }\n };\n\n Netmask.prototype.next = function(count) {\n if (count == null) {\n count = 1;\n }\n return new Netmask(long2ip(this.netLong + (this.size * count)), this.mask);\n };\n\n Netmask.prototype.forEach = function(fn) {\n var index, lastLong, long;\n long = ip2long(this.first);\n lastLong = ip2long(this.last);\n index = 0;\n while (long <= lastLong) {\n fn(long2ip(long), long, index);\n index++;\n long++;\n }\n };\n\n Netmask.prototype.toString = function() {\n return this.base + \"/\" + this.bitmask;\n };\n\n return Netmask;\n\n })();\n\n exports.ip2long = ip2long;\n\n exports.long2ip = long2ip;\n\n exports.Netmask = Netmask;\n\n}).call(this);\n","// full library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index\");\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(\"./enum\"),\n util = require(\"./util\");\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"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\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(\"./namespace\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(\"./enum\"),\n types = require(\"./types\"),\n util = require(\"./util\");\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(\"./index-minimal\");\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(\"./encoder\");\nprotobuf.decoder = require(\"./decoder\");\nprotobuf.verifier = require(\"./verifier\");\nprotobuf.converter = require(\"./converter\");\n\n// Reflection\nprotobuf.ReflectionObject = require(\"./object\");\nprotobuf.Namespace = require(\"./namespace\");\nprotobuf.Root = require(\"./root\");\nprotobuf.Enum = require(\"./enum\");\nprotobuf.Type = require(\"./type\");\nprotobuf.Field = require(\"./field\");\nprotobuf.OneOf = require(\"./oneof\");\nprotobuf.MapField = require(\"./mapfield\");\nprotobuf.Service = require(\"./service\");\nprotobuf.Method = require(\"./method\");\n\n// Runtime\nprotobuf.Message = require(\"./message\");\nprotobuf.wrappers = require(\"./wrappers\");\n\n// Utility\nprotobuf.types = require(\"./types\");\nprotobuf.util = require(\"./util\");\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(\"./writer\");\nprotobuf.BufferWriter = require(\"./writer_buffer\");\nprotobuf.Reader = require(\"./reader\");\nprotobuf.BufferReader = require(\"./reader_buffer\");\n\n// Utility\nprotobuf.util = require(\"./util/minimal\");\nprotobuf.rpc = require(\"./rpc\");\nprotobuf.roots = require(\"./roots\");\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(\"./index-light\");\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(\"./tokenize\");\nprotobuf.parse = require(\"./parse\");\nprotobuf.common = require(\"./common\");\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(\"./field\");\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(\"./types\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(\"./util\");\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(\"./field\"),\n util = require(\"./util\"),\n OneOf = require(\"./oneof\");\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(\"./util\");\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(\"./field\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(\"./tokenize\"),\n Root = require(\"./root\"),\n Type = require(\"./type\"),\n Field = require(\"./field\"),\n MapField = require(\"./mapfield\"),\n OneOf = require(\"./oneof\"),\n Enum = require(\"./enum\"),\n Service = require(\"./service\"),\n Method = require(\"./method\"),\n types = require(\"./types\"),\n util = require(\"./util\");\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n // Syntax is needed to understand the meaning of the optional field rule\n // Otherwise the meaning is ambiguous between proto2 and proto3\n root.setOption(\"syntax\", syntax);\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(\"./reader\");\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(\"./field\"),\n Enum = require(\"./enum\"),\n OneOf = require(\"./oneof\"),\n util = require(\"./util\");\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(\"./rpc/service\");\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(\"../util/minimal\");\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(\"./method\"),\n util = require(\"./util\"),\n rpc = require(\"./rpc\");\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(\"./enum\"),\n OneOf = require(\"./oneof\"),\n Field = require(\"./field\"),\n MapField = require(\"./mapfield\"),\n Service = require(\"./service\"),\n Message = require(\"./message\"),\n Reader = require(\"./reader\"),\n Writer = require(\"./writer\"),\n util = require(\"./util\"),\n encoder = require(\"./encoder\"),\n decoder = require(\"./decoder\"),\n verifier = require(\"./verifier\"),\n converter = require(\"./converter\"),\n wrappers = require(\"./wrappers\");\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(\"./util\");\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(\"./util/minimal\");\n\nvar roots = require(\"./roots\");\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(\"@protobufjs/codegen\");\nutil.fetch = require(\"@protobufjs/fetch\");\nutil.path = require(\"@protobufjs/path\");\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n 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(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(\"./type\");\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(\"./enum\");\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(\"./root\"))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(\"../util/minimal\");\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(\"@protobufjs/aspromise\");\n\n// converts to / from base64 encoded strings\nutil.base64 = require(\"@protobufjs/base64\");\n\n// base class of rpc.Service\nutil.EventEmitter = require(\"@protobufjs/eventemitter\");\n\n// float handling accross browsers\nutil.float = require(\"@protobufjs/float\");\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(\"@protobufjs/inquire\");\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(\"@protobufjs/utf8\");\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(\"@protobufjs/pool\");\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(\"./longbits\");\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(\"./enum\"),\n util = require(\"./util\");\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(\"./message\");\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(\"./writer\");\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n","/*!\n * MIT License\n * \n * Copyright (c) 2017-2022 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n'use strict';\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","__webpack_require__.amdO = {};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map","/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc';\nconst N1 = Math.pow(2, 7);\nconst N2 = Math.pow(2, 14);\nconst N3 = Math.pow(2, 21);\nconst N4 = Math.pow(2, 28);\nconst N5 = Math.pow(2, 35);\nconst N6 = Math.pow(2, 42);\nconst N7 = Math.pow(2, 49);\n/** Most significant bit of a byte */\nconst MSB = 0x80;\n/** Rest of the bits in a byte */\nconst REST = 0x7f;\nexport function encodingLength(value) {\n if (value < N1) {\n return 1;\n }\n if (value < N2) {\n return 2;\n }\n if (value < N3) {\n return 3;\n }\n if (value < N4) {\n return 4;\n }\n if (value < N5) {\n return 5;\n }\n if (value < N6) {\n return 6;\n }\n if (value < N7) {\n return 7;\n }\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint');\n }\n return 8;\n}\nexport function encodeUint8Array(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 1: {\n buf[offset++] = (value & 0xFF);\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function encodeUint8ArrayList(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 1: {\n buf.set(offset++, (value & 0xFF));\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function decodeUint8Array(buf, offset) {\n let b = buf[offset];\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 1];\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 2];\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 3];\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 4];\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 5];\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 6];\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 7];\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function decodeUint8ArrayList(buf, offset) {\n let b = buf.get(offset);\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 1);\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 2);\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 3);\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 4);\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 5);\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 6);\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 7);\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function encode(value, buf, offset = 0) {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value));\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset);\n }\n else {\n return encodeUint8ArrayList(value, buf, offset);\n }\n}\nexport function decode(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset);\n }\n else {\n return decodeUint8ArrayList(buf, offset);\n }\n}\n//# sourceMappingURL=index.js.map","const f32 = new Float32Array([-0]);\nconst f8b = new Uint8Array(f32.buffer);\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[0];\n buf[pos + 1] = f8b[1];\n buf[pos + 2] = f8b[2];\n buf[pos + 3] = f8b[3];\n}\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[3];\n buf[pos + 1] = f8b[2];\n buf[pos + 2] = f8b[1];\n buf[pos + 3] = f8b[0];\n}\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE(buf, pos) {\n f8b[0] = buf[pos];\n f8b[1] = buf[pos + 1];\n f8b[2] = buf[pos + 2];\n f8b[3] = buf[pos + 3];\n return f32[0];\n}\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE(buf, pos) {\n f8b[3] = buf[pos];\n f8b[2] = buf[pos + 1];\n f8b[1] = buf[pos + 2];\n f8b[0] = buf[pos + 3];\n return f32[0];\n}\nconst f64 = new Float64Array([-0]);\nconst d8b = new Uint8Array(f64.buffer);\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[0];\n buf[pos + 1] = d8b[1];\n buf[pos + 2] = d8b[2];\n buf[pos + 3] = d8b[3];\n buf[pos + 4] = d8b[4];\n buf[pos + 5] = d8b[5];\n buf[pos + 6] = d8b[6];\n buf[pos + 7] = d8b[7];\n}\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[7];\n buf[pos + 1] = d8b[6];\n buf[pos + 2] = d8b[5];\n buf[pos + 3] = d8b[4];\n buf[pos + 4] = d8b[3];\n buf[pos + 5] = d8b[2];\n buf[pos + 6] = d8b[1];\n buf[pos + 7] = d8b[0];\n}\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE(buf, pos) {\n d8b[0] = buf[pos];\n d8b[1] = buf[pos + 1];\n d8b[2] = buf[pos + 2];\n d8b[3] = buf[pos + 3];\n d8b[4] = buf[pos + 4];\n d8b[5] = buf[pos + 5];\n d8b[6] = buf[pos + 6];\n d8b[7] = buf[pos + 7];\n return f64[0];\n}\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE(buf, pos) {\n d8b[7] = buf[pos];\n d8b[6] = buf[pos + 1];\n d8b[5] = buf[pos + 2];\n d8b[4] = buf[pos + 3];\n d8b[3] = buf[pos + 4];\n d8b[2] = buf[pos + 5];\n d8b[1] = buf[pos + 6];\n d8b[0] = buf[pos + 7];\n return f64[0];\n}\n//# sourceMappingURL=float.js.map","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n lo;\n hi;\n constructor(lo, hi) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n /**\n * Low bits\n */\n this.lo = lo | 0;\n /**\n * High bits\n */\n this.hi = hi | 0;\n }\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber(unsigned = false) {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n }\n /**\n * Converts this long bits to a bigint\n */\n toBigInt(unsigned = false) {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n));\n }\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n /**\n * Converts this long bits to a string\n */\n toString(unsigned = false) {\n return this.toBigInt(unsigned).toString();\n }\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode() {\n const mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = (this.lo << 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode() {\n const mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = (this.hi >>> 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length() {\n const part0 = this.lo;\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;\n const part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt(value) {\n if (value === 0n) {\n return zero;\n }\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value));\n }\n const negative = value < 0n;\n if (negative) {\n value = -value;\n }\n let hi = value >> 32n;\n let lo = value - (hi << 32n);\n if (negative) {\n hi = ~hi | 0n;\n lo = ~lo | 0n;\n if (++lo > TWO_32) {\n lo = 0n;\n if (++hi > TWO_32) {\n hi = 0n;\n }\n }\n }\n return new LongBits(Number(lo), Number(hi));\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber(value) {\n if (value === 0) {\n return zero;\n }\n const sign = value < 0;\n if (sign) {\n value = -value;\n }\n let lo = value >>> 0;\n let hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295) {\n hi = 0;\n }\n }\n }\n return new LongBits(lo, hi);\n }\n /**\n * Constructs new long bits from a number, long or string\n */\n static from(value) {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value);\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value);\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value));\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n }\n}\nconst zero = new LongBits(0, 0);\nzero.toBigInt = function () { return 0n; };\nzero.zzEncode = zero.zzDecode = function () { return this; };\nzero.length = function () { return 1; };\nconst TWO_32 = 4294967296n;\n//# sourceMappingURL=longbits.js.map","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length(string) {\n let len = 0;\n let c = 0;\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i);\n if (c < 128) {\n len += 1;\n }\n else if (c < 2048) {\n len += 2;\n }\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i;\n len += 4;\n }\n else {\n len += 3;\n }\n }\n return len;\n}\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read(buffer, start, end) {\n const len = end - start;\n if (len < 1) {\n return '';\n }\n let parts;\n const chunk = [];\n let i = 0; // char offset\n let t; // temporary\n while (start < end) {\n t = buffer[start++];\n if (t < 128) {\n chunk[i++] = t;\n }\n else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\n }\n else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\n chunk[i++] = 0xD800 + (t >> 10);\n chunk[i++] = 0xDC00 + (t & 1023);\n }\n else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\n }\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n }\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write(string, buffer, offset) {\n const start = offset;\n let c1; // character 1\n let c2; // character 2\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i);\n if (c1 < 128) {\n buffer[offset++] = c1;\n }\n else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192;\n buffer[offset++] = c1 & 63 | 128;\n }\n else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\n ++i;\n buffer[offset++] = c1 >> 18 | 240;\n buffer[offset++] = c1 >> 12 & 63 | 128;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n else {\n buffer[offset++] = c1 >> 12 | 224;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n }\n return offset - start;\n}\n//# sourceMappingURL=utf8.js.map","import { decodeUint8Array, encodingLength } from 'uint8-varint';\nimport { readFloatLE, readDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport * as utf8 from './utf8.js';\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);\n}\nfunction readFixed32End(buf, end) {\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0;\n}\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader {\n buf;\n pos;\n len;\n _slice = Uint8Array.prototype.subarray;\n constructor(buffer) {\n /**\n * Read buffer\n */\n this.buf = buffer;\n /**\n * Read buffer position\n */\n this.pos = 0;\n /**\n * Read buffer length\n */\n this.len = buffer.length;\n }\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32() {\n let value = 4294967295;\n value = (this.buf[this.pos] & 127) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n }\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32() {\n const value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n }\n /**\n * Reads a varint as a boolean\n */\n bool() {\n return this.uint32() !== 0;\n }\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4);\n return res;\n }\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4) | 0;\n return res;\n }\n /**\n * Reads a float (32 bit) as a number\n */\n float() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n }\n /**\n * Reads a double (64 bit float) as a number\n */\n double() {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n }\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes() {\n const length = this.uint32();\n const start = this.pos;\n const end = this.pos + length;\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end);\n }\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string() {\n const bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n }\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip(length) {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n }\n else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n } while ((this.buf[this.pos++] & 128) !== 0);\n }\n return this;\n }\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);\n }\n return this;\n }\n readLongVarint() {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0);\n let i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n i = 0;\n }\n else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n throw Error('invalid varint encoding');\n }\n readFixed64() {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8);\n }\n const lo = readFixed32End(this.buf, this.pos += 4);\n const hi = readFixed32End(this.buf, this.pos += 4);\n return new LongBits(lo, hi);\n }\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64() {\n return this.readLongVarint().toBigInt();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number() {\n return this.readLongVarint().toNumber();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String() {\n return this.readLongVarint().toString();\n }\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64() {\n return this.readLongVarint().toBigInt(true);\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number() {\n const value = decodeUint8Array(this.buf, this.pos);\n this.pos += encodingLength(value);\n return value;\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String() {\n return this.readLongVarint().toString(true);\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64() {\n return this.readLongVarint().zzDecode().toBigInt();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number() {\n return this.readLongVarint().zzDecode().toNumber();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String() {\n return this.readLongVarint().zzDecode().toString();\n }\n /**\n * Reads fixed 64 bits\n */\n fixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String() {\n return this.readFixed64().toString();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String() {\n return this.readFixed64().toString();\n }\n}\nexport function createReader(buf) {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());\n}\n//# sourceMappingURL=reader.js.map","import { createReader } from './utils/reader.js';\nexport function decodeMessage(buf, codec, opts) {\n const reader = createReader(buf);\n return codec.decode(reader, undefined, opts);\n}\n//# sourceMappingURL=decode.js.map","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nexport function fromString(str) {\n return new TextEncoder().encode(str);\n}\nexport function toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from '../bytes.js';\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet }) {\n const { encode, decode } = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map","import { from } from './base.js';\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map","import { fromString, toString } from '../bytes.js';\nimport { from } from './base.js';\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n});\n//# sourceMappingURL=identity.js.map","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 0x0200;\nexport function encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nexport function decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map","import { coerce } from '../bytes.js';\nexport const name = 'raw';\nexport const code = 0x55;\nexport function encode(node) {\n return coerce(node);\n}\nexport function decode(data) {\n return coerce(data);\n}\n//# sourceMappingURL=raw.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n return [code, varint.decode.bytes];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes } from '../bytes.js';\nimport * as varint from '../varint.js';\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0x0;\nconst name = 'identity';\nconst encode = coerce;\nfunction digest(input) {\n return Digest.create(code, encode(input));\n}\nexport const identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map","import * as Digest from './digest.js';\nexport function from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map","/* global crypto */\nimport { from } from './hasher.js';\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import { base32 } from './bases/base32.js';\nimport { base36 } from './bases/base36.js';\nimport { base58btc } from './bases/base58.js';\nimport { coerce } from './bytes.js';\nimport * as Digest from './hashes/digest.js';\nimport * as varint from './varint.js';\n// This way TS will also expose all the types from module\nexport * from './link/interface.js';\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n case base36.prefix: {\n const decoder = base ?? base36;\n return [base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","import * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base2 from './bases/base2.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base8 from './bases/base8.js';\nimport * as identityBase from './bases/identity.js';\nimport * as json from './codecs/json.js';\nimport * as raw from './codecs/raw.js';\nimport * as identity from './hashes/identity.js';\nimport * as sha2 from './hashes/sha2.js';\nimport { CID, hasher, digest, varint, bytes } from './index.js';\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };\nexport const hashes = { ...sha2, ...identity };\nexport const codecs = { raw, json };\nexport { CID, hasher, digest, varint, bytes };\n//# sourceMappingURL=basics.js.map","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '#alloc';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;\n//# sourceMappingURL=bases.js.map","import bases, {} from './util/bases.js';\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map","import { encodeUint8Array, encodingLength } from 'uint8-varint';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { writeFloatLE, writeDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport pool from './pool.js';\nimport * as utf8 from './utf8.js';\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n fn;\n /**\n * Value byte length\n */\n len;\n /**\n * Next operation\n */\n next;\n /**\n * Value to write\n */\n val;\n constructor(fn, len, val) {\n this.fn = fn;\n this.len = len;\n this.next = undefined;\n this.val = val; // type varies\n }\n}\n/* istanbul ignore next */\nfunction noop() { } // eslint-disable-line no-empty-function\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n head;\n /**\n * Current tail\n */\n tail;\n /**\n * Current buffer length\n */\n len;\n /**\n * Next state\n */\n next;\n constructor(writer) {\n this.head = writer.head;\n this.tail = writer.tail;\n this.len = writer.len;\n this.next = writer.states;\n }\n}\nconst bufferPool = pool();\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc(size) {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size);\n }\n return bufferPool(size);\n}\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter {\n /**\n * Current length\n */\n len;\n /**\n * Operations head\n */\n head;\n /**\n * Operations tail\n */\n tail;\n /**\n * Linked forked states\n */\n states;\n constructor() {\n this.len = 0;\n this.head = new Op(noop, 0, 0);\n this.tail = this.head;\n this.states = null;\n }\n /**\n * Pushes a new operation to the queue\n */\n _push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n }\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5, value)).len;\n return this;\n }\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n }\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value) {\n return this._push(encodeUint8Array, encodingLength(value), value);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value) {\n return this.uint64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value) {\n return this.uint64(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value) {\n return this.uint64Number(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value) {\n return this.uint64String(value);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value) {\n const bits = LongBits.fromBigInt(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value) {\n const bits = LongBits.fromNumber(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value) {\n return this.sint64(BigInt(value));\n }\n /**\n * Writes a boolish value as a varint\n */\n bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n }\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n }\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value) {\n return this.fixed32(value);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value) {\n const bits = LongBits.fromNumber(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value) {\n return this.fixed64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value) {\n return this.fixed64(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value) {\n return this.fixed64Number(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value) {\n return this.fixed64String(value);\n }\n /**\n * Writes a float (32 bit)\n */\n float(value) {\n return this._push(writeFloatLE, 4, value);\n }\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double(value) {\n return this._push(writeDoubleLE, 8, value);\n }\n /**\n * Writes a sequence of bytes\n */\n bytes(value) {\n const len = value.length >>> 0;\n if (len === 0) {\n return this._push(writeByte, 1, 0);\n }\n return this.uint32(len)._push(writeBytes, len, value);\n }\n /**\n * Writes a string\n */\n string(value) {\n const len = utf8.length(value);\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n }\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n }\n /**\n * Resets this instance to the last state\n */\n reset() {\n if (this.states != null) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n }\n else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n }\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim() {\n const head = this.head;\n const tail = this.tail;\n const len = this.len;\n this.reset().uint32(len);\n if (len !== 0) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n }\n /**\n * Finishes the write operation\n */\n finish() {\n let head = this.head.next; // skip noop\n const buf = alloc(this.len);\n let pos = 0;\n while (head != null) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n }\n}\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n next;\n constructor(len, val) {\n super(writeVarint32, len, val);\n this.next = undefined;\n }\n}\nfunction writeVarint64(val, buf, pos) {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\nfunction writeFixed32(val, buf, pos) {\n buf[pos] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\nfunction writeBytes(val, buf, pos) {\n buf.set(val, pos);\n}\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value) {\n const len = value.length >>> 0;\n this.uint32(len);\n if (len > 0) {\n this._push(writeBytesBuffer, len, value);\n }\n return this;\n };\n Uint8ArrayWriter.prototype.string = function (value) {\n const len = globalThis.Buffer.byteLength(value);\n this.uint32(len);\n if (len > 0) {\n this._push(writeStringBuffer, len, value);\n }\n return this;\n };\n}\nfunction writeBytesBuffer(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos);\n // @ts-expect-error buf isn't a Uint8Array?\n }\n else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos);\n }\n else {\n buf.set(uint8ArrayFromString(val), pos);\n }\n}\n/**\n * Creates a new writer\n */\nexport function createWriter() {\n return new Uint8ArrayWriter();\n}\n//# sourceMappingURL=writer.js.map","import { allocUnsafe } from 'uint8arrays/alloc';\n/**\n * A general purpose buffer pool\n */\nexport default function pool(size) {\n const SIZE = size ?? 8192;\n const MAX = SIZE >>> 1;\n let slab;\n let offset = SIZE;\n return function poolAlloc(size) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size);\n }\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE);\n offset = 0;\n }\n const buf = slab.subarray(offset, offset += size);\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1;\n }\n return buf;\n };\n}\n//# sourceMappingURL=pool.js.map","import { createWriter } from './utils/writer.js';\nexport function encodeMessage(message, codec) {\n const w = createWriter();\n codec.encode(message, w, {\n lengthDelimited: false\n });\n return w.finish();\n}\n//# sourceMappingURL=encode.js.map","// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport var CODEC_TYPES;\n(function (CODEC_TYPES) {\n CODEC_TYPES[CODEC_TYPES[\"VARINT\"] = 0] = \"VARINT\";\n CODEC_TYPES[CODEC_TYPES[\"BIT64\"] = 1] = \"BIT64\";\n CODEC_TYPES[CODEC_TYPES[\"LENGTH_DELIMITED\"] = 2] = \"LENGTH_DELIMITED\";\n CODEC_TYPES[CODEC_TYPES[\"START_GROUP\"] = 3] = \"START_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"END_GROUP\"] = 4] = \"END_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"BIT32\"] = 5] = \"BIT32\";\n})(CODEC_TYPES || (CODEC_TYPES = {}));\nexport function createCodec(name, type, encode, decode) {\n return {\n name,\n type,\n encode,\n decode\n };\n}\n//# sourceMappingURL=codec.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterRequest;\n(function (FilterRequest) {\n let ContentFilter;\n (function (ContentFilter) {\n let _codec;\n ContentFilter.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(10);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ContentFilter.encode = (obj) => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n ContentFilter.decode = (buf, opts) => {\n return decodeMessage(buf, ContentFilter.codec(), opts);\n };\n })(ContentFilter = FilterRequest.ContentFilter || (FilterRequest.ContentFilter = {}));\n let _codec;\n FilterRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.subscribe != null && obj.subscribe !== false)) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n w.uint32(26);\n FilterRequest.ContentFilter.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscribe: false,\n topic: '',\n contentFilters: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n case 3: {\n if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {\n throw new MaxLengthError('Decode error - map field \"contentFilters\" had too many elements');\n }\n obj.contentFilters.push(FilterRequest.ContentFilter.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.contentFilters$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRequest.encode = (obj) => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n FilterRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRequest.codec(), opts);\n };\n})(FilterRequest || (FilterRequest = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(10);\n WakuMessage.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new MaxLengthError('Decode error - map field \"messages\" had too many elements');\n }\n obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var FilterRpc;\n(function (FilterRpc) {\n let _codec;\n FilterRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n FilterRequest.codec().encode(obj.request, w);\n }\n if (obj.push != null) {\n w.uint32(26);\n MessagePush.codec().encode(obj.push, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = FilterRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.push = MessagePush.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.push\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRpc.encode = (obj) => {\n return encodeMessage(obj, FilterRpc.codec());\n };\n FilterRpc.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRpc.codec(), opts);\n };\n})(FilterRpc || (FilterRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var TopicOnlyMessage;\n(function (TopicOnlyMessage) {\n let _codec;\n TopicOnlyMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n TopicOnlyMessage.encode = (obj) => {\n return encodeMessage(obj, TopicOnlyMessage.codec());\n };\n TopicOnlyMessage.decode = (buf, opts) => {\n return decodeMessage(buf, TopicOnlyMessage.codec(), opts);\n };\n})(TopicOnlyMessage || (TopicOnlyMessage = {}));\n//# sourceMappingURL=topic_only_message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, enumeration, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterSubscribeRequest;\n(function (FilterSubscribeRequest) {\n let FilterSubscribeType;\n (function (FilterSubscribeType) {\n FilterSubscribeType[\"SUBSCRIBER_PING\"] = \"SUBSCRIBER_PING\";\n FilterSubscribeType[\"SUBSCRIBE\"] = \"SUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE\"] = \"UNSUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE_ALL\"] = \"UNSUBSCRIBE_ALL\";\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let __FilterSubscribeTypeValues;\n (function (__FilterSubscribeTypeValues) {\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBER_PING\"] = 0] = \"SUBSCRIBER_PING\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBE\"] = 1] = \"SUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE\"] = 2] = \"UNSUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE_ALL\"] = 3] = \"UNSUBSCRIBE_ALL\";\n })(__FilterSubscribeTypeValues || (__FilterSubscribeTypeValues = {}));\n (function (FilterSubscribeType) {\n FilterSubscribeType.codec = () => {\n return enumeration(__FilterSubscribeTypeValues);\n };\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let _codec;\n FilterSubscribeRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.filterSubscribeType != null && __FilterSubscribeTypeValues[obj.filterSubscribeType] !== 0) {\n w.uint32(16);\n FilterSubscribeRequest.FilterSubscribeType.codec().encode(obj.filterSubscribeType, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(82);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentTopics != null) {\n for (const value of obj.contentTopics) {\n w.uint32(90);\n w.string(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n filterSubscribeType: FilterSubscribeType.SUBSCRIBER_PING,\n contentTopics: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.filterSubscribeType = FilterSubscribeRequest.FilterSubscribeType.codec().decode(reader);\n break;\n }\n case 10: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 11: {\n if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {\n throw new MaxLengthError('Decode error - map field \"contentTopics\" had too many elements');\n }\n obj.contentTopics.push(reader.string());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeRequest.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeRequest.codec());\n };\n FilterSubscribeRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeRequest.codec(), opts);\n };\n})(FilterSubscribeRequest || (FilterSubscribeRequest = {}));\nexport var FilterSubscribeResponse;\n(function (FilterSubscribeResponse) {\n let _codec;\n FilterSubscribeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if ((obj.statusCode != null && obj.statusCode !== 0)) {\n w.uint32(80);\n w.uint32(obj.statusCode);\n }\n if (obj.statusDesc != null) {\n w.uint32(90);\n w.string(obj.statusDesc);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n statusCode: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 10: {\n obj.statusCode = reader.uint32();\n break;\n }\n case 11: {\n obj.statusDesc = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeResponse.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeResponse.codec());\n };\n FilterSubscribeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeResponse.codec(), opts);\n };\n})(FilterSubscribeResponse || (FilterSubscribeResponse = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.wakuMessage != null) {\n w.uint32(10);\n WakuMessage.codec().encode(obj.wakuMessage, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(18);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.wakuMessage = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.wakuMessage\n });\n break;\n }\n case 2: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter_v2.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var PushRequest;\n(function (PushRequest) {\n let _codec;\n PushRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.pubsubTopic != null && obj.pubsubTopic !== '')) {\n w.uint32(10);\n w.string(obj.pubsubTopic);\n }\n if (obj.message != null) {\n w.uint32(18);\n WakuMessage.codec().encode(obj.message, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n pubsubTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 2: {\n obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.message\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRequest.encode = (obj) => {\n return encodeMessage(obj, PushRequest.codec());\n };\n PushRequest.decode = (buf, opts) => {\n return decodeMessage(buf, PushRequest.codec(), opts);\n };\n})(PushRequest || (PushRequest = {}));\nexport var PushResponse;\n(function (PushResponse) {\n let _codec;\n PushResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.isSuccess != null && obj.isSuccess !== false)) {\n w.uint32(8);\n w.bool(obj.isSuccess);\n }\n if (obj.info != null) {\n w.uint32(18);\n w.string(obj.info);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n isSuccess: false\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.isSuccess = reader.bool();\n break;\n }\n case 2: {\n obj.info = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushResponse.encode = (obj) => {\n return encodeMessage(obj, PushResponse.codec());\n };\n PushResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PushResponse.codec(), opts);\n };\n})(PushResponse || (PushResponse = {}));\nexport var PushRpc;\n(function (PushRpc) {\n let _codec;\n PushRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n PushRequest.codec().encode(obj.request, w);\n }\n if (obj.response != null) {\n w.uint32(26);\n PushResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = PushRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.response = PushResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRpc.encode = (obj) => {\n return encodeMessage(obj, PushRpc.codec());\n };\n PushRpc.decode = (buf, opts) => {\n return decodeMessage(buf, PushRpc.codec(), opts);\n };\n})(PushRpc || (PushRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=light_push.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var WakuMessageKeyValue;\n(function (WakuMessageKeyValue) {\n let _codec;\n WakuMessageKeyValue.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messageHash != null) {\n w.uint32(10);\n w.bytes(obj.messageHash);\n }\n if (obj.message != null) {\n w.uint32(18);\n WakuMessage.codec().encode(obj.message, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(26);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.messageHash = reader.bytes();\n break;\n }\n case 2: {\n obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.message\n });\n break;\n }\n case 3: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessageKeyValue.encode = (obj) => {\n return encodeMessage(obj, WakuMessageKeyValue.codec());\n };\n WakuMessageKeyValue.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessageKeyValue.codec(), opts);\n };\n})(WakuMessageKeyValue || (WakuMessageKeyValue = {}));\nexport var StoreQueryRequest;\n(function (StoreQueryRequest) {\n let _codec;\n StoreQueryRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if ((obj.includeData != null && obj.includeData !== false)) {\n w.uint32(16);\n w.bool(obj.includeData);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(82);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentTopics != null) {\n for (const value of obj.contentTopics) {\n w.uint32(90);\n w.string(value);\n }\n }\n if (obj.timeStart != null) {\n w.uint32(96);\n w.sint64(obj.timeStart);\n }\n if (obj.timeEnd != null) {\n w.uint32(104);\n w.sint64(obj.timeEnd);\n }\n if (obj.messageHashes != null) {\n for (const value of obj.messageHashes) {\n w.uint32(162);\n w.bytes(value);\n }\n }\n if (obj.paginationCursor != null) {\n w.uint32(410);\n w.bytes(obj.paginationCursor);\n }\n if ((obj.paginationForward != null && obj.paginationForward !== false)) {\n w.uint32(416);\n w.bool(obj.paginationForward);\n }\n if (obj.paginationLimit != null) {\n w.uint32(424);\n w.uint64(obj.paginationLimit);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n includeData: false,\n contentTopics: [],\n messageHashes: [],\n paginationForward: false\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.includeData = reader.bool();\n break;\n }\n case 10: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 11: {\n if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {\n throw new MaxLengthError('Decode error - map field \"contentTopics\" had too many elements');\n }\n obj.contentTopics.push(reader.string());\n break;\n }\n case 12: {\n obj.timeStart = reader.sint64();\n break;\n }\n case 13: {\n obj.timeEnd = reader.sint64();\n break;\n }\n case 20: {\n if (opts.limits?.messageHashes != null && obj.messageHashes.length === opts.limits.messageHashes) {\n throw new MaxLengthError('Decode error - map field \"messageHashes\" had too many elements');\n }\n obj.messageHashes.push(reader.bytes());\n break;\n }\n case 51: {\n obj.paginationCursor = reader.bytes();\n break;\n }\n case 52: {\n obj.paginationForward = reader.bool();\n break;\n }\n case 53: {\n obj.paginationLimit = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n StoreQueryRequest.encode = (obj) => {\n return encodeMessage(obj, StoreQueryRequest.codec());\n };\n StoreQueryRequest.decode = (buf, opts) => {\n return decodeMessage(buf, StoreQueryRequest.codec(), opts);\n };\n})(StoreQueryRequest || (StoreQueryRequest = {}));\nexport var StoreQueryResponse;\n(function (StoreQueryResponse) {\n let _codec;\n StoreQueryResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.statusCode != null) {\n w.uint32(80);\n w.uint32(obj.statusCode);\n }\n if (obj.statusDesc != null) {\n w.uint32(90);\n w.string(obj.statusDesc);\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(162);\n WakuMessageKeyValue.codec().encode(value, w);\n }\n }\n if (obj.paginationCursor != null) {\n w.uint32(410);\n w.bytes(obj.paginationCursor);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 10: {\n obj.statusCode = reader.uint32();\n break;\n }\n case 11: {\n obj.statusDesc = reader.string();\n break;\n }\n case 20: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new MaxLengthError('Decode error - map field \"messages\" had too many elements');\n }\n obj.messages.push(WakuMessageKeyValue.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n case 51: {\n obj.paginationCursor = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n StoreQueryResponse.encode = (obj) => {\n return encodeMessage(obj, StoreQueryResponse.codec());\n };\n StoreQueryResponse.decode = (buf, opts) => {\n return decodeMessage(buf, StoreQueryResponse.codec(), opts);\n };\n})(StoreQueryResponse || (StoreQueryResponse = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=store_v3.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nexport var PeerInfo;\n(function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.enr != null) {\n w.uint32(10);\n w.bytes(obj.enr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.enr = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return encodeMessage(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return decodeMessage(buf, PeerInfo.codec(), opts);\n };\n})(PeerInfo || (PeerInfo = {}));\nexport var PeerExchangeQuery;\n(function (PeerExchangeQuery) {\n let _codec;\n PeerExchangeQuery.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.numPeers != null) {\n w.uint32(8);\n w.uint64(obj.numPeers);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.numPeers = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeQuery.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeQuery.codec());\n };\n PeerExchangeQuery.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeQuery.codec(), opts);\n };\n})(PeerExchangeQuery || (PeerExchangeQuery = {}));\nexport var PeerExchangeResponse;\n(function (PeerExchangeResponse) {\n let _codec;\n PeerExchangeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerInfos != null) {\n for (const value of obj.peerInfos) {\n w.uint32(10);\n PeerInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peerInfos: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.peerInfos != null && obj.peerInfos.length === opts.limits.peerInfos) {\n throw new MaxLengthError('Decode error - map field \"peerInfos\" had too many elements');\n }\n obj.peerInfos.push(PeerInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.peerInfos$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeResponse.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeResponse.codec());\n };\n PeerExchangeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeResponse.codec(), opts);\n };\n})(PeerExchangeResponse || (PeerExchangeResponse = {}));\nexport var PeerExchangeRPC;\n(function (PeerExchangeRPC) {\n let _codec;\n PeerExchangeRPC.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.query != null) {\n w.uint32(10);\n PeerExchangeQuery.codec().encode(obj.query, w);\n }\n if (obj.response != null) {\n w.uint32(18);\n PeerExchangeResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.query = PeerExchangeQuery.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.query\n });\n break;\n }\n case 2: {\n obj.response = PeerExchangeResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeRPC.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeRPC.codec());\n };\n PeerExchangeRPC.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeRPC.codec(), opts);\n };\n})(PeerExchangeRPC || (PeerExchangeRPC = {}));\n//# sourceMappingURL=peer_exchange.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nexport var WakuMetadataRequest;\n(function (WakuMetadataRequest) {\n let _codec;\n WakuMetadataRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new MaxLengthError('Decode error - map field \"shards\" had too many elements');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataRequest.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataRequest.codec());\n };\n WakuMetadataRequest.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataRequest.codec(), opts);\n };\n})(WakuMetadataRequest || (WakuMetadataRequest = {}));\nexport var WakuMetadataResponse;\n(function (WakuMetadataResponse) {\n let _codec;\n WakuMetadataResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new MaxLengthError('Decode error - map field \"shards\" had too many elements');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataResponse.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataResponse.codec());\n };\n WakuMetadataResponse.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataResponse.codec(), opts);\n };\n})(WakuMetadataResponse || (WakuMetadataResponse = {}));\n//# sourceMappingURL=metadata.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function enumeration(v) {\n function findValue(val) {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value');\n }\n return v[val];\n }\n const encode = function enumEncode(val, writer) {\n const enumValue = findValue(val);\n writer.int32(enumValue);\n };\n const decode = function enumDecode(reader) {\n const val = reader.int32();\n return findValue(val);\n };\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode);\n}\n//# sourceMappingURL=enum.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function message(encode, decode) {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode);\n}\n//# sourceMappingURL=message.js.map","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\nexport { decodeMessage } from './decode.js';\nexport { encodeMessage } from './encode.js';\nexport { enumeration } from './codecs/enum.js';\nexport { message } from './codecs/message.js';\nexport { createReader as reader } from './utils/reader.js';\nexport { createWriter as writer } from './utils/writer.js';\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * Thrown when a repeated field has too many elements\n */\nexport class MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_LENGTH';\n name = 'MaxLengthError';\n}\n/**\n * Thrown when a map has too many elements\n */\nexport class MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_SIZE';\n name = 'MaxSizeError';\n}\nexport class ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_PARSE_ERROR';\n name = 'ParseError';\n}\nexport class NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_NO_MESSAGES_FOUND';\n name = 'NoMessagesFoundError';\n}\n//# sourceMappingURL=index.js.map","export function isDefined(value) {\n return Boolean(value);\n}\n//# sourceMappingURL=is_defined.js.map","export function groupByContentTopic(values) {\n const groupedDecoders = new Map();\n values.forEach((value) => {\n let decs = groupedDecoders.get(value.contentTopic);\n if (!decs) {\n groupedDecoders.set(value.contentTopic, []);\n decs = groupedDecoders.get(value.contentTopic);\n }\n decs.push(value);\n });\n return groupedDecoders;\n}\n//# sourceMappingURL=group_by.js.map","const FRAME_RATE = 60;\n/**\n * Function that transforms IReceiver subscription to iterable stream of data.\n * @param receiver - object that allows to be subscribed to;\n * @param decoder - parameter to be passed to receiver for subscription;\n * @param options - options for receiver for subscription;\n * @param iteratorOptions - optional configuration for iterator;\n * @returns iterator and stop function to terminate it.\n */\nexport async function toAsyncIterator(receiver, decoder, iteratorOptions) {\n const iteratorDelay = iteratorOptions?.iteratorDelay ?? FRAME_RATE;\n const messages = [];\n let unsubscribe;\n unsubscribe = await receiver.subscribeWithUnsubscribe(decoder, (message) => {\n messages.push(message);\n });\n const isWithTimeout = Number.isInteger(iteratorOptions?.timeoutMs);\n const timeoutMs = iteratorOptions?.timeoutMs ?? 0;\n const startTime = Date.now();\n async function* iterator() {\n while (true) {\n if (isWithTimeout && Date.now() - startTime >= timeoutMs) {\n return;\n }\n await wait(iteratorDelay);\n const message = messages.shift();\n if (!unsubscribe && messages.length === 0) {\n return message;\n }\n if (!message && unsubscribe) {\n continue;\n }\n yield message;\n }\n }\n return {\n iterator: iterator(),\n async stop() {\n if (unsubscribe) {\n await unsubscribe();\n unsubscribe = undefined;\n }\n }\n };\n}\nfunction wait(ms) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n//# sourceMappingURL=to_async_iterator.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nexport const Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nexport const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/**\n * SHA2-224 hash function\n */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","export var Protocols;\n(function (Protocols) {\n Protocols[\"Relay\"] = \"relay\";\n Protocols[\"Store\"] = \"store\";\n Protocols[\"LightPush\"] = \"lightpush\";\n Protocols[\"Filter\"] = \"filter\";\n})(Protocols || (Protocols = {}));\nexport var ProtocolError;\n(function (ProtocolError) {\n /** Could not determine the origin of the fault. Best to check connectivity and try again */\n ProtocolError[\"GENERIC_FAIL\"] = \"Generic error\";\n /**\n * Failure to protobuf encode the message. This is not recoverable and needs\n * further investigation.\n */\n ProtocolError[\"ENCODE_FAILED\"] = \"Failed to encode\";\n /**\n * Failure to protobuf decode the message. May be due to a remote peer issue,\n * ensuring that messages are sent via several peer enable mitigation of this error.\n */\n ProtocolError[\"DECODE_FAILED\"] = \"Failed to decode\";\n /**\n * The message payload is empty, making the message invalid. Ensure that a non-empty\n * payload is set on the outgoing message.\n */\n ProtocolError[\"EMPTY_PAYLOAD\"] = \"Payload is empty\";\n /**\n * The message size is above the maximum message size allowed on the Waku Network.\n * Compressing the message or using an alternative strategy for large messages is recommended.\n */\n ProtocolError[\"SIZE_TOO_BIG\"] = \"Size is too big\";\n /**\n * The PubsubTopic passed to the send function is not configured on the Waku node.\n * Please ensure that the PubsubTopic is used when initializing the Waku node.\n */\n ProtocolError[\"TOPIC_NOT_CONFIGURED\"] = \"Topic not configured\";\n /**\n * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.\n * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.\n */\n ProtocolError[\"TOPIC_DECODER_MISMATCH\"] = \"Topic decoder mismatch\";\n /**\n * The topics passed in the decoders do not match each other, or don't exist at all.\n * Ensure that all the pubsub topics used in the decoders are valid and match each other.\n */\n ProtocolError[\"INVALID_DECODER_TOPICS\"] = \"Invalid decoder topics\";\n /**\n * Failure to find a peer with suitable protocols. This may due to a connection issue.\n * Mitigation can be: retrying after a given time period, display connectivity issue\n * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`\n * on the connection manager before retrying.\n */\n ProtocolError[\"NO_PEER_AVAILABLE\"] = \"No peer available\";\n /**\n * Failure to find a stream to the peer. This may be because the connection with the peer is not still alive.\n * Mitigation can be: retrying after a given time period, or mitigation for `NO_PEER_AVAILABLE` can be used.\n */\n ProtocolError[\"NO_STREAM_AVAILABLE\"] = \"No stream available\";\n /**\n * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"NO_RESPONSE\"] = \"No response received\";\n /**\n * The remote peer rejected the message. Information provided by the remote peer\n * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"REMOTE_PEER_REJECTED\"] = \"Remote peer rejected\";\n /**\n * The protocol request timed out without a response. This may be due to a connection issue.\n * Mitigation can be: retrying after a given time period\n */\n ProtocolError[\"REQUEST_TIMEOUT\"] = \"Request timeout\";\n /**\n * Missing credentials info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L186\n */\n ProtocolError[\"RLN_IDENTITY_MISSING\"] = \"Identity credentials are not set\";\n /**\n * Membership index missing info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L188\n */\n ProtocolError[\"RLN_MEMBERSHIP_INDEX\"] = \"Membership index is not set\";\n /**\n * Message limit is missing.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L190\n */\n ProtocolError[\"RLN_LIMIT_MISSING\"] = \"User message limit is not set\";\n /**\n * General proof generation error message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42\n */\n ProtocolError[\"RLN_PROOF_GENERATION\"] = \"Proof generation failed\";\n})(ProtocolError || (ProtocolError = {}));\n//# sourceMappingURL=protocols.js.map","export var Tags;\n(function (Tags) {\n Tags[\"BOOTSTRAP\"] = \"bootstrap\";\n Tags[\"PEER_EXCHANGE\"] = \"peer-exchange\";\n Tags[\"LOCAL\"] = \"local-peer-cache\";\n})(Tags || (Tags = {}));\nexport var EPeersByDiscoveryEvents;\n(function (EPeersByDiscoveryEvents) {\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_BOOTSTRAP\"] = \"peer:discovery:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_PEER_EXCHANGE\"] = \"peer:discovery:peer-exchange\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_BOOTSTRAP\"] = \"peer:connected:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_PEER_EXCHANGE\"] = \"peer:connected:peer-exchange\";\n})(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));\nexport var EConnectionStateEvents;\n(function (EConnectionStateEvents) {\n EConnectionStateEvents[\"CONNECTION_STATUS\"] = \"waku:connection\";\n})(EConnectionStateEvents || (EConnectionStateEvents = {}));\n//# sourceMappingURL=connection_manager.js.map","export const DNS_DISCOVERY_TAG = \"@waku/bootstrap\";\n//# sourceMappingURL=dns_discovery.js.map","/**\n * The default cluster ID for The Waku Network\n */\nexport const DEFAULT_CLUSTER_ID = 1;\n/**\n * DefaultShardInfo is default configuration for The Waku Network.\n */\nexport const DefaultShardInfo = {\n clusterId: DEFAULT_CLUSTER_ID,\n shards: [0, 1, 2, 3, 4, 5, 6, 7, 8]\n};\nexport const DefaultNetworkConfig = DefaultShardInfo;\n//# sourceMappingURL=constants.js.map","export var HealthStatus;\n(function (HealthStatus) {\n HealthStatus[\"Unhealthy\"] = \"Unhealthy\";\n HealthStatus[\"MinimallyHealthy\"] = \"MinimallyHealthy\";\n HealthStatus[\"SufficientlyHealthy\"] = \"SufficientlyHealthy\";\n})(HealthStatus || (HealthStatus = {}));\n//# sourceMappingURL=health_manager.js.map","import bases, {} from './util/bases.js';\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map","import { fromString } from \"uint8arrays/from-string\";\nimport { toString } from \"uint8arrays/to-string\";\n/**\n * Convert input to a byte array.\n *\n * Handles both `0x` prefixed and non-prefixed strings.\n */\nexport function hexToBytes(hex) {\n if (typeof hex === \"string\") {\n const _hex = hex.replace(/^0x/i, \"\");\n return fromString(_hex.toLowerCase(), \"base16\");\n }\n return hex;\n}\nexport function numberToBytes(value) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof value === \"number\") {\n view.setFloat64(0, value, false);\n }\n else {\n view.setBigInt64(0, value, false);\n }\n return new Uint8Array(buffer);\n}\n/**\n * Convert byte array to hex string (no `0x` prefix).\n */\nexport const bytesToHex = (bytes) => toString(bytes, \"base16\");\n/**\n * Decode byte array to utf-8 string.\n */\nexport const bytesToUtf8 = (b) => toString(b, \"utf8\");\n/**\n * Encode utf-8 string to byte array.\n */\nexport const utf8ToBytes = (s) => fromString(s, \"utf8\");\n/**\n * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`\n */\nexport function concat(byteArrays, totalLength) {\n const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);\n const res = new Uint8Array(len);\n let offset = 0;\n for (const bytes of byteArrays) {\n res.set(bytes, offset);\n offset += bytes.length;\n }\n return res;\n}\n//# sourceMappingURL=index.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { DEFAULT_CLUSTER_ID } from \"@waku/interfaces\";\nimport { concat, utf8ToBytes } from \"../../bytes/index.js\";\nimport { isAutoSharding, isStaticSharding } from \"./type_guards.js\";\nexport * from \"./type_guards.js\";\nexport function derivePubsubTopicsFromNetworkConfig(networkConfig) {\n if (isStaticSharding(networkConfig)) {\n if (networkConfig.shards.length === 0) {\n throw new Error(\"Invalid shards configuration: please provide at least one shard\");\n }\n return shardInfoToPubsubTopics(networkConfig);\n }\n else if (isAutoSharding(networkConfig)) {\n if (networkConfig.contentTopics.length === 0) {\n throw new Error(\"Invalid content topics configuration: please provide at least one content topic\");\n }\n return networkConfig.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, networkConfig.clusterId));\n }\n else {\n throw new Error(\"Unknown shard config. Please use ShardInfo or ContentTopicInfo\");\n }\n}\nexport const singleShardInfoToPubsubTopic = (shardInfo) => {\n if (shardInfo.shard === undefined)\n throw new Error(\"Invalid shard\");\n return `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${shardInfo.shard}`;\n};\nexport const singleShardInfosToShardInfo = (singleShardInfos) => {\n if (singleShardInfos.length === 0)\n throw new Error(\"Invalid shard\");\n const clusterIds = singleShardInfos.map((shardInfo) => shardInfo.clusterId);\n if (new Set(clusterIds).size !== 1) {\n throw new Error(\"Passed shard infos have different clusterIds\");\n }\n const shards = singleShardInfos\n .map((shardInfo) => shardInfo.shard)\n .filter((shard) => shard !== undefined);\n return {\n clusterId: singleShardInfos[0].clusterId,\n shards\n };\n};\nexport const shardInfoToPubsubTopics = (shardInfo) => {\n if (\"contentTopics\" in shardInfo && shardInfo.contentTopics) {\n // Autosharding: explicitly defined content topics\n return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));\n }\n else if (\"shards\" in shardInfo) {\n // Static sharding\n if (shardInfo.shards === undefined)\n throw new Error(\"Invalid shard\");\n return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${index}`)));\n }\n else if (\"application\" in shardInfo && \"version\" in shardInfo) {\n // Autosharding: single shard from application and version\n return [\n contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`, shardInfo.clusterId)\n ];\n }\n else {\n throw new Error(\"Missing required configuration in shard parameters\");\n }\n};\nexport const pubsubTopicToSingleShardInfo = (pubsubTopics) => {\n const parts = pubsubTopics.split(\"/\");\n if (parts.length != 6 ||\n parts[1] !== \"waku\" ||\n parts[2] !== \"2\" ||\n parts[3] !== \"rs\")\n throw new Error(\"Invalid pubsub topic\");\n const clusterId = parseInt(parts[4]);\n const shard = parseInt(parts[5]);\n if (isNaN(clusterId) || isNaN(shard))\n throw new Error(\"Invalid clusterId or shard\");\n return {\n clusterId,\n shard\n };\n};\nexport const pubsubTopicsToShardInfo = (pubsubTopics) => {\n const shardInfoSet = new Set();\n const clusterIds = new Set();\n for (const topic of pubsubTopics) {\n const { clusterId, shard } = pubsubTopicToSingleShardInfo(topic);\n shardInfoSet.add(`${clusterId}:${shard}`);\n clusterIds.add(clusterId);\n }\n if (shardInfoSet.size === 0) {\n throw new Error(\"No valid pubsub topics provided\");\n }\n if (clusterIds.size > 1) {\n throw new Error(\"Pubsub topics from multiple cluster IDs are not supported\");\n }\n const clusterId = clusterIds.values().next().value;\n const shards = Array.from(shardInfoSet).map((info) => parseInt(info.split(\":\")[1]));\n return {\n clusterId,\n shards\n };\n};\n//TODO: move part of BaseProtocol instead of utils\n// return `ProtocolError.TOPIC_NOT_CONFIGURED` instead of throwing\nexport function ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {\n if (!configuredTopics.includes(pubsubTopic)) {\n throw new Error(`Pubsub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);\n }\n}\n/**\n * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/\n * @param contentTopic String to validate\n * @returns Object with each content topic field as an attribute\n */\nexport function ensureValidContentTopic(contentTopic) {\n const parts = contentTopic.split(\"/\");\n if (parts.length < 5 || parts.length > 6) {\n throw Error(\"Content topic format is invalid\");\n }\n // Validate generation field if present\n let generation = 0;\n if (parts.length == 6) {\n generation = parseInt(parts[1]);\n if (isNaN(generation)) {\n throw new Error(\"Invalid generation field in content topic\");\n }\n if (generation > 0) {\n throw new Error(\"Generation greater than 0 is not supported\");\n }\n }\n // Validate remaining fields\n const fields = parts.splice(-4);\n // Validate application field\n if (fields[0].length == 0) {\n throw new Error(\"Application field cannot be empty\");\n }\n // Validate version field\n if (fields[1].length == 0) {\n throw new Error(\"Version field cannot be empty\");\n }\n // Validate topic name field\n if (fields[2].length == 0) {\n throw new Error(\"Topic name field cannot be empty\");\n }\n // Validate encoding field\n if (fields[3].length == 0) {\n throw new Error(\"Encoding field cannot be empty\");\n }\n return {\n generation,\n application: fields[0],\n version: fields[1],\n topicName: fields[2],\n encoding: fields[3]\n };\n}\n/**\n * Given a string, determines which autoshard index to use for its pubsub topic.\n * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm\n */\nexport function contentTopicToShardIndex(contentTopic, networkShards = 8) {\n const { application, version } = ensureValidContentTopic(contentTopic);\n const digest = sha256(concat([utf8ToBytes(application), utf8ToBytes(version)]));\n const dataview = new DataView(digest.buffer.slice(-8));\n return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));\n}\nexport function contentTopicToPubsubTopic(contentTopic, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n if (!contentTopic) {\n throw Error(\"Content topic must be specified\");\n }\n const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);\n return `/waku/2/rs/${clusterId}/${shardIndex}`;\n}\n/**\n * Given an array of content topics, groups them together by their Pubsub topic as derived using the algorithm for autosharding.\n * If any of the content topics are not properly formatted, the function will throw an error.\n */\nexport function contentTopicsByPubsubTopic(contentTopics, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n const groupedContentTopics = new Map();\n for (const contentTopic of contentTopics) {\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic, clusterId, networkShards);\n let topics = groupedContentTopics.get(pubsubTopic);\n if (!topics) {\n groupedContentTopics.set(pubsubTopic, []);\n topics = groupedContentTopics.get(pubsubTopic);\n }\n topics.push(contentTopic);\n }\n return groupedContentTopics;\n}\n/**\n * Used when creating encoders/decoders to determine which pubsub topic to use\n */\nexport function determinePubsubTopic(contentTopic, \n// TODO: make it accept ShardInfo https://github.com/waku-org/js-waku/issues/2086\npubsubTopicShardInfo) {\n if (typeof pubsubTopicShardInfo == \"string\") {\n return pubsubTopicShardInfo;\n }\n return pubsubTopicShardInfo?.shard !== undefined\n ? singleShardInfoToPubsubTopic(pubsubTopicShardInfo)\n : contentTopicToPubsubTopic(contentTopic, pubsubTopicShardInfo?.clusterId ?? DEFAULT_CLUSTER_ID);\n}\n/**\n * Validates sharding configuration and sets defaults where possible.\n * @returns Validated sharding parameters, with any missing values set to defaults\n */\nexport const ensureShardingConfigured = (networkConfig) => {\n const clusterId = networkConfig.clusterId ?? DEFAULT_CLUSTER_ID;\n const shards = \"shards\" in networkConfig ? networkConfig.shards : [];\n const contentTopics = \"contentTopics\" in networkConfig ? networkConfig.contentTopics : [];\n const isShardsConfigured = shards && shards.length > 0;\n const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;\n if (isShardsConfigured) {\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })\n };\n }\n if (isContentTopicsConfigured) {\n const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));\n const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics\n };\n }\n throw new Error(\"Missing minimum required configuration options for static sharding or autosharding.\");\n};\n//# sourceMappingURL=index.js.map","export const decodeRelayShard = (bytes) => {\n // explicitly converting to Uint8Array to avoid Buffer\n // https://github.com/libp2p/js-libp2p/issues/2146\n bytes = new Uint8Array(bytes);\n if (bytes.length < 3)\n throw new Error(\"Insufficient data\");\n const view = new DataView(bytes.buffer);\n const clusterId = view.getUint16(0);\n const shards = [];\n if (bytes.length === 130) {\n // rsv format (Bit Vector)\n for (let i = 0; i < 1024; i++) {\n const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (i % 8);\n if (view.getUint8(byteIndex) & (1 << bitIndex)) {\n shards.push(i);\n }\n }\n }\n else {\n // rs format (Index List)\n const numIndices = view.getUint8(2);\n for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {\n if (offset + 1 >= bytes.length)\n throw new Error(\"Unexpected end of data\");\n shards.push(view.getUint16(offset));\n }\n }\n return { clusterId, shards };\n};\nexport const encodeRelayShard = (shardInfo) => {\n const { clusterId, shards } = shardInfo;\n const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;\n const buffer = new ArrayBuffer(totalLength);\n const view = new DataView(buffer);\n view.setUint16(0, clusterId);\n if (shards.length >= 64) {\n // rsv format (Bit Vector)\n for (const index of shards) {\n const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (index % 8);\n view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));\n }\n }\n else {\n // rs format (Index List)\n view.setUint8(2, shards.length);\n for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {\n view.setUint16(offset, shards[i]);\n }\n }\n return new Uint8Array(buffer);\n};\n//# sourceMappingURL=relay_shard_codec.js.map","import debug from \"debug\";\nconst APP_NAME = \"waku\";\nexport class Logger {\n _info;\n _warn;\n _error;\n static createDebugNamespace(level, prefix) {\n return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;\n }\n constructor(prefix) {\n this._info = debug(Logger.createDebugNamespace(\"info\", prefix));\n this._warn = debug(Logger.createDebugNamespace(\"warn\", prefix));\n this._error = debug(Logger.createDebugNamespace(\"error\", prefix));\n }\n get info() {\n return this._info;\n }\n get warn() {\n return this._warn;\n }\n get error() {\n return this._error;\n }\n log(level, ...args) {\n const logger = this[level];\n logger(...args);\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_message as proto } from \"@waku/proto\";\nimport { determinePubsubTopic, Logger } from \"@waku/utils\";\nconst log = new Logger(\"message:version-0\");\nconst OneMillion = BigInt(1_000_000);\nexport const Version = 0;\nexport { proto };\nexport class DecodedMessage {\n pubsubTopic;\n proto;\n constructor(pubsubTopic, proto) {\n this.pubsubTopic = pubsubTopic;\n this.proto = proto;\n }\n get ephemeral() {\n return Boolean(this.proto.ephemeral);\n }\n get payload() {\n return this.proto.payload;\n }\n get contentTopic() {\n return this.proto.contentTopic;\n }\n get _rawTimestamp() {\n return this.proto.timestamp;\n }\n get timestamp() {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n return;\n }\n catch (e) {\n return;\n }\n }\n get meta() {\n return this.proto.meta;\n }\n get version() {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n return this.proto.version ?? 0;\n }\n get rateLimitProof() {\n return this.proto.rateLimitProof;\n }\n}\nexport class Encoder {\n contentTopic;\n ephemeral;\n pubsubTopic;\n metaSetter;\n constructor(contentTopic, ephemeral = false, pubsubTopic, metaSetter) {\n this.contentTopic = contentTopic;\n this.ephemeral = ephemeral;\n this.pubsubTopic = pubsubTopic;\n this.metaSetter = metaSetter;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n async toWire(message) {\n return proto.WakuMessage.encode(await this.toProtoObj(message));\n }\n async toProtoObj(message) {\n const timestamp = message.timestamp ?? new Date();\n const protoMessage = {\n payload: message.payload,\n version: Version,\n contentTopic: this.contentTopic,\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n meta: undefined,\n rateLimitProof: message.rateLimitProof,\n ephemeral: this.ephemeral\n };\n if (this.metaSetter) {\n const meta = this.metaSetter(protoMessage);\n return { ...protoMessage, meta };\n }\n return protoMessage;\n }\n}\n/**\n * Creates an encoder that encode messages without Waku level encryption or signature.\n *\n * An encoder is used to encode messages in the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format to be sent over the Waku network. The resulting encoder can then be\n * pass to { @link @waku/interfaces!ISender.send } to automatically encode outgoing\n * messages.\n */\nexport function createEncoder({ pubsubTopic, pubsubTopicShardInfo, contentTopic, ephemeral, metaSetter }) {\n return new Encoder(contentTopic, ephemeral, determinePubsubTopic(contentTopic, pubsubTopic ?? pubsubTopicShardInfo), metaSetter);\n}\nexport class Decoder {\n pubsubTopic;\n contentTopic;\n constructor(pubsubTopic, contentTopic) {\n this.pubsubTopic = pubsubTopic;\n this.contentTopic = contentTopic;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n fromWireToProtoObj(bytes) {\n const protoMessage = proto.WakuMessage.decode(bytes);\n return Promise.resolve({\n payload: protoMessage.payload,\n contentTopic: protoMessage.contentTopic,\n version: protoMessage.version ?? undefined,\n timestamp: protoMessage.timestamp ?? undefined,\n meta: protoMessage.meta ?? undefined,\n rateLimitProof: protoMessage.rateLimitProof ?? undefined,\n ephemeral: protoMessage.ephemeral ?? false\n });\n }\n async fromProtoObj(pubsubTopic, proto) {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n if (proto.version ?? 0 !== Version) {\n log.error(\"Failed to decode due to incorrect version, expected:\", Version, \", actual:\", proto.version);\n return Promise.resolve(undefined);\n }\n return new DecodedMessage(pubsubTopic, proto);\n }\n}\n/**\n * Creates a decoder that decode messages without Waku level encryption.\n *\n * A decoder is used to decode messages from the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format when received from the Waku network. The resulting decoder can then be\n * pass to { @link @waku/interfaces!IReceiver.subscribe } to automatically decode incoming\n * messages.\n *\n * @param contentTopic The resulting decoder will only decode messages with this content topic.\n */\nexport function createDecoder(contentTopic, pubsubTopicShardInfo) {\n return new Decoder(determinePubsubTopic(contentTopic, pubsubTopicShardInfo), contentTopic);\n}\n//# sourceMappingURL=version_0.js.map","/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction all(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = [];\n for await (const entry of source) {\n arr.push(entry);\n }\n return arr;\n })();\n }\n const arr = [];\n for (const entry of source) {\n arr.push(entry);\n }\n return arr;\n}\nexport default all;\n//# sourceMappingURL=index.js.map","import { allocUnsafe } from '#alloc';\nimport { asUint8Array } from '#util/as-uint8array';\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}\n//# sourceMappingURL=concat.js.map","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map","/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc';\nimport { concat } from 'uint8arrays/concat';\nimport { equals } from 'uint8arrays/equals';\nconst symbol = Symbol.for('@achingbrain/uint8arraylist');\nfunction findBufAndOffset(bufs, index) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds');\n }\n let offset = 0;\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength;\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n };\n }\n offset = bufEnd;\n }\n throw new RangeError('index is out of bounds');\n}\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList(value) {\n return Boolean(value?.[symbol]);\n}\nexport class Uint8ArrayList {\n bufs;\n length;\n [symbol] = true;\n constructor(...data) {\n this.bufs = [];\n this.length = 0;\n if (data.length > 0) {\n this.appendAll(data);\n }\n }\n *[Symbol.iterator]() {\n yield* this.bufs;\n }\n get byteLength() {\n return this.length;\n }\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append(...bufs) {\n this.appendAll(bufs);\n }\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll(bufs) {\n let length = 0;\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.push(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.push(...buf.bufs);\n }\n else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend(...bufs) {\n this.prependAll(bufs);\n }\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll(bufs) {\n let length = 0;\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.unshift(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.unshift(...buf.bufs);\n }\n else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Read the value at `index`\n */\n get(index) {\n const res = findBufAndOffset(this.bufs, index);\n return res.buf[res.index];\n }\n /**\n * Set the value at `index` to `value`\n */\n set(index, value) {\n const res = findBufAndOffset(this.bufs, index);\n res.buf[res.index] = value;\n }\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i]);\n }\n }\n else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i));\n }\n }\n else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n /**\n * Remove bytes from the front of the pool\n */\n consume(bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes);\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return;\n }\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = [];\n this.length = 0;\n return;\n }\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength;\n this.length -= this.bufs[0].byteLength;\n this.bufs.shift();\n }\n else {\n this.bufs[0] = this.bufs[0].subarray(bytes);\n this.length -= bytes;\n break;\n }\n }\n }\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n return concat(bufs, length);\n }\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n if (bufs.length === 1) {\n return bufs[0];\n }\n return concat(bufs, length);\n }\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n const list = new Uint8ArrayList();\n list.length = length;\n // don't loop, just set the bufs\n list.bufs = [...bufs];\n return list;\n }\n _subList(beginInclusive, endExclusive) {\n beginInclusive = beginInclusive ?? 0;\n endExclusive = endExclusive ?? this.length;\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive;\n }\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive;\n }\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds');\n }\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 };\n }\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length };\n }\n const bufs = [];\n let offset = 0;\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i];\n const bufStart = offset;\n const bufEnd = bufStart + buf.byteLength;\n // for next loop\n offset = bufEnd;\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue;\n }\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n const start = beginInclusive - bufStart;\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));\n break;\n }\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf);\n continue;\n }\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart));\n continue;\n }\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart));\n break;\n }\n // slice started before this buffer and ends after it\n bufs.push(buf);\n }\n return { bufs, length: endExclusive - beginInclusive };\n }\n indexOf(search, offset = 0) {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array');\n }\n const needle = search instanceof Uint8Array ? search : search.subarray();\n offset = Number(offset ?? 0);\n if (isNaN(offset)) {\n offset = 0;\n }\n if (offset < 0) {\n offset = this.length + offset;\n }\n if (offset < 0) {\n offset = 0;\n }\n if (search.length === 0) {\n return offset > this.length ? this.length : offset;\n }\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M = needle.byteLength;\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long');\n }\n // radix\n const radix = 256;\n const rightmostPositions = new Int32Array(radix);\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1;\n }\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j;\n }\n // Return offset of first match, -1 if no match\n const right = rightmostPositions;\n const lastIndex = this.byteLength - needle.byteLength;\n const lastPatIndex = needle.byteLength - 1;\n let skip;\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0;\n for (let j = lastPatIndex; j >= 0; j--) {\n const char = this.get(i + j);\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char]);\n break;\n }\n }\n if (skip === 0) {\n return i;\n }\n }\n return -1;\n }\n getInt8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt8(0);\n }\n setInt8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt8(0, value);\n this.write(buf, byteOffset);\n }\n getInt16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt16(0, littleEndian);\n }\n setInt16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getInt32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt32(0, littleEndian);\n }\n setInt32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigInt64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigInt64(0, littleEndian);\n }\n setBigInt64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigInt64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint8(0);\n }\n setUint8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint8(0, value);\n this.write(buf, byteOffset);\n }\n getUint16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint16(0, littleEndian);\n }\n setUint16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint32(0, littleEndian);\n }\n setUint32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigUint64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigUint64(0, littleEndian);\n }\n setBigUint64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigUint64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat32(0, littleEndian);\n }\n setFloat32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat64(0, littleEndian);\n }\n setFloat64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (!(other instanceof Uint8ArrayList)) {\n return false;\n }\n if (other.bufs.length !== this.bufs.length) {\n return false;\n }\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false;\n }\n }\n return true;\n }\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays(bufs, length) {\n const list = new Uint8ArrayList();\n list.bufs = bufs;\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);\n }\n list.length = length;\n return list;\n }\n}\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n//# sourceMappingURL=index.js.map","export function isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\n//# sourceMappingURL=utils.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { isAsyncIterable } from './utils.js';\nconst defaultEncoder = (length) => {\n const lengthLength = varint.encodingLength(length);\n const lengthBuf = allocUnsafe(lengthLength);\n varint.encode(length, lengthBuf);\n defaultEncoder.bytes = lengthLength;\n return lengthBuf;\n};\ndefaultEncoder.bytes = 0;\nexport function encode(source, options) {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n function* maybeYield(chunk) {\n // length + data\n const length = encodeLength(chunk.byteLength);\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length;\n }\n else {\n yield* length;\n }\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk;\n }\n else {\n yield* chunk;\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n }\n return (function* () {\n for (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n}\nencode.single = (chunk, options) => {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n return new Uint8ArrayList(encodeLength(chunk.byteLength), chunk);\n};\n//# sourceMappingURL=encode.js.map","/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map","/* eslint max-depth: [\"error\", 6] */\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js';\nimport { isAsyncIterable } from './utils.js';\n// Maximum length of the length section of the message\nexport const MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nexport const MAX_DATA_LENGTH = 1024 * 1024 * 4;\nvar ReadMode;\n(function (ReadMode) {\n ReadMode[ReadMode[\"LENGTH\"] = 0] = \"LENGTH\";\n ReadMode[ReadMode[\"DATA\"] = 1] = \"DATA\";\n})(ReadMode || (ReadMode = {}));\nconst defaultDecoder = (buf) => {\n const length = varint.decode(buf);\n defaultDecoder.bytes = varint.encodingLength(length);\n return length;\n};\ndefaultDecoder.bytes = 0;\nexport function decode(source, options) {\n const buffer = new Uint8ArrayList();\n let mode = ReadMode.LENGTH;\n let dataLength = -1;\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;\n function* maybeYield() {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer);\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long');\n }\n const dataLengthLength = lengthDecoder.bytes;\n buffer.consume(dataLengthLength);\n if (options?.onLength != null) {\n options.onLength(dataLength);\n }\n mode = ReadMode.DATA;\n }\n catch (err) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long');\n }\n break;\n }\n throw err;\n }\n }\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break;\n }\n const data = buffer.sublist(0, dataLength);\n buffer.consume(dataLength);\n if (options?.onData != null) {\n options.onData(data);\n }\n yield data;\n mode = ReadMode.LENGTH;\n }\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input');\n }\n })();\n }\n return (function* () {\n for (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input');\n }\n })();\n}\ndecode.fromReader = (reader, options) => {\n let byteLength = 1; // Read single byte chunks until the length is known\n const varByteSource = (async function* () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength);\n if (done === true) {\n return;\n }\n if (value != null) {\n yield value;\n }\n }\n catch (err) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null };\n }\n throw err;\n }\n finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1;\n }\n }\n }());\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l) => { byteLength = l; };\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n });\n};\n//# sourceMappingURL=decode.js.map","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","// ported from https://www.npmjs.com/package/fast-fifo\nclass FixedFIFO {\n buffer;\n mask;\n top;\n btm;\n next;\n constructor(hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two');\n }\n this.buffer = new Array(hwm);\n this.mask = hwm - 1;\n this.top = 0;\n this.btm = 0;\n this.next = null;\n }\n push(data) {\n if (this.buffer[this.top] !== undefined) {\n return false;\n }\n this.buffer[this.top] = data;\n this.top = (this.top + 1) & this.mask;\n return true;\n }\n shift() {\n const last = this.buffer[this.btm];\n if (last === undefined) {\n return undefined;\n }\n this.buffer[this.btm] = undefined;\n this.btm = (this.btm + 1) & this.mask;\n return last;\n }\n isEmpty() {\n return this.buffer[this.btm] === undefined;\n }\n}\nexport class FIFO {\n size;\n hwm;\n head;\n tail;\n constructor(options = {}) {\n this.hwm = options.splitLimit ?? 16;\n this.head = new FixedFIFO(this.hwm);\n this.tail = this.head;\n this.size = 0;\n }\n calculateSize(obj) {\n if (obj?.byteLength != null) {\n return obj.byteLength;\n }\n return 1;\n }\n push(val) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value);\n }\n if (!this.head.push(val)) {\n const prev = this.head;\n this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);\n this.head.push(val);\n }\n }\n shift() {\n let val = this.tail.shift();\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next;\n this.tail.next = null;\n this.tail = next;\n val = this.tail.shift();\n }\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value);\n }\n return val;\n }\n isEmpty() {\n return this.head.isEmpty();\n }\n}\n//# sourceMappingURL=fifo.js.map","/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\nimport deferred from 'p-defer';\nimport { FIFO } from './fifo.js';\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.code = code ?? 'ABORT_ERR';\n }\n}\nexport function pushable(options = {}) {\n const getNext = (buffer) => {\n const next = buffer.shift();\n if (next == null) {\n return { done: true };\n }\n if (next.error != null) {\n throw next.error;\n }\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n };\n };\n return _pushable(getNext, options);\n}\nexport function pushableV(options = {}) {\n const getNext = (buffer) => {\n let next;\n const values = [];\n while (!buffer.isEmpty()) {\n next = buffer.shift();\n if (next == null) {\n break;\n }\n if (next.error != null) {\n throw next.error;\n }\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value);\n }\n }\n if (next == null) {\n return { done: true };\n }\n return {\n done: next.done === true,\n value: values\n };\n };\n return _pushable(getNext, options);\n}\nfunction _pushable(getNext, options) {\n options = options ?? {};\n let onEnd = options.onEnd;\n let buffer = new FIFO();\n let pushable;\n let onNext;\n let ended;\n let drain = deferred();\n const waitNext = async () => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer);\n }\n if (ended) {\n return { done: true };\n }\n return await new Promise((resolve, reject) => {\n onNext = (next) => {\n onNext = null;\n buffer.push(next);\n try {\n resolve(getNext(buffer));\n }\n catch (err) {\n reject(err);\n }\n return pushable;\n };\n });\n }\n finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve();\n drain = deferred();\n });\n }\n }\n };\n const bufferNext = (next) => {\n if (onNext != null) {\n return onNext(next);\n }\n buffer.push(next);\n return pushable;\n };\n const bufferError = (err) => {\n buffer = new FIFO();\n if (onNext != null) {\n return onNext({ error: err });\n }\n buffer.push({ error: err });\n return pushable;\n };\n const push = (value) => {\n if (ended) {\n return pushable;\n }\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value');\n }\n return bufferNext({ done: false, value });\n };\n const end = (err) => {\n if (ended)\n return pushable;\n ended = true;\n return (err != null) ? bufferError(err) : bufferNext({ done: true });\n };\n const _return = () => {\n buffer = new FIFO();\n end();\n return { done: true };\n };\n const _throw = (err) => {\n end(err);\n return { done: true };\n };\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength() {\n return buffer.size;\n },\n onEmpty: async (options) => {\n const signal = options?.signal;\n signal?.throwIfAborted();\n if (buffer.isEmpty()) {\n return;\n }\n let cancel;\n let listener;\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError());\n };\n signal.addEventListener('abort', listener);\n });\n }\n try {\n await Promise.race([\n drain.promise,\n cancel\n ]);\n }\n finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener);\n }\n }\n }\n };\n if (onEnd == null) {\n return pushable;\n }\n const _pushable = pushable;\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next() {\n return _pushable.next();\n },\n throw(err) {\n _pushable.throw(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return { done: true };\n },\n return() {\n _pushable.return();\n if (onEnd != null) {\n onEnd();\n onEnd = undefined;\n }\n return { done: true };\n },\n push,\n end(err) {\n _pushable.end(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return pushable;\n },\n get readableLength() {\n return _pushable.readableLength;\n },\n onEmpty: (opts) => {\n return _pushable.onEmpty(opts);\n }\n };\n return pushable;\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\nimport { pushable } from 'it-pushable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction merge(...sources) {\n const syncSources = [];\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source);\n }\n }\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return (function* () {\n for (const source of syncSources) {\n yield* source;\n }\n })();\n }\n return (async function* () {\n const output = pushable({\n objectMode: true\n });\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(sources.map(async (source) => {\n for await (const item of source) {\n output.push(item);\n }\n }));\n output.end();\n }\n catch (err) {\n output.end(err);\n }\n });\n yield* output;\n })();\n}\nexport default merge;\n//# sourceMappingURL=index.js.map","import { pushable } from 'it-pushable';\nimport merge from 'it-merge';\nexport function pipe(first, ...rest) {\n if (first == null) {\n throw new Error('Empty pipeline');\n }\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first;\n first = () => duplex.source;\n // Iterable at start: wrap in function\n }\n else if (isIterable(first) || isAsyncIterable(first)) {\n const source = first;\n first = () => source;\n }\n const fns = [first, ...rest];\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink;\n }\n }\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i]);\n }\n }\n }\n return rawPipe(...fns);\n}\nexport const rawPipe = (...fns) => {\n let res;\n while (fns.length > 0) {\n res = fns.shift()(res);\n }\n return res;\n};\nconst isAsyncIterable = (obj) => {\n return obj?.[Symbol.asyncIterator] != null;\n};\nconst isIterable = (obj) => {\n return obj?.[Symbol.iterator] != null;\n};\nconst isDuplex = (obj) => {\n if (obj == null) {\n return false;\n }\n return obj.sink != null && obj.source != null;\n};\nconst duplexPipelineFn = (duplex) => {\n return (source) => {\n const p = duplex.sink(source);\n if (p?.then != null) {\n const stream = pushable({\n objectMode: true\n });\n p.then(() => {\n stream.end();\n }, (err) => {\n stream.end(err);\n });\n let sourceWrap;\n const source = duplex.source;\n if (isAsyncIterable(source)) {\n sourceWrap = async function* () {\n yield* source;\n stream.end();\n };\n }\n else if (isIterable(source)) {\n sourceWrap = function* () {\n yield* source;\n stream.end();\n };\n }\n else {\n throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable');\n }\n return merge(stream, sourceWrap());\n }\n return duplex.source;\n };\n};\n//# sourceMappingURL=index.js.map","export function selectOpenConnection(connections) {\n return connections\n .filter((c) => c.status === \"open\")\n .sort((left, right) => right.timeline.open - left.timeline.open)\n .at(0);\n}\n//# sourceMappingURL=utils.js.map","import { Logger } from \"@waku/utils\";\nimport { selectOpenConnection } from \"./utils.js\";\nconst STREAM_LOCK_KEY = \"consumed\";\nexport class StreamManager {\n multicodec;\n getConnections;\n addEventListener;\n log;\n ongoingCreation = new Set();\n streamPool = new Map();\n constructor(multicodec, getConnections, addEventListener) {\n this.multicodec = multicodec;\n this.getConnections = getConnections;\n this.addEventListener = addEventListener;\n this.log = new Logger(`stream-manager:${multicodec}`);\n this.addEventListener(\"peer:update\", this.handlePeerUpdateStreamPool);\n }\n async getStream(peer) {\n const peerId = peer.id.toString();\n const scheduledStream = this.streamPool.get(peerId);\n if (scheduledStream) {\n this.streamPool.delete(peerId);\n await scheduledStream;\n }\n let stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n stream = await this.createStream(peer);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n async createStream(peer, retries = 0) {\n const connections = this.getConnections(peer.id);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n }\n let lastError;\n let stream;\n for (let i = 0; i < retries + 1; i++) {\n try {\n this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n stream = await connection.newStream(this.multicodec);\n this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n break;\n }\n catch (error) {\n lastError = error;\n }\n }\n if (!stream) {\n throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +\n lastError);\n }\n return stream;\n }\n async createStreamWithLock(peer) {\n const peerId = peer.id.toString();\n if (this.ongoingCreation.has(peerId)) {\n this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);\n return;\n }\n try {\n this.ongoingCreation.add(peerId);\n await this.createStream(peer);\n }\n catch (error) {\n this.log.error(`Failed to createStreamWithLock:`, error);\n }\n finally {\n this.ongoingCreation.delete(peerId);\n }\n return;\n }\n handlePeerUpdateStreamPool = (evt) => {\n const { peer } = evt.detail;\n if (!peer.protocols.includes(this.multicodec)) {\n return;\n }\n const stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n return;\n }\n this.scheduleNewStream(peer);\n };\n scheduleNewStream(peer) {\n this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n // abandon previous attempt\n if (this.streamPool.has(peer.id.toString())) {\n this.streamPool.delete(peer.id.toString());\n }\n this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));\n }\n getOpenStreamForCodec(peerId) {\n const connections = this.getConnections(peerId);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n return;\n }\n const stream = connection.streams.find((s) => s.protocol === this.multicodec);\n if (!stream) {\n return;\n }\n const isStreamUnusable = [\"done\", \"closed\", \"closing\"].includes(stream.writeStatus || \"\");\n if (isStreamUnusable || this.isStreamLocked(stream)) {\n return;\n }\n return stream;\n }\n lockStream(peerId, stream) {\n this.log.info(`Locking stream for peerId:${peerId}\\tstreamId:${stream.id}`);\n stream.metadata[STREAM_LOCK_KEY] = true;\n }\n isStreamLocked(stream) {\n return !!stream.metadata[STREAM_LOCK_KEY];\n }\n}\n//# sourceMappingURL=stream_manager.js.map","import { getPeersForProtocol, sortPeersByLatency } from \"@waku/utils/libp2p\";\nimport { filterPeersByDiscovery } from \"./filterPeers.js\";\nimport { StreamManager } from \"./stream_manager/index.js\";\n/**\n * A class with predefined helpers, to be used as a base to implement Waku\n * Protocols.\n */\nexport class BaseProtocol {\n multicodec;\n components;\n log;\n pubsubTopics;\n addLibp2pEventListener;\n removeLibp2pEventListener;\n streamManager;\n constructor(multicodec, components, log, pubsubTopics) {\n this.multicodec = multicodec;\n this.components = components;\n this.log = log;\n this.pubsubTopics = pubsubTopics;\n this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);\n this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);\n this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);\n }\n async getStream(peer) {\n return this.streamManager.getStream(peer);\n }\n /**\n * Returns known peers from the address book (`libp2p.peerStore`) that support\n * the class protocol. Waku may or may not be currently connected to these\n * peers.\n */\n async allPeers() {\n return getPeersForProtocol(this.components.peerStore, [this.multicodec]);\n }\n async connectedPeers() {\n const peers = await this.allPeers();\n return peers.filter((peer) => {\n const connections = this.components.connectionManager.getConnections(peer.id);\n return connections.length > 0;\n });\n }\n /**\n * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.\n *\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n * @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.\n */\n async getPeers({ numPeers, maxBootstrapPeers } = {\n maxBootstrapPeers: 0,\n numPeers: 0\n }) {\n // Retrieve all connected peers that support the protocol & shard (if configured)\n const allAvailableConnectedPeers = await this.connectedPeers();\n // Filter the peers based on discovery & number of peers requested\n const filteredPeers = filterPeersByDiscovery(allAvailableConnectedPeers, numPeers, maxBootstrapPeers);\n // Sort the peers by latency\n const sortedFilteredPeers = await sortPeersByLatency(this.components.peerStore, filteredPeers);\n if (sortedFilteredPeers.length === 0) {\n this.log.warn(\"No peers found. Ensure you have a connection to the network.\");\n }\n if (sortedFilteredPeers.length < numPeers) {\n this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);\n }\n return sortedFilteredPeers;\n }\n}\n//# sourceMappingURL=base_protocol.js.map","import { bytesToUtf8 } from \"../bytes/index.js\";\n/**\n * Returns a pseudo-random peer that supports the given protocol.\n * Useful for protocols such as store and light push\n */\nexport function selectRandomPeer(peers) {\n if (peers.length === 0)\n return;\n const index = Math.round(Math.random() * (peers.length - 1));\n return peers[index];\n}\n/**\n * Function to sort peers by latency from lowest to highest\n * @param peerStore - The Libp2p PeerStore\n * @param peers - The list of peers to choose from\n * @returns Sorted array of peers by latency\n */\nexport async function sortPeersByLatency(peerStore, peers) {\n if (peers.length === 0)\n return [];\n const results = await Promise.all(peers.map(async (peer) => {\n try {\n const pingBytes = (await peerStore.get(peer.id)).metadata.get(\"ping\");\n if (!pingBytes)\n return { peer, ping: Infinity };\n const ping = Number(bytesToUtf8(pingBytes));\n return { peer, ping };\n }\n catch (error) {\n return { peer, ping: Infinity };\n }\n }));\n // filter out null values\n const validResults = results.filter((result) => result !== null);\n return validResults\n .sort((a, b) => a.ping - b.ping)\n .map((result) => result.peer);\n}\n/**\n * Returns the list of peers that supports the given protocol.\n */\nexport async function getPeersForProtocol(peerStore, protocols) {\n const peers = [];\n await peerStore.forEach((peer) => {\n for (let i = 0; i < protocols.length; i++) {\n if (peer.protocols.includes(protocols[i])) {\n peers.push(peer);\n break;\n }\n }\n });\n return peers;\n}\n//# sourceMappingURL=index.js.map","import { Tags } from \"@waku/interfaces\";\n/**\n * Retrieves a list of peers based on the specified criteria:\n * 1. If numPeers is 0, return all peers\n * 2. Bootstrap peers are prioritized\n * 3. Non-bootstrap peers are randomly selected to fill up to numPeers\n *\n * @param peers - The list of peers to filter from.\n * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.\n * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.\n * @returns An array of peers based on the specified criteria.\n */\nexport function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {\n // Collect the bootstrap peers up to the specified maximum\n let bootstrapPeers = peers\n .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))\n .slice(0, maxBootstrapPeers);\n // If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array\n if (numPeers > 0 && numPeers < bootstrapPeers.length) {\n bootstrapPeers = bootstrapPeers.slice(0, numPeers);\n }\n // Collect non-bootstrap peers\n const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));\n // If numPeers is 0, return all peers\n if (numPeers === 0) {\n return [...bootstrapPeers, ...nonBootstrapPeers];\n }\n // Initialize the list of selected peers with the bootstrap peers\n const selectedPeers = [...bootstrapPeers];\n // Fill up to numPeers with remaining random peers if needed\n while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {\n const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);\n const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];\n selectedPeers.push(randomPeer);\n }\n return selectedPeers;\n}\n//# sourceMappingURL=filterPeers.js.map","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import { proto_filter_v2 as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n/**\n * FilterPushRPC represents a message conforming to the Waku FilterPush protocol.\n * Protocol documentation: https://rfc.vac.dev/spec/12/\n */\nexport class FilterPushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.MessagePush.decode(bytes);\n return new FilterPushRpc(res);\n }\n encode() {\n return proto.MessagePush.encode(this.proto);\n }\n get wakuMessage() {\n return this.proto.wakuMessage;\n }\n /**\n * Get the pubsub topic from the FilterPushRpc object.\n * @returns string\n */\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n}\nexport class FilterSubscribeRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createSubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeAllRequest(pubsubTopic) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE_ALL,\n pubsubTopic,\n contentTopics: []\n });\n }\n static createSubscriberPingRequest() {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBER_PING,\n pubsubTopic: \"\",\n contentTopics: []\n });\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeRequest.decode(bytes);\n return new FilterSubscribeRpc(res);\n }\n encode() {\n return proto.FilterSubscribeRequest.encode(this.proto);\n }\n get filterSubscribeType() {\n return this.proto.filterSubscribeType;\n }\n get requestId() {\n return this.proto.requestId;\n }\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n get contentTopics() {\n return this.proto.contentTopics;\n }\n}\nexport class FilterSubscribeResponse {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeResponse.decode(bytes);\n return new FilterSubscribeResponse(res);\n }\n encode() {\n return proto.FilterSubscribeResponse.encode(this.proto);\n }\n get statusCode() {\n return this.proto.statusCode;\n }\n get statusDesc() {\n return this.proto.statusDesc;\n }\n get requestId() {\n return this.proto.requestId;\n }\n}\n//# sourceMappingURL=filter_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { FilterPushRpc, FilterSubscribeResponse, FilterSubscribeRpc } from \"./filter_rpc.js\";\nconst log = new Logger(\"filter:v2\");\nexport const FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\nexport class FilterCore extends BaseProtocol {\n handleIncomingMessage;\n pubsubTopics;\n constructor(handleIncomingMessage, pubsubTopics, libp2p) {\n super(FilterCodecs.SUBSCRIBE, libp2p.components, log, pubsubTopics);\n this.handleIncomingMessage = handleIncomingMessage;\n this.pubsubTopics = pubsubTopics;\n libp2p\n .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {\n maxInboundStreams: 100\n })\n .catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n }\n async subscribe(pubsubTopic, peer, contentTopics) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createSubscribeRequest(pubsubTopic, contentTopics);\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send subscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async unsubscribe(pubsubTopic, peer, contentTopics) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n const unsubscribeRequest = FilterSubscribeRpc.createUnsubscribeRequest(pubsubTopic, contentTopics);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);\n }\n catch (error) {\n log.error(\"Failed to send unsubscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n async unsubscribeAll(pubsubTopic, peer) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);\n const res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n if (!res || !res.length) {\n return {\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n },\n success: null\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async ping(peer) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n const request = FilterSubscribeRpc.createSubscriberPingRequest();\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send ping request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n if (!res || !res.length) {\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n onRequest(streamData) {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n pipe(stream, lp.decode, async (source) => {\n for await (const bytes of source) {\n const response = FilterPushRpc.decode(bytes.slice());\n const { pubsubTopic, wakuMessage } = response;\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n await this.handleIncomingMessage(pubsubTopic, wakuMessage, connection.remotePeer.toString());\n }\n }).then(() => {\n log.info(\"Receiving pipe closed.\");\n }, async (e) => {\n log.error(`Error with receiving pipe on peer:${connection.remotePeer.toString()} -- stream:${stream.id} -- protocol:${stream.protocol}: `, e);\n });\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_lightpush as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\nexport class PushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(message, pubsubTopic) {\n return new PushRpc({\n requestId: uuid(),\n request: {\n message: message,\n pubsubTopic: pubsubTopic\n },\n response: undefined\n });\n }\n static decode(bytes) {\n const res = proto.PushRpc.decode(bytes);\n return new PushRpc(res);\n }\n encode() {\n return proto.PushRpc.encode(this.proto);\n }\n get query() {\n return this.proto.request;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=push_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\n// should match nwaku\n// https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/rln_relay.nim#L309\n// https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/tests/waku_rln_relay/rln/waku_rln_relay_utils.nim#L20\nconst RLN_GENERATION_PREFIX_ERROR = \"could not generate rln-v2 proof\";\nexport const isRLNResponseError = (info) => {\n if (!info) {\n return false;\n }\n return info.includes(RLN_GENERATION_PREFIX_ERROR);\n};\nexport const matchRLNErrorMessage = (info) => {\n const rlnErrorMap = {\n [ProtocolError.RLN_IDENTITY_MISSING]: ProtocolError.RLN_IDENTITY_MISSING,\n [ProtocolError.RLN_MEMBERSHIP_INDEX]: ProtocolError.RLN_MEMBERSHIP_INDEX,\n [ProtocolError.RLN_LIMIT_MISSING]: ProtocolError.RLN_LIMIT_MISSING\n };\n const infoLowerCase = info.toLowerCase();\n for (const errorKey in rlnErrorMap) {\n if (infoLowerCase.includes(errorKey.toLowerCase())) {\n return rlnErrorMap[errorKey];\n }\n }\n return ProtocolError.RLN_PROOF_GENERATION;\n};\n//# sourceMappingURL=utils.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { PushResponse } from \"@waku/proto\";\nimport { isMessageSizeUnderCap } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { PushRpc } from \"./push_rpc.js\";\nimport { isRLNResponseError, matchRLNErrorMessage } from \"./utils.js\";\nconst log = new Logger(\"light-push\");\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class LightPushCore extends BaseProtocol {\n pubsubTopics;\n constructor(pubsubTopics, libp2p) {\n super(LightPushCodec, libp2p.components, log, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n }\n async preparePushMessage(encoder, message) {\n try {\n if (!message.payload || message.payload.length === 0) {\n log.error(\"Failed to send waku light push: payload is empty\");\n return { query: null, error: ProtocolError.EMPTY_PAYLOAD };\n }\n if (!(await isMessageSizeUnderCap(encoder, message))) {\n log.error(\"Failed to send waku light push: message is bigger than 1MB\");\n return { query: null, error: ProtocolError.SIZE_TOO_BIG };\n }\n const protoMessage = await encoder.toProtoObj(message);\n if (!protoMessage) {\n log.error(\"Failed to encode to protoMessage, aborting push\");\n return {\n query: null,\n error: ProtocolError.ENCODE_FAILED\n };\n }\n const query = PushRpc.createRequest(protoMessage, encoder.pubsubTopic);\n return { query, error: null };\n }\n catch (error) {\n log.error(\"Failed to prepare push message\", error);\n return {\n query: null,\n error: ProtocolError.GENERIC_FAIL\n };\n }\n }\n async send(encoder, message, peer) {\n const { query, error: preparationError } = await this.preparePushMessage(encoder, message);\n if (preparationError || !query) {\n return {\n success: null,\n failure: {\n error: preparationError,\n peerId: peer.id\n }\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n let res;\n try {\n res = await pipe([query.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (err) {\n log.error(\"Failed to send waku light push request\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n let response;\n try {\n response = PushRpc.decode(bytes).response;\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.DECODE_FAILED,\n peerId: peer.id\n }\n };\n }\n if (!response) {\n log.error(\"Remote peer fault: No response in PushRPC\");\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n }\n };\n }\n if (isRLNResponseError(response.info)) {\n const rlnErrorCase = matchRLNErrorMessage(response.info);\n log.error(\"Remote peer rejected the message: \", rlnErrorCase);\n return {\n success: null,\n failure: {\n error: rlnErrorCase,\n peerId: peer.id\n }\n };\n }\n if (!response.isSuccess) {\n log.error(\"Remote peer rejected the message: \", response.info);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return { success: peer.id, failure: null };\n }\n}\n//# sourceMappingURL=index.js.map","const MB = 1024 ** 2;\nconst SIZE_CAP_IN_MB = 1;\n/**\n * Return whether the size of the message is under the upper limit for the network.\n * This performs a protobuf encoding! If you have access to the fully encoded message,\n * use {@link isSizeUnderCapBuf} instead.\n * @param message\n * @param encoder\n */\nexport async function isMessageSizeUnderCap(encoder, message) {\n const buf = await encoder.toWire(message);\n if (!buf)\n return false;\n return isWireSizeUnderCap(buf);\n}\nexport const isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;\n//# sourceMappingURL=is_size_valid.js.map","const EmptyMessage = {\n payload: new Uint8Array(),\n contentTopic: \"\",\n version: undefined,\n timestamp: undefined,\n meta: undefined,\n rateLimitProof: undefined,\n ephemeral: undefined\n};\nexport function toProtoMessage(wire) {\n return { ...EmptyMessage, ...wire };\n}\n//# sourceMappingURL=to_proto_message.js.map","import { proto_store as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n// https://github.com/waku-org/nwaku/blob/7205f95cff9f49ca0bb762e8fd0bf56a6a7f3b3b/waku/waku_store/common.nim#L12\nexport const DEFAULT_PAGE_SIZE = 20;\nexport const MAX_PAGE_SIZE = 100;\nconst ONE_MILLION = 1_000000;\nexport class StoreQueryRequest {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static create(params) {\n const request = new StoreQueryRequest({\n ...params,\n requestId: uuid(),\n timeStart: params.timeStart\n ? BigInt(params.timeStart.getTime() * ONE_MILLION)\n : undefined,\n timeEnd: params.timeEnd\n ? BigInt(params.timeEnd.getTime() * ONE_MILLION)\n : undefined,\n messageHashes: params.messageHashes || [],\n paginationLimit: params.paginationLimit\n ? BigInt(params.paginationLimit)\n : undefined\n });\n // Validate request parameters based on RFC\n if ((params.pubsubTopic && !params.contentTopics) ||\n (!params.pubsubTopic && params.contentTopics)) {\n throw new Error(\"Both pubsubTopic and contentTopics must be set or unset\");\n }\n if (params.messageHashes &&\n (params.pubsubTopic ||\n params.contentTopics ||\n params.timeStart ||\n params.timeEnd)) {\n throw new Error(\"Message hash lookup queries cannot include content filter criteria\");\n }\n return request;\n }\n static decode(bytes) {\n const res = proto.StoreQueryRequest.decode(bytes);\n return new StoreQueryRequest(res);\n }\n encode() {\n return proto.StoreQueryRequest.encode(this.proto);\n }\n}\nexport class StoreQueryResponse {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.StoreQueryResponse.decode(bytes);\n return new StoreQueryResponse(res);\n }\n encode() {\n return proto.StoreQueryResponse.encode(this.proto);\n }\n get statusCode() {\n return this.proto.statusCode;\n }\n get statusDesc() {\n return this.proto.statusDesc;\n }\n get messages() {\n return this.proto.messages;\n }\n get paginationCursor() {\n return this.proto.paginationCursor;\n }\n}\n//# sourceMappingURL=rpc.js.map","import { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { toProtoMessage } from \"../to_proto_message.js\";\nimport { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, StoreQueryRequest, StoreQueryResponse } from \"./rpc.js\";\nconst log = new Logger(\"store\");\nexport const StoreCodec = \"/vac/waku/store-query/3.0.0\";\nexport class StoreCore extends BaseProtocol {\n pubsubTopics;\n constructor(pubsubTopics, libp2p) {\n super(StoreCodec, libp2p.components, log, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n }\n async *queryPerPage(queryOpts, decoders, peer) {\n if (queryOpts.contentTopics.toString() !==\n Array.from(decoders.keys()).toString()) {\n throw new Error(\"Internal error, the decoders should match the query's content topics\");\n }\n let currentCursor = queryOpts.paginationCursor;\n while (true) {\n const storeQueryRequest = StoreQueryRequest.create({\n ...queryOpts,\n paginationCursor: currentCursor\n });\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (e) {\n log.error(\"Failed to get stream\", e);\n break;\n }\n const res = await pipe([storeQueryRequest.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const storeQueryResponse = StoreQueryResponse.decode(bytes);\n if (!storeQueryResponse.statusCode ||\n storeQueryResponse.statusCode >= 300) {\n const errorMessage = `Store query failed with status code: ${storeQueryResponse.statusCode}, description: ${storeQueryResponse.statusDesc}`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n if (!storeQueryResponse.messages || !storeQueryResponse.messages.length) {\n log.warn(\"Stopping pagination due to empty messages in response\");\n break;\n }\n log.info(`${storeQueryResponse.messages.length} messages retrieved from store`);\n const decodedMessages = storeQueryResponse.messages.map((protoMsg) => {\n if (!protoMsg.message) {\n return Promise.resolve(undefined);\n }\n const contentTopic = protoMsg.message.contentTopic;\n if (contentTopic) {\n const decoder = decoders.get(contentTopic);\n if (decoder) {\n return decoder.fromProtoObj(protoMsg.pubsubTopic || \"\", toProtoMessage(protoMsg.message));\n }\n }\n return Promise.resolve(undefined);\n });\n yield decodedMessages;\n if (queryOpts.paginationForward) {\n currentCursor =\n storeQueryResponse.messages[storeQueryResponse.messages.length - 1]\n .messageHash;\n }\n else {\n currentCursor = storeQueryResponse.messages[0].messageHash;\n }\n if (storeQueryResponse.messages.length > MAX_PAGE_SIZE &&\n storeQueryResponse.messages.length <\n (queryOpts.paginationLimit || DEFAULT_PAGE_SIZE)) {\n break;\n }\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { setMaxListeners } from './events.js';\n/**\n * An implementation of a typed event target\n * etc\n */\nexport class TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nexport const CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map","import { Logger, pubsubTopicToSingleShardInfo } from \"@waku/utils\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport { createEncoder } from \"./message/version_0.js\";\nexport const RelayPingContentTopic = \"/relay-ping/1/ping/null\";\nconst log = new Logger(\"keep-alive\");\nexport class KeepAliveManager {\n relay;\n libp2p;\n options;\n pingKeepAliveTimers = new Map();\n relayKeepAliveTimers = new Map();\n constructor({ options, relay, libp2p }) {\n this.options = options;\n this.relay = relay;\n this.libp2p = libp2p;\n }\n start(peerId) {\n // Just in case a timer already exists for this peer\n this.stop(peerId);\n const { pingKeepAlive: pingPeriodSecs, relayKeepAlive: relayPeriodSecs } = this.options;\n const peerIdStr = peerId.toString();\n // Ping the peer every pingPeriodSecs seconds\n // if pingPeriodSecs is 0, don't ping the peer\n if (pingPeriodSecs !== 0) {\n const interval = setInterval(() => {\n void (async () => {\n let ping;\n try {\n // ping the peer for keep alive\n // also update the peer store with the latency\n try {\n ping = await this.libp2p.services.ping.ping(peerId);\n log.info(`Ping succeeded (${peerIdStr})`, ping);\n }\n catch (error) {\n log.error(`Ping failed for peer (${peerIdStr}).\n Next ping will be attempted in ${pingPeriodSecs} seconds.\n `);\n return;\n }\n try {\n await this.libp2p.peerStore.merge(peerId, {\n metadata: {\n ping: utf8ToBytes(ping.toString())\n }\n });\n }\n catch (e) {\n log.error(\"Failed to update ping\", e);\n }\n }\n catch (e) {\n log.error(`Ping failed (${peerIdStr})`, e);\n }\n })();\n }, pingPeriodSecs * 1000);\n this.pingKeepAliveTimers.set(peerIdStr, interval);\n }\n const relay = this.relay;\n if (relay && relayPeriodSecs !== 0) {\n const intervals = this.scheduleRelayPings(relay, relayPeriodSecs, peerId.toString());\n this.relayKeepAliveTimers.set(peerId, intervals);\n }\n }\n stop(peerId) {\n const peerIdStr = peerId.toString();\n if (this.pingKeepAliveTimers.has(peerIdStr)) {\n clearInterval(this.pingKeepAliveTimers.get(peerIdStr));\n this.pingKeepAliveTimers.delete(peerIdStr);\n }\n if (this.relayKeepAliveTimers.has(peerId)) {\n this.relayKeepAliveTimers.get(peerId)?.map(clearInterval);\n this.relayKeepAliveTimers.delete(peerId);\n }\n }\n stopAll() {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers)\n ]) {\n clearInterval(timer);\n }\n this.pingKeepAliveTimers.clear();\n this.relayKeepAliveTimers.clear();\n }\n connectionsExist() {\n return (this.pingKeepAliveTimers.size > 0 || this.relayKeepAliveTimers.size > 0);\n }\n scheduleRelayPings(relay, relayPeriodSecs, peerIdStr) {\n // send a ping message to each PubsubTopic the peer is part of\n const intervals = [];\n for (const topic of relay.pubsubTopics) {\n const meshPeers = relay.getMeshPeers(topic);\n if (!meshPeers.includes(peerIdStr))\n continue;\n const encoder = createEncoder({\n pubsubTopicShardInfo: pubsubTopicToSingleShardInfo(topic),\n contentTopic: RelayPingContentTopic,\n ephemeral: true\n });\n const interval = setInterval(() => {\n log.info(\"Sending Waku Relay ping message\");\n relay\n .send(encoder, { payload: new Uint8Array([1]) })\n .catch((e) => log.error(\"Failed to send relay ping\", e));\n }, relayPeriodSecs * 1000);\n intervals.push(interval);\n }\n return intervals;\n }\n}\n//# sourceMappingURL=keep_alive_manager.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { DNS_DISCOVERY_TAG, EConnectionStateEvents, EPeersByDiscoveryEvents } from \"@waku/interfaces\";\nimport { Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport { KeepAliveManager } from \"./keep_alive_manager.js\";\nconst log = new Logger(\"connection-manager\");\nexport const DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;\nexport const DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;\nexport const DEFAULT_MAX_PARALLEL_DIALS = 3;\nexport class ConnectionManager extends TypedEventEmitter {\n configuredPubsubTopics;\n static instances = new Map();\n keepAliveManager;\n options;\n libp2p;\n dialAttemptsForPeer = new Map();\n dialErrorsForPeer = new Map();\n currentActiveParallelDialCount = 0;\n pendingPeerDialQueue = [];\n isP2PNetworkConnected = false;\n isConnected() {\n if (globalThis?.navigator && !globalThis?.navigator?.onLine) {\n return false;\n }\n return this.isP2PNetworkConnected;\n }\n static create(peerId, libp2p, keepAliveOptions, pubsubTopics, relay, options) {\n let instance = ConnectionManager.instances.get(peerId);\n if (!instance) {\n instance = new ConnectionManager(libp2p, keepAliveOptions, pubsubTopics, relay, options);\n ConnectionManager.instances.set(peerId, instance);\n }\n return instance;\n }\n stop() {\n this.keepAliveManager.stopAll();\n this.libp2p.removeEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n this.libp2p.removeEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n this.libp2p.removeEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n this.stopNetworkStatusListener();\n }\n async dropConnection(peerId) {\n try {\n this.keepAliveManager.stop(peerId);\n await this.libp2p.hangUp(peerId);\n log.info(`Dropped connection with peer ${peerId.toString()}`);\n }\n catch (error) {\n log.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);\n }\n }\n async getPeersByDiscovery() {\n const peersDiscovered = await this.libp2p.peerStore.all();\n const peersConnected = this.libp2p\n .getConnections()\n .map((conn) => conn.remotePeer);\n const peersDiscoveredByBootstrap = [];\n const peersDiscoveredByPeerExchange = [];\n const peersDiscoveredByLocal = [];\n const peersConnectedByBootstrap = [];\n const peersConnectedByPeerExchange = [];\n const peersConnectedByLocal = [];\n for (const peer of peersDiscovered) {\n const tags = await this.getTagNamesForPeer(peer.id);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersDiscoveredByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersDiscoveredByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersDiscoveredByLocal.push(peer);\n }\n }\n for (const peerId of peersConnected) {\n const peer = await this.libp2p.peerStore.get(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersConnectedByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersConnectedByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersConnectedByLocal.push(peer);\n }\n }\n return {\n DISCOVERED: {\n [Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,\n [Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,\n [Tags.LOCAL]: peersDiscoveredByLocal\n },\n CONNECTED: {\n [Tags.BOOTSTRAP]: peersConnectedByBootstrap,\n [Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,\n [Tags.LOCAL]: peersConnectedByLocal\n }\n };\n }\n constructor(libp2p, keepAliveOptions, configuredPubsubTopics, relay, options) {\n super();\n this.configuredPubsubTopics = configuredPubsubTopics;\n this.libp2p = libp2p;\n this.configuredPubsubTopics = configuredPubsubTopics;\n this.options = {\n maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,\n maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,\n maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,\n ...options\n };\n this.keepAliveManager = new KeepAliveManager({\n relay,\n libp2p,\n options: keepAliveOptions\n });\n this.startEventListeners()\n .then(() => log.info(`Connection Manager is now running`))\n .catch((error) => log.error(`Unexpected error while running service`, error));\n // libp2p emits `peer:discovery` events during its initialization\n // which means that before the ConnectionManager is initialized, some peers may have been discovered\n // we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager\n this.dialPeerStorePeers().catch((error) => log.error(`Unexpected error while dialing peer store peers`, error));\n }\n async dialPeerStorePeers() {\n const peerInfos = await this.libp2p.peerStore.all();\n const dialPromises = [];\n for (const peerInfo of peerInfos) {\n if (this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id))\n continue;\n dialPromises.push(this.attemptDial(peerInfo.id));\n }\n try {\n await Promise.all(dialPromises);\n }\n catch (error) {\n log.error(`Unexpected error while dialing peer store peers`, error);\n }\n }\n async startEventListeners() {\n this.startPeerDiscoveryListener();\n this.startPeerConnectionListener();\n this.startPeerDisconnectionListener();\n this.startNetworkStatusListener();\n }\n async dialPeer(peerId) {\n this.currentActiveParallelDialCount += 1;\n let dialAttempt = 0;\n while (dialAttempt < this.options.maxDialAttemptsForPeer) {\n try {\n log.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);\n await this.libp2p.dial(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n // add tag to connection describing discovery mechanism\n // don't add duplicate tags\n this.libp2p.getConnections(peerId).forEach((conn) => {\n conn.tags = Array.from(new Set([...conn.tags, ...tags]));\n });\n // instead of deleting the peer from the peer store, we set the dial attempt to -1\n // this helps us keep track of peers that have been dialed before\n this.dialAttemptsForPeer.set(peerId.toString(), -1);\n // Dialing succeeded, break the loop\n this.keepAliveManager.start(peerId);\n break;\n }\n catch (error) {\n if (error instanceof AggregateError) {\n // Handle AggregateError\n log.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);\n }\n else {\n // Handle generic error\n log.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);\n }\n this.dialErrorsForPeer.set(peerId.toString(), error);\n dialAttempt++;\n this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);\n }\n }\n // Always decrease the active dial count and process the dial queue\n this.currentActiveParallelDialCount--;\n this.processDialQueue();\n // If max dial attempts reached and dialing failed, delete the peer\n if (dialAttempt === this.options.maxDialAttemptsForPeer) {\n try {\n const error = this.dialErrorsForPeer.get(peerId.toString());\n if (error) {\n let errorMessage;\n if (error instanceof AggregateError) {\n if (!error.errors) {\n log.warn(`No errors array found for AggregateError`);\n }\n else if (error.errors.length === 0) {\n log.warn(`Errors array is empty for AggregateError`);\n }\n else {\n errorMessage = JSON.stringify(error.errors[0]);\n }\n }\n else {\n errorMessage = error.message;\n }\n log.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);\n }\n this.dialErrorsForPeer.delete(peerId.toString());\n await this.libp2p.peerStore.delete(peerId);\n // if it was last available peer - attempt DNS discovery\n await this.attemptDnsDiscovery();\n }\n catch (error) {\n throw new Error(`Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`);\n }\n }\n }\n async attemptDnsDiscovery() {\n if (this.libp2p.getConnections().length > 0)\n return;\n if ((await this.libp2p.peerStore.all()).length > 0)\n return;\n log.info(\"Attempting to trigger DNS discovery.\");\n const dnsDiscovery = Object.values(this.libp2p.components.components).find((v) => {\n if (v && v.toString) {\n return v.toString().includes(DNS_DISCOVERY_TAG);\n }\n return false;\n });\n if (!dnsDiscovery)\n return;\n await dnsDiscovery.findPeers();\n }\n processDialQueue() {\n if (this.pendingPeerDialQueue.length > 0 &&\n this.currentActiveParallelDialCount < this.options.maxParallelDials) {\n const peerId = this.pendingPeerDialQueue.shift();\n if (!peerId)\n return;\n this.attemptDial(peerId).catch((error) => {\n log.error(error);\n });\n }\n }\n startPeerDiscoveryListener() {\n this.libp2p.addEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n }\n startPeerConnectionListener() {\n this.libp2p.addEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n }\n startPeerDisconnectionListener() {\n // TODO: ensure that these following issues are updated and confirmed\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n this.libp2p.addEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n }\n async attemptDial(peerId) {\n if (!(await this.shouldDialPeer(peerId)))\n return;\n if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {\n this.pendingPeerDialQueue.push(peerId);\n return;\n }\n await this.dialPeer(peerId);\n }\n onEventHandlers = {\n \"peer:discovery\": (evt) => {\n void (async () => {\n const { id: peerId } = evt.detail;\n await this.dispatchDiscoveryEvent(peerId);\n try {\n await this.attemptDial(peerId);\n }\n catch (error) {\n log.error(`Error dialing peer ${peerId.toString()} : ${error}`);\n }\n })();\n },\n \"peer:connect\": (evt) => {\n void (async () => {\n log.info(`Connected to peer ${evt.detail.toString()}`);\n const peerId = evt.detail;\n this.keepAliveManager.start(peerId);\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n if (isBootstrap) {\n const bootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));\n // If we have too many bootstrap connections, drop one\n if (bootstrapConnections.length > this.options.maxBootstrapPeersAllowed) {\n await this.dropConnection(peerId);\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP, {\n detail: peerId\n }));\n }\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n this.setP2PNetworkConnected();\n })();\n },\n \"peer:disconnect\": (evt) => {\n void (async () => {\n this.keepAliveManager.stop(evt.detail);\n this.setP2PNetworkDisconnected();\n })();\n },\n \"browser:network\": () => {\n this.dispatchWakuConnectionEvent();\n }\n };\n /**\n * Checks if the peer should be dialed based on the following conditions:\n * 1. If the peer is already connected, don't dial\n * 2. If the peer is not part of any of the configured pubsub topics, don't dial\n * 3. If the peer is not dialable based on bootstrap status, don't dial\n * 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it\n * @returns true if the peer should be dialed, false otherwise\n */\n async shouldDialPeer(peerId) {\n const isConnected = this.libp2p.getConnections(peerId).length > 0;\n if (isConnected) {\n log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);\n return false;\n }\n const isSameShard = await this.isPeerTopicConfigured(peerId);\n if (!isSameShard) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n log.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.configuredPubsubTopics}).\n Not dialing.`);\n return false;\n }\n const isPreferredBasedOnBootstrap = await this.isPeerDialableBasedOnBootstrapStatus(peerId);\n if (!isPreferredBasedOnBootstrap) {\n log.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);\n return false;\n }\n const hasBeenDialed = this.dialAttemptsForPeer.has(peerId.toString());\n if (hasBeenDialed) {\n log.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);\n return false;\n }\n return true;\n }\n /**\n * Checks if the peer is dialable based on the following conditions:\n * 1. If the peer is a bootstrap peer, it is only dialable if the number of current bootstrap connections is less than the max allowed.\n * 2. If the peer is not a bootstrap peer\n */\n async isPeerDialableBasedOnBootstrapStatus(peerId) {\n const tagNames = await this.getTagNamesForPeer(peerId);\n const isBootstrap = tagNames.some((tagName) => tagName === Tags.BOOTSTRAP);\n if (!isBootstrap) {\n return true;\n }\n const currentBootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => {\n return conn.tags.find((name) => name === Tags.BOOTSTRAP);\n }).length;\n return currentBootstrapConnections < this.options.maxBootstrapPeersAllowed;\n }\n async dispatchDiscoveryEvent(peerId) {\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n this.dispatchEvent(new CustomEvent(isBootstrap\n ? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP\n : EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n /**\n * Fetches the tag names for a given peer\n */\n async getTagNamesForPeer(peerId) {\n try {\n const peer = await this.libp2p.peerStore.get(peerId);\n return Array.from(peer.tags.keys());\n }\n catch (error) {\n log.error(`Failed to get peer ${peerId}, error: ${error}`);\n return [];\n }\n }\n async isPeerTopicConfigured(peerId) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n // If there's no shard information, simply return true\n if (!shardInfo)\n return true;\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n const isTopicConfigured = pubsubTopics.some((topic) => this.configuredPubsubTopics.includes(topic));\n return isTopicConfigured;\n }\n async getPeerShardInfo(peerId, peerStore) {\n const peer = await peerStore.get(peerId);\n const shardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (!shardInfoBytes)\n return undefined;\n return decodeRelayShard(shardInfoBytes);\n }\n startNetworkStatusListener() {\n try {\n globalThis.addEventListener(\"online\", this.onEventHandlers[\"browser:network\"]);\n globalThis.addEventListener(\"offline\", this.onEventHandlers[\"browser:network\"]);\n }\n catch (err) {\n log.error(`Failed to start network listener: ${err}`);\n }\n }\n stopNetworkStatusListener() {\n try {\n globalThis.removeEventListener(\"online\", this.onEventHandlers[\"browser:network\"]);\n globalThis.removeEventListener(\"offline\", this.onEventHandlers[\"browser:network\"]);\n }\n catch (err) {\n log.error(`Failed to stop network listener: ${err}`);\n }\n }\n setP2PNetworkConnected() {\n if (!this.isP2PNetworkConnected) {\n this.isP2PNetworkConnected = true;\n this.dispatchWakuConnectionEvent();\n }\n }\n setP2PNetworkDisconnected() {\n if (this.isP2PNetworkConnected &&\n this.libp2p.getConnections().length === 0) {\n this.isP2PNetworkConnected = false;\n this.dispatchWakuConnectionEvent();\n }\n }\n dispatchWakuConnectionEvent() {\n this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.isConnected()\n }));\n }\n}\n//# sourceMappingURL=connection_manager.js.map","import { HealthStatus, Protocols } from \"@waku/interfaces\";\nclass HealthManager {\n static instance;\n health;\n constructor() {\n this.health = {\n overallStatus: HealthStatus.Unhealthy,\n protocolStatuses: new Map()\n };\n }\n static getInstance() {\n if (!HealthManager.instance) {\n HealthManager.instance = new HealthManager();\n }\n return HealthManager.instance;\n }\n getHealthStatus() {\n return this.health.overallStatus;\n }\n getProtocolStatus(protocol) {\n return this.health.protocolStatuses.get(protocol);\n }\n updateProtocolHealth(multicodec, connectedPeers) {\n const protocol = this.getNameFromMulticodec(multicodec);\n let status = HealthStatus.Unhealthy;\n if (connectedPeers == 1) {\n status = HealthStatus.MinimallyHealthy;\n }\n else if (connectedPeers >= 2) {\n status = HealthStatus.SufficientlyHealthy;\n }\n this.health.protocolStatuses.set(protocol, {\n name: protocol,\n status: status,\n lastUpdate: new Date()\n });\n this.updateOverallHealth();\n }\n getNameFromMulticodec(multicodec) {\n let name;\n if (multicodec.includes(\"filter\")) {\n name = Protocols.Filter;\n }\n else if (multicodec.includes(\"lightpush\")) {\n name = Protocols.LightPush;\n }\n else if (multicodec.includes(\"store\")) {\n name = Protocols.Store;\n }\n else {\n throw new Error(`Unknown protocol: ${multicodec}`);\n }\n return name;\n }\n updateOverallHealth() {\n const relevantProtocols = [Protocols.LightPush, Protocols.Filter];\n const statuses = relevantProtocols.map((p) => this.getProtocolStatus(p)?.status);\n if (statuses.some((status) => status === HealthStatus.Unhealthy)) {\n this.health.overallStatus = HealthStatus.Unhealthy;\n }\n else if (statuses.some((status) => status === HealthStatus.MinimallyHealthy)) {\n this.health.overallStatus = HealthStatus.MinimallyHealthy;\n }\n else {\n this.health.overallStatus = HealthStatus.SufficientlyHealthy;\n }\n }\n}\nexport const getHealthManager = () => HealthManager.getInstance();\n//# sourceMappingURL=health_manager.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { proto_metadata } from \"@waku/proto\";\nimport { encodeRelayShard, Logger, pubsubTopicsToShardInfo } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nconst log = new Logger(\"metadata\");\nexport const MetadataCodec = \"/vac/waku/metadata/1.0.0\";\nclass Metadata extends BaseProtocol {\n pubsubTopics;\n libp2pComponents;\n handshakesConfirmed = new Map();\n constructor(pubsubTopics, libp2p) {\n super(MetadataCodec, libp2p.components, log, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n this.libp2pComponents = libp2p;\n void libp2p.registrar.handle(MetadataCodec, (streamData) => {\n void this.onRequest(streamData);\n });\n }\n /**\n * Make a metadata query to a peer\n */\n async query(peerId) {\n const request = proto_metadata.WakuMetadataRequest.encode(pubsubTopicsToShardInfo(this.pubsubTopics));\n const peer = await this.libp2pComponents.peerStore.get(peerId);\n if (!peer) {\n return {\n shardInfo: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n shardInfo: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const encodedResponse = await pipe([request], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return {\n shardInfo: null,\n error\n };\n }\n await this.savePeerShardInfo(peerId, shardInfo);\n return {\n shardInfo,\n error: null\n };\n }\n async confirmOrAttemptHandshake(peerId) {\n const shardInfo = this.handshakesConfirmed.get(peerId.toString());\n if (shardInfo) {\n return {\n shardInfo,\n error: null\n };\n }\n return await this.query(peerId);\n }\n /**\n * Handle an incoming metadata request\n */\n async onRequest(streamData) {\n try {\n const { stream, connection } = streamData;\n const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode(pubsubTopicsToShardInfo(this.pubsubTopics));\n const encodedResponse = await pipe([encodedShardInfo], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return;\n }\n await this.savePeerShardInfo(connection.remotePeer, shardInfo);\n }\n catch (error) {\n log.error(\"Error handling metadata request\", error);\n }\n }\n decodeMetadataResponse(encodedResponse) {\n const bytes = new Uint8ArrayList();\n encodedResponse.forEach((chunk) => {\n bytes.append(chunk);\n });\n const response = proto_metadata.WakuMetadataResponse.decode(bytes);\n if (!response) {\n log.error(\"Error decoding metadata response\");\n return {\n shardInfo: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n return {\n shardInfo: response,\n error: null\n };\n }\n async savePeerShardInfo(peerId, shardInfo) {\n // add or update the shardInfo to peer store\n await this.libp2pComponents.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n this.handshakesConfirmed.set(peerId.toString(), shardInfo);\n }\n}\nexport function wakuMetadata(pubsubTopics) {\n return (components) => new Metadata(pubsubTopics, components);\n}\n//# sourceMappingURL=index.js.map","export const peerIdSymbol = Symbol.for('@libp2p/peer-id');\nexport function isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map","import { Parser } from \"./parser.js\";\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\nconst parser = new Parser();\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input) {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPAddr());\n}\n//# sourceMappingURL=parse.js.map","/* eslint-disable @typescript-eslint/no-unsafe-return */\nexport class Parser {\n index = 0;\n input = \"\";\n new(input) {\n this.index = 0;\n this.input = input;\n return this;\n }\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically(fn) {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith(fn) {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n /** Peek the next character from the input */\n peekChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n /** Read the next character from the input */\n readChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target) {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator(sep, index, inner) {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n if (digitCount === 0) {\n return undefined;\n }\n else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n }\n else {\n return result;\n }\n });\n }\n /** Read an IPv4 address. */\n readIPv4Addr() {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n return out;\n });\n }\n /** Read an IPv6 Address. */\n readIPv6Addr() {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups) => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n return [ix + 4, true];\n }\n }\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n if (headSize === 16) {\n return head;\n }\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n return head;\n });\n }\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr() {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n//# sourceMappingURL=parser.js.map","import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n/** Check if `input` is IPv4. */\nexport function isIPv4(input) {\n return Boolean(parseIPv4(input));\n}\n/** Check if `input` is IPv6. */\nexport function isIPv6(input) {\n return Boolean(parseIPv6(input));\n}\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input) {\n return Boolean(parseIP(input));\n}\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input) {\n if (isIPv4(input)) {\n return 4;\n }\n else if (isIPv6(input)) {\n return 6;\n }\n else {\n return undefined;\n }\n}\n//# sourceMappingURL=is-ip.js.map","import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\nexport const maxIPv6Octet = parseInt(\"0xFFFF\", 16);\nexport const ipv4Prefix = new Uint8Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255,\n]);\nexport function maskIp(ip, mask) {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)) {\n ip = ip.slice(12);\n }\n const n = ip.length;\n if (n != mask.length) {\n throw new Error(\"Failed to mask ip\");\n }\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n out[i] = ip[i] & mask[i];\n }\n return out;\n}\nexport function containsIp(net, ip) {\n if (typeof ip === \"string\") {\n ip = parseIP(ip);\n }\n if (ip == null)\n throw new Error(\"Invalid ip\");\n if (ip.length !== net.network.length) {\n return false;\n }\n for (let i = 0; i < ip.length; i++) {\n if ((net.network[i] & net.mask[i]) !== (ip[i] & net.mask[i])) {\n return false;\n }\n }\n return true;\n}\nexport function iPv4FromIPv6(ip) {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\nexport function isIPv4mappedIPv6(ip) {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n//# sourceMappingURL=ip.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nexport { isIP } from '@chainsafe/is-ip';\nexport const isV4 = isIPv4;\nexport const isV6 = isIPv6;\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip) {\n let offset = 0;\n ip = ip.toString().trim();\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4);\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff;\n });\n return bytes;\n }\n if (isV6(ip)) {\n const sections = ip.split(':', 8);\n let i;\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i]);\n let v4Buffer;\n if (isv4) {\n v4Buffer = toBytes(sections[i]);\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16');\n }\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'));\n }\n }\n if (sections[0] === '') {\n while (sections.length < 8)\n sections.unshift('0');\n }\n else if (sections[sections.length - 1] === '') {\n while (sections.length < 8)\n sections.push('0');\n }\n else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++)\n ;\n const argv = [i, 1];\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0');\n }\n sections.splice.apply(sections, argv);\n }\n const bytes = new Uint8Array(offset + 16);\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16);\n bytes[offset++] = (word >> 8) & 0xff;\n bytes[offset++] = word & 0xff;\n }\n return bytes;\n }\n throw new Error('invalid ip address');\n};\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf, offset = 0, length) {\n offset = ~~offset;\n length = length ?? (buf.length - offset);\n const view = new DataView(buf.buffer);\n if (length === 4) {\n const result = [];\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i]);\n }\n return result.join('.');\n }\n if (length === 16) {\n const result = [];\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16));\n }\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::');\n }\n return '';\n};\n//# sourceMappingURL=ip.js.map","const V = -1;\nexport const names = {};\nexport const codes = {};\nexport const table = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [481, V, 'http-path'],\n [777, V, 'memory']\n];\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row);\n codes[proto.code] = proto;\n names[proto.name] = proto;\n});\nexport function createProtocol(code, size, name, resolvable, path) {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n };\n}\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol(proto) {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto];\n }\n throw new Error(`no protocol with code: ${proto}`);\n }\n else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto];\n }\n throw new Error(`no protocol with name: ${proto}`);\n }\n throw new Error(`invalid protocol id type: ${typeof proto}`);\n}\n//# sourceMappingURL=protocols-table.js.map","/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\nimport { IpNet } from '@chainsafe/netmask';\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { bases } from 'multiformats/basics';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport * as ip from './ip.js';\nimport { getProtocol } from './protocols-table.js';\nconst ip4Protocol = getProtocol('ip4');\nconst ip6Protocol = getProtocol('ip6');\nconst ipcidrProtocol = getProtocol('ipcidr');\nexport function convert(proto, a) {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a);\n }\n else {\n return convertToBytes(proto, a);\n }\n}\n/**\n * Convert [code,Uint8Array] to string\n */\nexport function convertToString(proto, buf) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf);\n case 42: // ipv6zone\n return bytes2str(buf);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString();\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf);\n case 421: // ipfs\n return bytes2mh(buf);\n case 444: // onion\n return bytes2onion(buf);\n case 445: // onion3\n return bytes2onion(buf);\n case 466: // certhash\n return bytes2mb(buf);\n case 481: // http-path\n return globalThis.encodeURIComponent(bytes2str(buf));\n default:\n return uint8ArrayToString(buf, 'base16'); // no clue. convert to hex\n }\n}\nexport function convertToBytes(proto, str) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str);\n case 41: // ipv6\n return ip2bytes(str);\n case 42: // ipv6zone\n return str2bytes(str);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10));\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str);\n case 421: // ipfs\n return mh2bytes(str);\n case 444: // onion\n return onion2bytes(str);\n case 445: // onion3\n return onion32bytes(str);\n case 466: // certhash\n return mb2bytes(str);\n case 481: // http-path\n return str2bytes(globalThis.decodeURIComponent(str));\n default:\n return uint8ArrayFromString(str, 'base16'); // no clue. convert from hex\n }\n}\nexport function convertToIpNet(multiaddr) {\n let mask;\n let addr;\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value;\n }\n if (code === ipcidrProtocol.code) {\n mask = value;\n }\n });\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr');\n }\n return new IpNet(addr, mask);\n}\nconst decoders = Object.values(bases).map((c) => c.decoder);\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1]);\n decoders.slice(2).forEach((d) => (acc = acc.or(d)));\n return acc;\n})();\nfunction ip2bytes(ipString) {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ip.toBytes(ipString);\n}\nfunction bytes2ip(ipBuff) {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length);\n if (ipString == null) {\n throw new Error('ipBuff is required');\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ipString;\n}\nfunction port2bytes(port) {\n const buf = new ArrayBuffer(2);\n const view = new DataView(buf);\n view.setUint16(0, port);\n return new Uint8Array(buf);\n}\nfunction bytes2port(buf) {\n const view = new DataView(buf.buffer);\n return view.getUint16(buf.byteOffset);\n}\nfunction str2bytes(str) {\n const buf = uint8ArrayFromString(str);\n const size = Uint8Array.from(varint.encode(buf.length));\n return uint8ArrayConcat([size, buf], size.length + buf.length);\n}\nfunction bytes2str(buf) {\n const size = varint.decode(buf);\n buf = buf.slice(varint.encodingLength(size));\n if (buf.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(buf);\n}\nfunction mh2bytes(hash) {\n let mh;\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes;\n }\n else {\n mh = CID.parse(hash).multihash.bytes;\n }\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length));\n return uint8ArrayConcat([size, mh], size.length + mh.length);\n}\nfunction mb2bytes(mbstr) {\n const mb = anybaseDecoder.decode(mbstr);\n const size = Uint8Array.from(varint.encode(mb.length));\n return uint8ArrayConcat([size, mb], size.length + mb.length);\n}\nfunction bytes2mb(buf) {\n const size = varint.decode(buf);\n const hash = buf.slice(varint.encodingLength(size));\n if (hash.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return 'u' + uint8ArrayToString(hash, 'base64url');\n}\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh(buf) {\n const size = varint.decode(buf);\n const address = buf.slice(varint.encodingLength(size));\n if (address.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(address, 'base58btc');\n}\nfunction onion2bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0]);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction onion32bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction bytes2onion(buf) {\n const addrBytes = buf.slice(0, buf.length - 2);\n const portBytes = buf.slice(buf.length - 2);\n const addr = uint8ArrayToString(addrBytes, 'base32');\n const port = bytes2port(portBytes);\n return `${addr}:${port}`;\n}\n//# sourceMappingURL=convert.js.map","import * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { convertToBytes, convertToString } from './convert.js';\nimport { getProtocol } from './protocols-table.js';\nexport function stringToMultiaddrParts(str) {\n str = cleanPath(str);\n const tuples = [];\n const stringTuples = [];\n let path = null;\n const parts = str.split('/').slice(1);\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n };\n }\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p];\n const proto = getProtocol(part);\n if (proto.size === 0) {\n tuples.push([proto.code]);\n stringTuples.push([proto.code]);\n // eslint-disable-next-line no-continue\n continue;\n }\n p++; // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str);\n }\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'));\n tuples.push([proto.code, convertToBytes(proto.code, path)]);\n stringTuples.push([proto.code, path]);\n break;\n }\n const bytes = convertToBytes(proto.code, parts[p]);\n tuples.push([proto.code, bytes]);\n stringTuples.push([proto.code, convertToString(proto.code, bytes)]);\n }\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n };\n}\nexport function bytesToMultiaddrParts(bytes) {\n const tuples = [];\n const stringTuples = [];\n let path = null;\n let i = 0;\n while (i < bytes.length) {\n const code = varint.decode(bytes, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, bytes.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n stringTuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = bytes.slice(i + n, i + n + size);\n i += (size + n);\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n const stringAddr = convertToString(code, addr);\n stringTuples.push([code, stringAddr]);\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr;\n break;\n }\n }\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n };\n}\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString(tuples) {\n const parts = [];\n tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n parts.push(proto.name);\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1]);\n }\n return null;\n });\n return cleanPath(parts.join('/'));\n}\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes(tuples) {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n let buf = Uint8Array.from(varint.encode(proto.code));\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]); // add address buffer\n }\n return buf;\n }));\n}\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr(p, addr) {\n if (p.size > 0) {\n return p.size / 8;\n }\n else if (p.size === 0) {\n return 0;\n }\n else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));\n return size + varint.encodingLength(size);\n }\n}\nexport function bytesToTuples(buf) {\n const tuples = [];\n let i = 0;\n while (i < buf.length) {\n const code = varint.decode(buf, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, buf.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = buf.slice(i + n, i + n + size);\n i += (size + n);\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n }\n return tuples;\n}\nexport function cleanPath(str) {\n return '/' + str.trim().split('/').filter((a) => a).join('/');\n}\nexport function ParseError(str) {\n return new Error('Error parsing address: ' + str);\n}\n//# sourceMappingURL=codec.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\nimport { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, tuplesToBytes } from './codec.js';\nimport { getProtocol, names } from './protocols-table.js';\nimport { isMultiaddr, multiaddr, resolvers } from './index.js';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n];\nclass NoAvailableResolverError extends Error {\n constructor(message = 'No available resolver') {\n super(message);\n this.name = 'NoAvailableResolverError';\n }\n}\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr {\n bytes;\n #string;\n #tuples;\n #stringTuples;\n #path;\n [symbol] = true;\n constructor(addr) {\n // default\n if (addr == null) {\n addr = '';\n }\n let parts;\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr);\n }\n else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`);\n }\n parts = stringToMultiaddrParts(addr);\n }\n else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes);\n }\n else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr');\n }\n this.bytes = parts.bytes;\n this.#string = parts.string;\n this.#tuples = parts.tuples;\n this.#stringTuples = parts.stringTuples;\n this.#path = parts.path;\n }\n toString() {\n return this.#string;\n }\n toJSON() {\n return this.toString();\n }\n toOptions() {\n let family;\n let transport;\n let host;\n let port;\n let zone = '';\n const tcp = getProtocol('tcp');\n const udp = getProtocol('udp');\n const ip4 = getProtocol('ip4');\n const ip6 = getProtocol('ip6');\n const dns6 = getProtocol('dns6');\n const ip6zone = getProtocol('ip6zone');\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`;\n }\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name;\n port = 443;\n host = `${value ?? ''}${zone}`;\n family = code === dns6.code ? 6 : 4;\n }\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name;\n port = parseInt(value ?? '');\n }\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name;\n host = `${value ?? ''}${zone}`;\n family = code === ip6.code ? 6 : 4;\n }\n }\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".');\n }\n const opts = {\n family,\n host,\n transport,\n port\n };\n return opts;\n }\n protos() {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)));\n }\n protoCodes() {\n return this.#tuples.map(([code]) => code);\n }\n protoNames() {\n return this.#tuples.map(([code]) => getProtocol(code).name);\n }\n tuples() {\n return this.#tuples;\n }\n stringTuples() {\n return this.#stringTuples;\n }\n encapsulate(addr) {\n addr = new Multiaddr(addr);\n return new Multiaddr(this.toString() + addr.toString());\n }\n decapsulate(addr) {\n const addrString = addr.toString();\n const s = this.toString();\n const i = s.lastIndexOf(addrString);\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);\n }\n return new Multiaddr(s.slice(0, i));\n }\n decapsulateCode(code) {\n const tuples = this.tuples();\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)));\n }\n }\n return this;\n }\n getPeerId() {\n try {\n let tuples = [];\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name]);\n }\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = [];\n }\n });\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop();\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1];\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc');\n }\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc');\n }\n return null;\n }\n catch (e) {\n return null;\n }\n }\n getPath() {\n return this.#path;\n }\n equals(addr) {\n return uint8ArrayEquals(this.bytes, addr.bytes);\n }\n async resolve(options) {\n const resolvableProto = this.protos().find((p) => p.resolvable);\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this];\n }\n const resolver = resolvers.get(resolvableProto.name);\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);\n }\n const result = await resolver(this, options);\n return result.map(str => multiaddr(str));\n }\n nodeAddress() {\n const options = this.toOptions();\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`);\n }\n return {\n family: options.family,\n address: options.host,\n port: options.port\n };\n }\n isThinWaistAddress(addr) {\n const protos = (addr ?? this).protos();\n if (protos.length !== 2) {\n return false;\n }\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false;\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false;\n }\n return true;\n }\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect]() {\n return `Multiaddr(${this.#string})`;\n }\n}\n//# sourceMappingURL=multiaddr.js.map","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js';\nimport { getProtocol } from './protocols-table.js';\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map();\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js';\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress(addr, transport) {\n if (addr == null) {\n throw new Error('requires node address object');\n }\n if (transport == null) {\n throw new Error('requires transport protocol');\n }\n let ip;\n let host = addr.address;\n switch (addr.family) {\n case 4:\n ip = 'ip4';\n break;\n case 6:\n ip = 'ip6';\n if (host.includes('%')) {\n const parts = host.split('%');\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr');\n }\n host = parts[0];\n const zone = parts[1];\n ip = `/ip6zone/${zone}/ip6`;\n }\n break;\n default:\n throw Error('Invalid addr family, should be 4 or 6.');\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'));\n}\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName(addr) {\n if (!isMultiaddr(addr)) {\n return false;\n }\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable);\n}\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr(value) {\n return Boolean(value?.[symbol]);\n}\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr(addr) {\n return new MultiaddrClass(addr);\n}\nexport { getProtocol as protocols };\n//# sourceMappingURL=index.js.map","const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nconst E_ALREADY_LOCKED = new Error('mutex already locked');\nconst E_CANCELED = new Error('request for lock canceled');\n\nvar __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Semaphore {\n constructor(_value, _cancelError = E_CANCELED) {\n this._value = _value;\n this._cancelError = _cancelError;\n this._queue = [];\n this._weightedWaiters = [];\n }\n acquire(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n return new Promise((resolve, reject) => {\n const task = { resolve, reject, weight, priority };\n const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);\n if (i === -1 && weight <= this._value) {\n // Needs immediate dispatch, skip the queue\n this._dispatchItem(task);\n }\n else {\n this._queue.splice(i + 1, 0, task);\n }\n });\n }\n runExclusive(callback_1) {\n return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {\n const [value, release] = yield this.acquire(weight, priority);\n try {\n return yield callback(value);\n }\n finally {\n release();\n }\n });\n }\n waitForUnlock(weight = 1, priority = 0) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n if (this._couldLockImmediately(weight, priority)) {\n return Promise.resolve();\n }\n else {\n return new Promise((resolve) => {\n if (!this._weightedWaiters[weight - 1])\n this._weightedWaiters[weight - 1] = [];\n insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });\n });\n }\n }\n isLocked() {\n return this._value <= 0;\n }\n getValue() {\n return this._value;\n }\n setValue(value) {\n this._value = value;\n this._dispatchQueue();\n }\n release(weight = 1) {\n if (weight <= 0)\n throw new Error(`invalid weight ${weight}: must be positive`);\n this._value += weight;\n this._dispatchQueue();\n }\n cancel() {\n this._queue.forEach((entry) => entry.reject(this._cancelError));\n this._queue = [];\n }\n _dispatchQueue() {\n this._drainUnlockWaiters();\n while (this._queue.length > 0 && this._queue[0].weight <= this._value) {\n this._dispatchItem(this._queue.shift());\n this._drainUnlockWaiters();\n }\n }\n _dispatchItem(item) {\n const previousValue = this._value;\n this._value -= item.weight;\n item.resolve([previousValue, this._newReleaser(item.weight)]);\n }\n _newReleaser(weight) {\n let called = false;\n return () => {\n if (called)\n return;\n called = true;\n this.release(weight);\n };\n }\n _drainUnlockWaiters() {\n if (this._queue.length === 0) {\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n waiters.forEach((waiter) => waiter.resolve());\n this._weightedWaiters[weight - 1] = [];\n }\n }\n else {\n const queuedPriority = this._queue[0].priority;\n for (let weight = this._value; weight > 0; weight--) {\n const waiters = this._weightedWaiters[weight - 1];\n if (!waiters)\n continue;\n const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);\n (i === -1 ? waiters : waiters.splice(0, i))\n .forEach((waiter => waiter.resolve()));\n }\n }\n }\n _couldLockImmediately(weight, priority) {\n return (this._queue.length === 0 || this._queue[0].priority < priority) &&\n weight <= this._value;\n }\n}\nfunction insertSorted(a, v) {\n const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);\n a.splice(i + 1, 0, v);\n}\nfunction findIndexFromEnd(a, predicate) {\n for (let i = a.length - 1; i >= 0; i--) {\n if (predicate(a[i])) {\n return i;\n }\n }\n return -1;\n}\n\nvar __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nclass Mutex {\n constructor(cancelError) {\n this._semaphore = new Semaphore(1, cancelError);\n }\n acquire() {\n return __awaiter$1(this, arguments, void 0, function* (priority = 0) {\n const [, releaser] = yield this._semaphore.acquire(1, priority);\n return releaser;\n });\n }\n runExclusive(callback, priority = 0) {\n return this._semaphore.runExclusive(() => callback(), 1, priority);\n }\n isLocked() {\n return this._semaphore.isLocked();\n }\n waitForUnlock(priority = 0) {\n return this._semaphore.waitForUnlock(1, priority);\n }\n release() {\n if (this._semaphore.isLocked())\n this._semaphore.release();\n }\n cancel() {\n return this._semaphore.cancel();\n }\n}\n\nvar __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nfunction withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {\n return {\n acquire: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {\n let isTimeout = false;\n const handle = setTimeout(() => {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n try {\n const ticket = yield (isSemaphore(sync)\n ? sync.acquire(weight, priority)\n : sync.acquire(priority));\n if (isTimeout) {\n const release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n }\n catch (e) {\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e);\n }\n }\n }));\n },\n runExclusive(callback, weight, priority) {\n return __awaiter(this, void 0, void 0, function* () {\n let release = () => undefined;\n try {\n const ticket = yield this.acquire(weight, priority);\n if (Array.isArray(ticket)) {\n release = ticket[1];\n return yield callback(ticket[0]);\n }\n else {\n release = ticket;\n return yield callback();\n }\n }\n finally {\n release();\n }\n });\n },\n release(weight) {\n sync.release(weight);\n },\n cancel() {\n return sync.cancel();\n },\n waitForUnlock: (weightOrPriority, priority) => {\n let weight;\n if (isSemaphore(sync)) {\n weight = weightOrPriority;\n }\n else {\n weight = undefined;\n priority = weightOrPriority;\n }\n if (weight !== undefined && weight <= 0) {\n throw new Error(`invalid weight ${weight}: must be positive`);\n }\n return new Promise((resolve, reject) => {\n const handle = setTimeout(() => reject(timeoutError), timeout);\n (isSemaphore(sync)\n ? sync.waitForUnlock(weight, priority)\n : sync.waitForUnlock(priority)).then(() => {\n clearTimeout(handle);\n resolve();\n });\n });\n },\n isLocked: () => sync.isLocked(),\n getValue: () => sync.getValue(),\n setValue: (value) => sync.setValue(value),\n };\n}\nfunction isSemaphore(sync) {\n return sync.getValue !== undefined;\n}\n\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return withTimeout(sync, 0, alreadyAcquiredError);\n}\n\nexport { E_ALREADY_LOCKED, E_CANCELED, E_TIMEOUT, Mutex, Semaphore, tryAcquire, withTimeout };\n","import { getHealthManager } from \"@waku/core\";\nimport { Mutex } from \"async-mutex\";\nexport class PeerManager {\n connectionManager;\n core;\n log;\n peers = new Map();\n healthManager;\n readMutex = new Mutex();\n writeMutex = new Mutex();\n writeLockHolder = null;\n constructor(connectionManager, core, log) {\n this.connectionManager = connectionManager;\n this.core = core;\n this.log = log;\n this.healthManager = getHealthManager();\n this.healthManager.updateProtocolHealth(this.core.multicodec, 0);\n }\n getWriteLockHolder() {\n return this.writeLockHolder;\n }\n getPeers() {\n return Array.from(this.peers.values());\n }\n async addPeer(peer) {\n return this.writeMutex.runExclusive(async () => {\n this.writeLockHolder = `addPeer: ${peer.id.toString()}`;\n await this.connectionManager.attemptDial(peer.id);\n this.peers.set(peer.id.toString(), peer);\n this.log.info(`Added and dialed peer: ${peer.id.toString()}`);\n this.healthManager.updateProtocolHealth(this.core.multicodec, this.peers.size);\n this.writeLockHolder = null;\n });\n }\n async removePeer(peerId) {\n return this.writeMutex.runExclusive(() => {\n this.writeLockHolder = `removePeer: ${peerId.toString()}`;\n this.peers.delete(peerId.toString());\n this.log.info(`Removed peer: ${peerId.toString()}`);\n this.healthManager.updateProtocolHealth(this.core.multicodec, this.peers.size);\n this.writeLockHolder = null;\n });\n }\n async getPeerCount() {\n return this.readMutex.runExclusive(() => this.peers.size);\n }\n async hasPeers() {\n return this.readMutex.runExclusive(() => this.peers.size > 0);\n }\n async removeExcessPeers(excessPeers) {\n this.log.info(`Removing ${excessPeers} excess peer(s)`);\n const peersToRemove = Array.from(this.peers.values()).slice(0, excessPeers);\n for (const peer of peersToRemove) {\n await this.removePeer(peer.id);\n }\n }\n /**\n * Finds and adds new peers to the peers list.\n * @param numPeers The number of peers to find and add.\n */\n async findAndAddPeers(numPeers) {\n const additionalPeers = await this.findPeers(numPeers);\n if (additionalPeers.length === 0) {\n this.log.warn(\"No additional peers found\");\n return [];\n }\n return this.addMultiplePeers(additionalPeers);\n }\n /**\n * Finds additional peers.\n * @param numPeers The number of peers to find.\n */\n async findPeers(numPeers) {\n const connectedPeers = await this.core.getPeers();\n return this.readMutex.runExclusive(async () => {\n const newPeers = connectedPeers\n .filter((peer) => !this.peers.has(peer.id.toString()))\n .slice(0, numPeers);\n return newPeers;\n });\n }\n async addMultiplePeers(peers) {\n const addedPeers = [];\n for (const peer of peers) {\n await this.addPeer(peer);\n addedPeers.push(peer);\n }\n return addedPeers;\n }\n}\n//# sourceMappingURL=peer_manager.js.map","import { Logger } from \"@waku/utils\";\nimport { PeerManager } from \"./peer_manager.js\";\nexport const DEFAULT_NUM_PEERS_TO_USE = 2;\nconst DEFAULT_MAINTAIN_PEERS_INTERVAL = 30_000;\nexport class BaseProtocolSDK {\n core;\n connectionManager;\n peerManager;\n numPeersToUse;\n maintainPeersIntervalId = null;\n log;\n constructor(core, connectionManager, options) {\n this.core = core;\n this.connectionManager = connectionManager;\n this.log = new Logger(`sdk:${core.multicodec}`);\n this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS_TO_USE;\n const maintainPeersInterval = options?.maintainPeersInterval ?? DEFAULT_MAINTAIN_PEERS_INTERVAL;\n this.peerManager = new PeerManager(connectionManager, core, this.log);\n this.log.info(`Initializing BaseProtocolSDK with numPeersToUse: ${this.numPeersToUse}, maintainPeersInterval: ${maintainPeersInterval}ms`);\n void this.startMaintainPeersInterval(maintainPeersInterval);\n }\n get connectedPeers() {\n return this.peerManager.getPeers().slice(0, this.numPeersToUse);\n }\n /**\n * Disconnects from a peer and tries to find a new one to replace it.\n * @param peerToDisconnect The peer to disconnect from.\n * @returns The new peer that was found and connected to.\n */\n async renewPeer(peerToDisconnect) {\n this.log.info(`Attempting to renew peer ${peerToDisconnect}`);\n const newPeer = await this.peerManager.findPeers(1);\n if (newPeer.length === 0) {\n this.log.error(\"Failed to find a new peer to replace the disconnected one\");\n return undefined;\n }\n await this.peerManager.removePeer(peerToDisconnect);\n await this.peerManager.addPeer(newPeer[0]);\n this.log.info(`Successfully renewed peer. New peer: ${newPeer[0].id}`);\n return newPeer[0];\n }\n /**\n * Stops the maintain peers interval.\n */\n stopMaintainPeersInterval() {\n if (this.maintainPeersIntervalId) {\n clearInterval(this.maintainPeersIntervalId);\n this.maintainPeersIntervalId = null;\n this.log.info(\"Maintain peers interval stopped\");\n }\n else {\n this.log.info(\"Maintain peers interval was not running\");\n }\n }\n /**\n * Checks if there are sufficient peers to send a message to.\n * If `forceUseAllPeers` is `false` (default), returns `true` if there are any connected peers.\n * If `forceUseAllPeers` is `true`, attempts to connect to `numPeersToUse` peers.\n * @param options Optional options object\n * @param options.forceUseAllPeers Optional flag to force connecting to `numPeersToUse` peers (default: false)\n * @param options.maxAttempts Optional maximum number of attempts to reach the required number of peers (default: 3)\n * @returns `true` if the required number of peers are connected, `false` otherwise\n */\n async hasPeers(options = {}) {\n const { forceUseAllPeers = false, maxAttempts = 3 } = options;\n this.log.info(`Checking for peers. forceUseAllPeers: ${forceUseAllPeers}, maxAttempts: ${maxAttempts}`);\n for (let attempts = 0; attempts < maxAttempts; attempts++) {\n this.log.info(`Attempt ${attempts + 1}/${maxAttempts} to reach required number of peers`);\n await this.maintainPeers();\n if (!forceUseAllPeers && this.connectedPeers.length > 0) {\n this.log.info(`At least one peer connected (${this.connectedPeers.length}), not forcing use of all peers`);\n return true;\n }\n if (this.connectedPeers.length >= this.numPeersToUse) {\n this.log.info(`Required number of peers (${this.numPeersToUse}) reached`);\n return true;\n }\n this.log.warn(`Found only ${this.connectedPeers.length}/${this.numPeersToUse} required peers. Retrying...`);\n }\n this.log.error(`Failed to find required number of peers (${this.numPeersToUse}) after ${maxAttempts} attempts`);\n return false;\n }\n /**\n * Starts an interval to maintain the peers list to `numPeersToUse`.\n * @param interval The interval in milliseconds to maintain the peers.\n */\n async startMaintainPeersInterval(interval) {\n this.log.info(`Starting maintain peers interval with ${interval}ms interval`);\n try {\n this.maintainPeersIntervalId = setInterval(() => {\n this.log.info(\"Running scheduled peer maintenance\");\n this.maintainPeers().catch((error) => {\n this.log.error(\"Error during scheduled peer maintenance:\", error);\n });\n }, interval);\n this.log.info(\"Maintain peers interval started successfully\");\n }\n catch (error) {\n this.log.error(\"Error starting maintain peers interval:\", error);\n throw error;\n }\n }\n /**\n * Maintains the peers list to `numPeersToUse`.\n */\n async maintainPeers() {\n try {\n const currentPeerCount = await this.peerManager.getPeerCount();\n const numPeersToAdd = this.numPeersToUse - currentPeerCount;\n this.log.info(`Current peer count: ${currentPeerCount}, target: ${this.numPeersToUse}`);\n if (numPeersToAdd === 0) {\n this.log.info(\"Peer count is at target, no maintenance required\");\n return;\n }\n if (numPeersToAdd > 0) {\n this.log.info(`Attempting to add ${numPeersToAdd} peer(s)`);\n await this.peerManager.findAndAddPeers(numPeersToAdd);\n }\n else {\n this.log.info(`Attempting to remove ${Math.abs(numPeersToAdd)} excess peer(s)`);\n await this.peerManager.removeExcessPeers(Math.abs(numPeersToAdd));\n }\n const finalPeerCount = await this.peerManager.getPeerCount();\n this.log.info(`Peer maintenance completed. Initial count: ${currentPeerCount}, Final count: ${finalPeerCount}`);\n }\n catch (error) {\n this.log.error(\"Error during peer maintenance\", { error });\n }\n }\n}\n//# sourceMappingURL=base_protocol.js.map","export const DEFAULT_KEEP_ALIVE = 10_000;\nexport const DEFAULT_LIGHT_PUSH_FILTER_CHECK = false;\nexport const DEFAULT_LIGHT_PUSH_FILTER_CHECK_INTERVAL = 10_000;\nexport const DEFAULT_SUBSCRIBE_OPTIONS = {\n keepAlive: DEFAULT_KEEP_ALIVE,\n enableLightPushFilterCheck: DEFAULT_LIGHT_PUSH_FILTER_CHECK\n};\n//# sourceMappingURL=constants.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { isDefined } from \"@waku/utils\";\nimport { bytesToHex, concat, numberToBytes, utf8ToBytes } from \"@waku/utils/bytes\";\n/**\n * Deterministic Message Hashing as defined in\n * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)\n */\nexport function messageHash(pubsubTopic, message) {\n const pubsubTopicBytes = utf8ToBytes(pubsubTopic);\n const contentTopicBytes = utf8ToBytes(message.contentTopic);\n const timestampBytes = tryConvertTimestampToBytes(message.timestamp);\n const bytes = concat([\n pubsubTopicBytes,\n message.payload,\n contentTopicBytes,\n message.meta,\n timestampBytes\n ].filter(isDefined));\n return sha256(bytes);\n}\nfunction tryConvertTimestampToBytes(timestamp) {\n if (!timestamp) {\n return;\n }\n let bigIntTimestamp;\n if (typeof timestamp === \"bigint\") {\n bigIntTimestamp = timestamp;\n }\n else {\n bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;\n }\n return numberToBytes(bigIntTimestamp);\n}\nexport function messageHashStr(pubsubTopic, message) {\n const hash = messageHash(pubsubTopic, message);\n const hashStr = bytesToHex(hash);\n return hashStr;\n}\n//# sourceMappingURL=index.js.map","import { messageHashStr } from \"@waku/message-hash\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nconst log = new Logger(\"sdk:receiver:reliability_monitor\");\nconst DEFAULT_MAX_PINGS = 3;\nconst MESSAGE_VERIFICATION_DELAY = 5_000;\nexport class ReceiverReliabilityMonitor {\n pubsubTopic;\n getPeers;\n renewPeer;\n getContentTopics;\n protocolSubscribe;\n addLibp2pEventListener;\n sendLightPushMessage;\n receivedMessagesFormPeer = new Set();\n receivedMessages = new Set();\n scheduledVerification = new Map();\n verifiedPeers = new Set();\n peerFailures = new Map();\n maxPingFailures = DEFAULT_MAX_PINGS;\n peerRenewalLocks = new Set();\n constructor(pubsubTopic, getPeers, renewPeer, getContentTopics, protocolSubscribe, addLibp2pEventListener, sendLightPushMessage) {\n this.pubsubTopic = pubsubTopic;\n this.getPeers = getPeers;\n this.renewPeer = renewPeer;\n this.getContentTopics = getContentTopics;\n this.protocolSubscribe = protocolSubscribe;\n this.addLibp2pEventListener = addLibp2pEventListener;\n this.sendLightPushMessage = sendLightPushMessage;\n this.addLibp2pEventListener(\"peer:disconnect\", (evt) => {\n const peerId = evt.detail;\n if (this.getPeers().some((p) => p.id.equals(peerId))) {\n void this.renewAndSubscribePeer(peerId);\n }\n });\n }\n setMaxPingFailures(value) {\n if (value === undefined) {\n return;\n }\n this.maxPingFailures = value;\n }\n async handlePingResult(peerId, result) {\n if (result?.success) {\n this.peerFailures.delete(peerId.toString());\n return;\n }\n const failures = (this.peerFailures.get(peerId.toString()) || 0) + 1;\n this.peerFailures.set(peerId.toString(), failures);\n if (failures >= this.maxPingFailures) {\n try {\n log.info(`Attempting to renew ${peerId.toString()} due to ping failures.`);\n await this.renewAndSubscribePeer(peerId);\n this.peerFailures.delete(peerId.toString());\n }\n catch (error) {\n log.error(`Failed to renew peer ${peerId.toString()}: ${error}.`);\n }\n }\n }\n notifyMessageReceived(peerIdStr, message) {\n const hash = this.buildMessageHash(message);\n this.verifiedPeers.add(peerIdStr);\n this.receivedMessagesFormPeer.add(`${peerIdStr}-${hash}`);\n log.info(`notifyMessage received debug: ephemeral:${message.ephemeral}\\t${bytesToUtf8(message.payload)}`);\n log.info(`notifyMessage received: peer:${peerIdStr}\\tmessage:${hash}`);\n if (this.receivedMessages.has(hash)) {\n return true;\n }\n this.receivedMessages.add(hash);\n return false;\n }\n notifyMessageSent(peerId, message) {\n const peerIdStr = peerId.toString();\n const hash = this.buildMessageHash(message);\n log.info(`notifyMessage sent debug: ${bytesToUtf8(message.payload)}`);\n if (this.scheduledVerification.has(peerIdStr)) {\n log.warn(`notifyMessage sent: attempting to schedule verification for pending peer:${peerIdStr}\\tmessage:${hash}`);\n return;\n }\n const timeout = window.setTimeout((async () => {\n const receivedAnyMessage = this.verifiedPeers.has(peerIdStr);\n const receivedTestMessage = this.receivedMessagesFormPeer.has(`${peerIdStr}-${hash}`);\n if (receivedAnyMessage || receivedTestMessage) {\n log.info(`notifyMessage sent setTimeout: verified that peer pushes filter messages, peer:${peerIdStr}\\tmessage:${hash}`);\n return;\n }\n log.warn(`notifyMessage sent setTimeout: peer didn't return probe message, attempting renewAndSubscribe, peer:${peerIdStr}\\tmessage:${hash}`);\n this.scheduledVerification.delete(peerIdStr);\n await this.renewAndSubscribePeer(peerId);\n }), MESSAGE_VERIFICATION_DELAY);\n this.scheduledVerification.set(peerIdStr, timeout);\n }\n shouldVerifyPeer(peerId) {\n const peerIdStr = peerId.toString();\n const isPeerVerified = this.verifiedPeers.has(peerIdStr);\n const isVerificationPending = this.scheduledVerification.has(peerIdStr);\n return !(isPeerVerified || isVerificationPending);\n }\n buildMessageHash(message) {\n return messageHashStr(this.pubsubTopic, message);\n }\n async renewAndSubscribePeer(peerId) {\n const peerIdStr = peerId.toString();\n try {\n if (this.peerRenewalLocks.has(peerIdStr)) {\n log.info(`Peer ${peerIdStr} is already being renewed.`);\n return;\n }\n this.peerRenewalLocks.add(peerIdStr);\n const newPeer = await this.renewPeer(peerId);\n if (!newPeer) {\n log.warn(`Failed to renew peer ${peerIdStr}: No new peer found.`);\n return;\n }\n await this.protocolSubscribe(this.pubsubTopic, newPeer, this.getContentTopics());\n await this.sendLightPushMessage(newPeer);\n this.peerFailures.delete(peerIdStr);\n return newPeer;\n }\n catch (error) {\n log.error(`Failed to renew peer ${peerIdStr}: ${error}.`);\n return;\n }\n finally {\n this.peerRenewalLocks.delete(peerIdStr);\n }\n }\n}\n//# sourceMappingURL=receiver.js.map","import { ReceiverReliabilityMonitor } from \"./receiver.js\";\nexport class ReliabilityMonitorManager {\n static receiverMonitors = new Map();\n static createReceiverMonitor(pubsubTopic, getPeers, renewPeer, getContentTopics, protocolSubscribe, addLibp2pEventListener, sendLightPushMessage) {\n if (ReliabilityMonitorManager.receiverMonitors.has(pubsubTopic)) {\n return ReliabilityMonitorManager.receiverMonitors.get(pubsubTopic);\n }\n const monitor = new ReceiverReliabilityMonitor(pubsubTopic, getPeers, renewPeer, getContentTopics, protocolSubscribe, addLibp2pEventListener, sendLightPushMessage);\n ReliabilityMonitorManager.receiverMonitors.set(pubsubTopic, monitor);\n return monitor;\n }\n constructor() { }\n static stop(pubsubTopic) {\n this.receiverMonitors.delete(pubsubTopic);\n }\n static stopAll() {\n for (const [pubsubTopic, monitor] of this.receiverMonitors) {\n monitor.setMaxPingFailures(undefined);\n this.receiverMonitors.delete(pubsubTopic);\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { createDecoder, createEncoder } from \"@waku/core\";\nimport { EConnectionStateEvents, ProtocolError } from \"@waku/interfaces\";\nimport { groupByContentTopic, Logger } from \"@waku/utils\";\nimport { ReliabilityMonitorManager } from \"../../reliability_monitor/index.js\";\nimport { DEFAULT_KEEP_ALIVE, DEFAULT_LIGHT_PUSH_FILTER_CHECK, DEFAULT_LIGHT_PUSH_FILTER_CHECK_INTERVAL, DEFAULT_SUBSCRIBE_OPTIONS } from \"./constants.js\";\nconst log = new Logger(\"sdk:filter:subscription_manager\");\nexport class SubscriptionManager {\n pubsubTopic;\n protocol;\n connectionManager;\n getPeers;\n renewPeer;\n libp2p;\n lightPush;\n reliabilityMonitor;\n keepAliveTimeout = DEFAULT_KEEP_ALIVE;\n keepAliveInterval = null;\n enableLightPushFilterCheck = DEFAULT_LIGHT_PUSH_FILTER_CHECK;\n subscriptionCallbacks;\n constructor(pubsubTopic, protocol, connectionManager, getPeers, renewPeer, libp2p, lightPush) {\n this.pubsubTopic = pubsubTopic;\n this.protocol = protocol;\n this.connectionManager = connectionManager;\n this.getPeers = getPeers;\n this.renewPeer = renewPeer;\n this.libp2p = libp2p;\n this.lightPush = lightPush;\n this.pubsubTopic = pubsubTopic;\n this.subscriptionCallbacks = new Map();\n this.reliabilityMonitor = ReliabilityMonitorManager.createReceiverMonitor(this.pubsubTopic, this.getPeers.bind(this), this.renewPeer.bind(this), () => Array.from(this.subscriptionCallbacks.keys()), this.protocol.subscribe.bind(this.protocol), this.protocol.addLibp2pEventListener.bind(this.protocol), this.sendLightPushCheckMessage.bind(this));\n }\n async subscribe(decoders, callback, options = DEFAULT_SUBSCRIBE_OPTIONS) {\n this.reliabilityMonitor.setMaxPingFailures(options.pingsBeforePeerRenewed);\n this.keepAliveTimeout = options.keepAlive || DEFAULT_KEEP_ALIVE;\n this.enableLightPushFilterCheck =\n options?.enableLightPushFilterCheck || DEFAULT_LIGHT_PUSH_FILTER_CHECK;\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n // check that all decoders are configured for the same pubsub topic as this subscription\n for (const decoder of decodersArray) {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n return {\n failures: [\n {\n error: ProtocolError.TOPIC_DECODER_MISMATCH\n }\n ],\n successes: []\n };\n }\n }\n if (this.enableLightPushFilterCheck) {\n decodersArray.push(createDecoder(this.buildLightPushContentTopic(), this.pubsubTopic));\n }\n const decodersGroupedByCT = groupByContentTopic(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n const promises = this.getPeers().map(async (peer) => this.subscribeWithPeerVerification(peer, contentTopics));\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"subscribe\");\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n };\n // don't handle case of internal content topic\n if (contentTopic === this.buildLightPushContentTopic()) {\n return;\n }\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n this.startSubscriptionsMaintenance(this.keepAliveTimeout);\n return finalResult;\n }\n async unsubscribe(contentTopics) {\n const promises = this.getPeers().map(async (peer) => {\n const response = await this.protocol.unsubscribe(this.pubsubTopic, peer, contentTopics);\n contentTopics.forEach((contentTopic) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n return response;\n });\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"unsubscribe\");\n if (this.subscriptionCallbacks.size === 0) {\n this.stopSubscriptionsMaintenance();\n }\n return finalResult;\n }\n async ping(peerId) {\n log.info(\"Sending keep-alive ping\");\n const peers = peerId ? [peerId] : this.getPeers().map((peer) => peer.id);\n const promises = peers.map((peerId) => this.pingSpecificPeer(peerId));\n const results = await Promise.allSettled(promises);\n return this.handleResult(results, \"ping\");\n }\n async unsubscribeAll() {\n const promises = this.getPeers().map(async (peer) => this.protocol.unsubscribeAll(this.pubsubTopic, peer));\n const results = await Promise.allSettled(promises);\n this.subscriptionCallbacks.clear();\n const finalResult = this.handleResult(results, \"unsubscribeAll\");\n this.stopSubscriptionsMaintenance();\n return finalResult;\n }\n async processIncomingMessage(message, peerIdStr) {\n const alreadyReceived = this.reliabilityMonitor.notifyMessageReceived(peerIdStr, message);\n if (alreadyReceived) {\n log.info(\"Message already received, skipping\");\n return;\n }\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\"Processing message with content topic \", contentTopic, \" on pubsub topic \", this.pubsubTopic);\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n async subscribeWithPeerVerification(peer, contentTopics) {\n const result = await this.protocol.subscribe(this.pubsubTopic, peer, contentTopics);\n await this.sendLightPushCheckMessage(peer);\n return result;\n }\n handleResult(results, type) {\n const result = { failures: [], successes: [] };\n for (const promiseResult of results) {\n if (promiseResult.status === \"rejected\") {\n log.error(`Failed to resolve ${type} promise successfully: `, promiseResult.reason);\n result.failures.push({ error: ProtocolError.GENERIC_FAIL });\n }\n else {\n const coreResult = promiseResult.value;\n if (coreResult.failure) {\n result.failures.push(coreResult.failure);\n }\n else {\n result.successes.push(coreResult.success);\n }\n }\n }\n return result;\n }\n async pingSpecificPeer(peerId) {\n const peer = this.getPeers().find((p) => p.id.equals(peerId));\n if (!peer) {\n return {\n success: null,\n failure: {\n peerId,\n error: ProtocolError.NO_PEER_AVAILABLE\n }\n };\n }\n let result;\n try {\n result = await this.protocol.ping(peer);\n }\n catch (error) {\n result = {\n success: null,\n failure: {\n peerId,\n error: ProtocolError.GENERIC_FAIL\n }\n };\n }\n log.info(`Received result from filter ping peerId:${peerId.toString()}\\tsuccess:${result.success?.toString()}\\tfailure:${result.failure?.error}`);\n await this.reliabilityMonitor.handlePingResult(peerId, result);\n return result;\n }\n startSubscriptionsMaintenance(timeout) {\n log.info(\"Starting subscriptions maintenance\");\n this.startKeepAlivePings(timeout);\n this.startConnectionListener();\n }\n stopSubscriptionsMaintenance() {\n log.info(\"Stopping subscriptions maintenance\");\n this.stopKeepAlivePings();\n this.stopConnectionListener();\n }\n startConnectionListener() {\n this.connectionManager.addEventListener(EConnectionStateEvents.CONNECTION_STATUS, this.connectionListener.bind(this));\n }\n stopConnectionListener() {\n this.connectionManager.removeEventListener(EConnectionStateEvents.CONNECTION_STATUS, this.connectionListener.bind(this));\n }\n async connectionListener({ detail: isConnected }) {\n if (!isConnected) {\n this.stopKeepAlivePings();\n return;\n }\n try {\n // we do nothing here, as the renewal process is managed internally by `this.ping()`\n await this.ping();\n }\n catch (err) {\n log.error(`networkStateListener failed to recover: ${err}`);\n }\n this.startKeepAlivePings(this.keepAliveTimeout);\n }\n startKeepAlivePings(timeout) {\n if (this.keepAliveInterval) {\n log.info(\"Recurring pings already set up.\");\n return;\n }\n this.keepAliveInterval = setInterval(() => {\n void this.ping();\n }, timeout);\n }\n stopKeepAlivePings() {\n if (!this.keepAliveInterval) {\n log.info(\"Already stopped recurring pings.\");\n return;\n }\n log.info(\"Stopping recurring pings.\");\n clearInterval(this.keepAliveInterval);\n this.keepAliveInterval = null;\n }\n async sendLightPushCheckMessage(peer) {\n if (this.lightPush &&\n this.libp2p &&\n this.reliabilityMonitor.shouldVerifyPeer(peer.id)) {\n const encoder = createEncoder({\n contentTopic: this.buildLightPushContentTopic(),\n pubsubTopic: this.pubsubTopic,\n ephemeral: true\n });\n const message = { payload: new Uint8Array(1) };\n const protoMessage = await encoder.toProtoObj(message);\n // make a delay to be sure message is send when subscription is in place\n setTimeout((async () => {\n const result = await this.lightPush.protocol.send(encoder, message, peer);\n this.reliabilityMonitor.notifyMessageSent(peer.id, protoMessage);\n if (result.failure) {\n log.error(`failed to send lightPush ping message to peer:${peer.id.toString()}\\t${result.failure.error}`);\n return;\n }\n }), DEFAULT_LIGHT_PUSH_FILTER_CHECK_INTERVAL);\n }\n }\n buildLightPushContentTopic() {\n return `/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`;\n }\n}\nasync function pushMessage(subscriptionCallback, pubsubTopic, message) {\n const { decoders, callback } = subscriptionCallback;\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n try {\n const decodePromises = decoders.map((dec) => dec\n .fromProtoObj(pubsubTopic, message)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\")));\n const decodedMessage = await Promise.any(decodePromises);\n await callback(decodedMessage);\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n//# sourceMappingURL=subscription_manager.js.map","import { FilterCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, groupByContentTopic, Logger, shardInfoToPubsubTopics, toAsyncIterator } from \"@waku/utils\";\nimport { BaseProtocolSDK } from \"../base_protocol.js\";\nimport { DEFAULT_SUBSCRIBE_OPTIONS } from \"./constants.js\";\nimport { SubscriptionManager } from \"./subscription_manager.js\";\nconst log = new Logger(\"sdk:filter\");\nclass Filter extends BaseProtocolSDK {\n libp2p;\n lightPush;\n protocol;\n activeSubscriptions = new Map();\n constructor(connectionManager, libp2p, lightPush, options) {\n super(new FilterCore(async (pubsubTopic, wakuMessage, peerIdStr) => {\n const subscription = this.getActiveSubscription(pubsubTopic);\n if (!subscription) {\n log.error(`No subscription locally registered for topic ${pubsubTopic}`);\n return;\n }\n await subscription.processIncomingMessage(wakuMessage, peerIdStr);\n }, connectionManager.configuredPubsubTopics, libp2p), connectionManager, { numPeersToUse: options?.numPeersToUse });\n this.libp2p = libp2p;\n this.lightPush = lightPush;\n this.protocol = this.core;\n this.activeSubscriptions = new Map();\n }\n /**\n * Opens a subscription with the Filter protocol using the provided decoders and callback.\n * This method combines the functionality of creating a subscription and subscribing to it.\n *\n * @param {IDecoder | IDecoder[]} decoders - A single decoder or an array of decoders to use for decoding messages.\n * @param {Callback} callback - The callback function to be invoked with decoded messages.\n * @param {ProtocolUseOptions} [protocolUseOptions] - Optional settings for using the protocol.\n * @param {SubscribeOptions} [subscribeOptions=DEFAULT_SUBSCRIBE_OPTIONS] - Options for the subscription.\n *\n * @returns {Promise} A promise that resolves to an object containing:\n * - subscription: The created subscription object if successful, or null if failed.\n * - error: A ProtocolError if the subscription creation failed, or null if successful.\n * - results: An object containing arrays of failures and successes from the subscription process.\n * Only present if the subscription was created successfully.\n *\n * @throws {Error} If there's an unexpected error during the subscription process.\n *\n * @remarks\n * This method attempts to create a subscription using the pubsub topic derived from the provided decoders,\n * then tries to subscribe using the created subscription. The return value should be interpreted as follows:\n * - If `subscription` is null and `error` is non-null, a critical error occurred and the subscription failed completely.\n * - If `subscription` is non-null and `error` is null, the subscription was created successfully.\n * In this case, check the `results` field for detailed information about successes and failures during the subscription process.\n * - Even if the subscription was created successfully, there might be some failures in the results.\n *\n * @example\n * ```typescript\n * const {subscription, error, results} = await waku.filter.subscribe(decoders, callback);\n * if (!subscription || error) {\n * console.error(\"Failed to create subscription:\", error);\n * }\n * console.log(\"Subscription created successfully\");\n * if (results.failures.length > 0) {\n * console.warn(\"Some errors occurred during subscription:\", results.failures);\n * }\n * console.log(\"Successful subscriptions:\", results.successes);\n *\n * ```\n */\n async subscribe(decoders, callback, protocolUseOptions, subscribeOptions = DEFAULT_SUBSCRIBE_OPTIONS) {\n const uniquePubsubTopics = this.getUniquePubsubTopics(decoders);\n if (uniquePubsubTopics.length !== 1) {\n return {\n subscription: null,\n error: ProtocolError.INVALID_DECODER_TOPICS,\n results: null\n };\n }\n const pubsubTopic = uniquePubsubTopics[0];\n const { subscription, error } = await this.createSubscription(pubsubTopic, protocolUseOptions);\n if (error) {\n return {\n subscription: null,\n error: error,\n results: null\n };\n }\n const { failures, successes } = await subscription.subscribe(decoders, callback, subscribeOptions);\n return {\n subscription,\n error: null,\n results: {\n failures: failures,\n successes: successes\n }\n };\n }\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(pubsubTopicShardInfo, options) {\n options = {\n autoRetry: true,\n ...options\n };\n const pubsubTopic = typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : shardInfoToPubsubTopics(pubsubTopicShardInfo)?.[0];\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n const hasPeers = await this.hasPeers(options);\n if (!hasPeers) {\n return {\n error: ProtocolError.NO_PEER_AVAILABLE,\n subscription: null\n };\n }\n log.info(`Creating filter subscription with ${this.connectedPeers.length} peers: `, this.connectedPeers.map((peer) => peer.id.toString()));\n const subscription = this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(pubsubTopic, new SubscriptionManager(pubsubTopic, this.protocol, this.connectionManager, () => this.connectedPeers, this.renewPeer.bind(this), this.libp2p, this.lightPush));\n return {\n error: null,\n subscription\n };\n }\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribeWithUnsubscribe(decoders, callback, options = DEFAULT_SUBSCRIBE_OPTIONS) {\n const uniquePubsubTopics = this.getUniquePubsubTopics(decoders);\n if (uniquePubsubTopics.length === 0) {\n throw Error(\"Failed to subscribe: no pubsubTopic found on decoders provided.\");\n }\n if (uniquePubsubTopics.length > 1) {\n throw Error(\"Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.\");\n }\n const { subscription, error } = await this.createSubscription(uniquePubsubTopics[0]);\n if (error) {\n throw Error(`Failed to create subscription: ${error}`);\n }\n await subscription.subscribe(decoders, callback, options);\n const contentTopics = Array.from(groupByContentTopic(Array.isArray(decoders) ? decoders : [decoders]).keys());\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n toSubscriptionIterator(decoders) {\n return toAsyncIterator(this, decoders);\n }\n //TODO: move to SubscriptionManager\n getActiveSubscription(pubsubTopic) {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n setActiveSubscription(pubsubTopic, subscription) {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n getUniquePubsubTopics(decoders) {\n if (!Array.isArray(decoders)) {\n return [decoders.pubsubTopic];\n }\n if (decoders.length === 0) {\n return [];\n }\n const pubsubTopics = new Set(decoders.map((d) => d.pubsubTopic));\n return [...pubsubTopics];\n }\n}\nexport function wakuFilter(connectionManager, lightPush, init) {\n return (libp2p) => new Filter(connectionManager, libp2p, lightPush, init);\n}\n//# sourceMappingURL=index.js.map","import { getHealthManager, LightPushCodec, LightPushCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, Logger } from \"@waku/utils\";\nimport { DEFAULT_NUM_PEERS_TO_USE } from \"../base_protocol.js\";\nconst log = new Logger(\"sdk:light-push\");\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_SEND_OPTIONS = {\n autoRetry: false,\n maxAttempts: DEFAULT_MAX_ATTEMPTS\n};\nexport class LightPush {\n libp2p;\n numPeersToUse = DEFAULT_NUM_PEERS_TO_USE;\n protocol;\n constructor(connectionManager, libp2p, options) {\n this.libp2p = libp2p;\n this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS_TO_USE;\n this.protocol = new LightPushCore(connectionManager.configuredPubsubTopics, libp2p);\n }\n async send(encoder, message, options = DEFAULT_SEND_OPTIONS) {\n const successes = [];\n const failures = [];\n const { pubsubTopic } = encoder;\n try {\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n }\n catch (error) {\n log.error(\"Failed to send waku light push: pubsub topic not configured\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ]\n };\n }\n const peers = await this.getConnectedPeers();\n if (peers.length === 0) {\n return {\n successes,\n failures: [\n {\n error: ProtocolError.NO_PEER_AVAILABLE\n }\n ]\n };\n }\n const results = await Promise.allSettled(peers.map((peer) => this.protocol.send(encoder, message, peer)));\n for (const result of results) {\n if (result.status !== \"fulfilled\") {\n log.error(\"Failed unexpectedly while sending:\", result.reason);\n failures.push({ error: ProtocolError.GENERIC_FAIL });\n continue;\n }\n const { failure, success } = result.value;\n if (success) {\n successes.push(success);\n continue;\n }\n if (failure) {\n failures.push(failure);\n if (options?.autoRetry) {\n void this.attemptRetries((peer) => this.protocol.send(encoder, message, peer), options.maxAttempts);\n }\n }\n }\n getHealthManager().updateProtocolHealth(this.protocol.multicodec, successes.length);\n return {\n successes,\n failures\n };\n }\n async attemptRetries(fn, maxAttempts) {\n maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;\n const connectedPeers = await this.getConnectedPeers();\n if (connectedPeers.length === 0) {\n log.warn(\"Cannot retry with no connected peers.\");\n return;\n }\n for (let i = 0; i < maxAttempts; i++) {\n const peer = connectedPeers[i % connectedPeers.length]; // always present as we checked for the length already\n const response = await fn(peer);\n if (response.success) {\n return;\n }\n log.info(`Attempted retry for peer:${peer.id} failed with:${response?.failure?.error}`);\n }\n }\n async getConnectedPeers() {\n const peerIDs = this.libp2p.getPeers();\n if (peerIDs.length === 0) {\n return [];\n }\n const peers = await Promise.all(peerIDs.map(async (id) => {\n try {\n return await this.libp2p.peerStore.get(id);\n }\n catch (e) {\n return null;\n }\n }));\n return peers\n .filter((p) => !!p)\n .filter((p) => p.protocols.includes(LightPushCodec))\n .slice(0, this.numPeersToUse);\n }\n}\nexport function wakuLightPush(connectionManager, init = {}) {\n return (libp2p) => new LightPush(connectionManager, libp2p, init);\n}\n//# sourceMappingURL=light_push.js.map","import { StoreCore } from \"@waku/core\";\nimport { messageHash } from \"@waku/message-hash\";\nimport { ensurePubsubTopicIsConfigured, isDefined, Logger } from \"@waku/utils\";\nimport { BaseProtocolSDK } from \"../base_protocol.js\";\nconst DEFAULT_NUM_PEERS = 1;\nconst log = new Logger(\"waku:store:sdk\");\n/**\n * StoreSDK is an implementation of the IStoreSDK interface.\n * It provides methods to interact with the Waku Store protocol.\n */\nexport class Store extends BaseProtocolSDK {\n protocol;\n constructor(connectionManager, libp2p) {\n super(new StoreCore(connectionManager.configuredPubsubTopics, libp2p), connectionManager, {\n numPeersToUse: DEFAULT_NUM_PEERS\n });\n this.protocol = this.core;\n }\n /**\n * Queries the Waku Store for historical messages using the provided decoders and options.\n * Returns an asynchronous generator that yields promises of decoded messages.\n *\n * @param decoders - An array of message decoders.\n * @param options - Optional query parameters.\n * @returns An asynchronous generator of promises of decoded messages.\n * @throws If no peers are available to query or if an error occurs during the query.\n */\n async *queryGenerator(decoders, options) {\n const { pubsubTopic, contentTopics, decodersAsMap } = this.validateDecodersAndPubsubTopic(decoders);\n const queryOpts = {\n pubsubTopic,\n contentTopics,\n includeData: true,\n paginationForward: true,\n ...options\n };\n const peer = (await this.protocol.getPeers({\n numPeers: this.numPeersToUse,\n maxBootstrapPeers: 1\n }))[0];\n if (!peer) {\n log.error(\"No peers available to query\");\n throw new Error(\"No peers available to query\");\n }\n log.info(`Querying store with options: ${JSON.stringify(options)}`);\n const responseGenerator = this.protocol.queryPerPage(queryOpts, decodersAsMap, peer);\n for await (const messages of responseGenerator) {\n yield messages;\n }\n }\n /**\n * Queries the Waku Store for historical messages and processes them with the provided callback in order.\n *\n * @param decoders - An array of message decoders.\n * @param callback - A callback function to process each decoded message.\n * @param options - Optional query parameters.\n * @returns A promise that resolves when the query and message processing are completed.\n */\n async queryWithOrderedCallback(decoders, callback, options) {\n log.info(\"Querying store with ordered callback\");\n for await (const promises of this.queryGenerator(decoders, options)) {\n if (await this.processMessages(promises, callback))\n break;\n }\n }\n /**\n * Queries the Waku Store for historical messages and processes them with the provided callback using promises.\n *\n * @param decoders - An array of message decoders.\n * @param callback - A callback function to process each promise of a decoded message.\n * @param options - Optional query parameters.\n * @returns A promise that resolves when the query and message processing are completed.\n */\n async queryWithPromiseCallback(decoders, callback, options) {\n log.info(\"Querying store with promise callback\");\n let abort = false;\n for await (const page of this.queryGenerator(decoders, options)) {\n const _promises = page.map(async (msgPromise) => {\n if (abort)\n return;\n abort = Boolean(await callback(msgPromise));\n });\n await Promise.all(_promises);\n if (abort)\n break;\n }\n }\n /**\n * Processes messages based on the provided callback and options.\n *\n * @param messages - An array of promises of decoded messages.\n * @param callback - A callback function to process each decoded message.\n * @returns A promise that resolves to a boolean indicating whether the processing should abort.\n * @private\n */\n async processMessages(messages, callback) {\n let abort = false;\n const messagesOrUndef = await Promise.all(messages);\n const processedMessages = messagesOrUndef.filter(isDefined);\n await Promise.all(processedMessages.map(async (msg) => {\n if (msg && !abort) {\n abort = Boolean(await callback(msg));\n }\n }));\n return abort;\n }\n /**\n * Creates a cursor based on the provided decoded message.\n *\n * @param message - The decoded message.\n * @returns A StoreCursor representing the message.\n */\n createCursor(message) {\n return messageHash(message.pubsubTopic, message);\n }\n /**\n * Validates the provided decoders and pubsub topic.\n *\n * @param decoders - An array of message decoders.\n * @returns An object containing the pubsub topic, content topics, and a map of decoders.\n * @throws If no decoders are provided, if multiple pubsub topics are provided, or if no decoders are found for the pubsub topic.\n * @private\n */\n validateDecodersAndPubsubTopic(decoders) {\n if (decoders.length === 0) {\n log.error(\"No decoders provided\");\n throw new Error(\"No decoders provided\");\n }\n const uniquePubsubTopicsInQuery = Array.from(new Set(decoders.map((decoder) => decoder.pubsubTopic)));\n if (uniquePubsubTopicsInQuery.length > 1) {\n log.error(\"API does not support querying multiple pubsub topics at once\");\n throw new Error(\"API does not support querying multiple pubsub topics at once\");\n }\n const pubsubTopicForQuery = uniquePubsubTopicsInQuery[0];\n ensurePubsubTopicIsConfigured(pubsubTopicForQuery, this.protocol.pubsubTopics);\n const decodersAsMap = new Map();\n decoders.forEach((dec) => {\n if (decodersAsMap.has(dec.contentTopic)) {\n log.error(\"API does not support different decoder per content topic\");\n throw new Error(\"API does not support different decoder per content topic\");\n }\n decodersAsMap.set(dec.contentTopic, dec);\n });\n const contentTopics = decoders\n .filter((decoder) => decoder.pubsubTopic === pubsubTopicForQuery)\n .map((dec) => dec.contentTopic);\n if (contentTopics.length === 0) {\n log.error(`No decoders found for topic ${pubsubTopicForQuery}`);\n throw new Error(\"No decoders found for topic \" + pubsubTopicForQuery);\n }\n return {\n pubsubTopic: pubsubTopicForQuery,\n contentTopics,\n decodersAsMap\n };\n }\n}\n/**\n * Factory function to create an instance of the StoreSDK.\n *\n * @param init - Partial options for protocol creation.\n * @returns A function that takes a Libp2p instance and returns a StoreSDK instance.\n */\nexport function wakuStore(connectionManager) {\n return (libp2p) => {\n return new Store(connectionManager, libp2p);\n };\n}\n//# sourceMappingURL=index.js.map","import { FilterCodecs, LightPushCodec, StoreCodec } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nconst log = new Logger(\"wait-for-remote-peer\");\n/**\n * @deprecated Since @waku/sdk 0.29.0. Will be removed from 0.31.0\n *\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using\n * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with\n * {@link @waku/sdk!createLightNode}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n * @throws If passing a protocol that is not mounted\n * @default Wait for remote peers with protocols enabled locally and no time out is applied.\n */\nexport async function waitForRemotePeer(waku, protocols, timeoutMs) {\n // if no protocols or empty array passed - try to derive from mounted\n protocols = protocols?.length ? protocols : getEnabledProtocols(waku);\n const connections = waku.libp2p.getConnections();\n if (!waku.isStarted()) {\n throw Error(\"Waku node is not started\");\n }\n if (connections.length > 0 && !protocols.includes(Protocols.Relay)) {\n const success = await waitForMetadata(waku, protocols);\n if (success) {\n return;\n }\n }\n const promises = [];\n if (protocols.includes(Protocols.Relay)) {\n if (!waku.relay) {\n throw Error(\"Cannot wait for Relay peer: protocol not mounted\");\n }\n promises.push(waku.relay.waitForPeers());\n }\n if (protocols.includes(Protocols.Store)) {\n if (!waku.store) {\n throw Error(\"Cannot wait for Store peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(StoreCodec, waku.libp2p));\n }\n if (protocols.includes(Protocols.LightPush)) {\n if (!waku.lightPush) {\n throw Error(\"Cannot wait for LightPush peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(LightPushCodec, waku.libp2p));\n }\n if (protocols.includes(Protocols.Filter)) {\n if (!waku.filter) {\n throw new Error(\"Cannot wait for Filter peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(FilterCodecs.SUBSCRIBE, waku.libp2p));\n }\n if (timeoutMs) {\n await rejectOnTimeout(Promise.all(promises), timeoutMs, \"Timed out waiting for a remote peer.\");\n }\n else {\n await Promise.all(promises);\n }\n}\n/**\n * Wait for a peer with the given protocol to be connected.\n * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.\n */\nasync function waitForConnectedPeer(codec, libp2p) {\n log.info(`Waiting for ${codec} peer.`);\n await new Promise((resolve) => {\n const cb = (async (evt) => {\n if (evt.detail?.protocols?.includes(codec)) {\n const metadataService = libp2p.services.metadata;\n if (!metadataService) {\n libp2p.removeEventListener(\"peer:identify\", cb);\n resolve();\n return;\n }\n try {\n await metadataService.confirmOrAttemptHandshake(evt.detail.peerId);\n libp2p.removeEventListener(\"peer:identify\", cb);\n resolve();\n }\n catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\") {\n log.error(\"Connection closed. Some peers can be on different shard.\");\n }\n log.error(`Error waiting for metadata: ${e}`);\n }\n }\n });\n libp2p.addEventListener(\"peer:identify\", cb);\n });\n}\n/**\n * Waits for the metadata from the remote peer.\n */\nasync function waitForMetadata(waku, protocols) {\n const connectedPeers = waku.libp2p.getPeers();\n const metadataService = waku.libp2p.services.metadata;\n const enabledCodes = mapProtocolsToCodecs(protocols);\n if (!connectedPeers.length || !metadataService) {\n log.info(`Skipping waitForMetadata due to missing connections:${connectedPeers.length} or metadataService:${!!metadataService}`);\n return false;\n }\n for (const peerId of connectedPeers) {\n try {\n const peer = await waku.libp2p.peerStore.get(peerId);\n const hasSomeCodes = peer.protocols.some((c) => enabledCodes.has(c));\n if (hasSomeCodes) {\n const response = await metadataService.confirmOrAttemptHandshake(peerId);\n if (!response.error) {\n peer.protocols.forEach((c) => {\n if (enabledCodes.has(c)) {\n enabledCodes.set(c, true);\n }\n });\n const confirmedAllCodecs = Array.from(enabledCodes.values()).every((v) => v);\n if (confirmedAllCodecs) {\n return true;\n }\n }\n }\n }\n catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\") {\n log.error(\"Connection closed. Some peers can be on different shard.\");\n }\n log.error(`Error while iterating through peers: ${e}`);\n continue;\n }\n }\n return false;\n}\nconst awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(Error(rejectReason)), ms));\nasync function rejectOnTimeout(promise, timeoutMs, rejectReason) {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\nfunction getEnabledProtocols(waku) {\n const protocols = [];\n if (waku.relay) {\n protocols.push(Protocols.Relay);\n }\n if (waku.filter) {\n protocols.push(Protocols.Filter);\n }\n if (waku.store) {\n protocols.push(Protocols.Store);\n }\n if (waku.lightPush) {\n protocols.push(Protocols.LightPush);\n }\n return protocols;\n}\nfunction mapProtocolsToCodecs(protocols) {\n const codecs = new Map();\n const protocolToCodec = {\n [Protocols.Filter]: FilterCodecs.SUBSCRIBE,\n [Protocols.LightPush]: LightPushCodec,\n [Protocols.Store]: StoreCodec\n };\n for (const protocol of protocols) {\n if (protocolToCodec[protocol]) {\n codecs.set(protocolToCodec[protocol], false);\n }\n }\n return codecs;\n}\n//# sourceMappingURL=wait_for_remote_peer.js.map","import { isPeerId } from \"@libp2p/interface\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { ConnectionManager, getHealthManager } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { wakuFilter } from \"../protocols/filter/index.js\";\nimport { wakuLightPush } from \"../protocols/light_push/index.js\";\nimport { wakuStore } from \"../protocols/store/index.js\";\nimport { ReliabilityMonitorManager } from \"../reliability_monitor/index.js\";\nimport { waitForRemotePeer } from \"./wait_for_remote_peer.js\";\nexport const DefaultPingKeepAliveValueSecs = 5 * 60;\nexport const DefaultRelayKeepAliveValueSecs = 5 * 60;\nexport const DefaultUserAgent = \"js-waku\";\nexport const DefaultPingMaxInboundStreams = 10;\nconst log = new Logger(\"waku\");\nexport class WakuNode {\n pubsubTopics;\n libp2p;\n relay;\n store;\n filter;\n lightPush;\n connectionManager;\n health;\n constructor(pubsubTopics, options, libp2p, protocolsEnabled, relay) {\n this.pubsubTopics = pubsubTopics;\n this.relay = relay;\n this.libp2p = libp2p;\n protocolsEnabled = {\n filter: false,\n lightpush: false,\n store: false,\n ...protocolsEnabled\n };\n const pingKeepAlive = options.pingKeepAlive || DefaultPingKeepAliveValueSecs;\n const relayKeepAlive = this.relay\n ? options.relayKeepAlive || DefaultRelayKeepAliveValueSecs\n : 0;\n const peerId = this.libp2p.peerId.toString();\n this.connectionManager = ConnectionManager.create(peerId, libp2p, { pingKeepAlive, relayKeepAlive }, this.pubsubTopics, this.relay);\n this.health = getHealthManager();\n if (protocolsEnabled.store) {\n const store = wakuStore(this.connectionManager);\n this.store = store(libp2p);\n }\n if (protocolsEnabled.lightpush) {\n const lightPush = wakuLightPush(this.connectionManager, options);\n this.lightPush = lightPush(libp2p);\n }\n if (protocolsEnabled.filter) {\n const filter = wakuFilter(this.connectionManager, this.lightPush, options);\n this.filter = filter(libp2p);\n }\n log.info(\"Waku node created\", peerId, `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this\n .lightPush}, filter: ${!!this.filter}`);\n }\n get peerId() {\n return this.libp2p.peerId;\n }\n get protocols() {\n return this.libp2p.getProtocols();\n }\n async dial(peer, protocols) {\n const _protocols = protocols ?? [];\n const peerId = this.mapToPeerIdOrMultiaddr(peer);\n if (typeof protocols === \"undefined\") {\n this.relay && _protocols.push(Protocols.Relay);\n this.store && _protocols.push(Protocols.Store);\n this.filter && _protocols.push(Protocols.Filter);\n this.lightPush && _protocols.push(Protocols.LightPush);\n }\n const codecs = [];\n if (_protocols.includes(Protocols.Relay)) {\n if (this.relay) {\n this.relay.gossipSub.multicodecs.forEach((codec) => codecs.push(codec));\n }\n else {\n log.error(\"Relay codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Store)) {\n if (this.store) {\n codecs.push(this.store.protocol.multicodec);\n }\n else {\n log.error(\"Store codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n if (this.lightPush) {\n codecs.push(this.lightPush.protocol.multicodec);\n }\n else {\n log.error(\"Light Push codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Filter)) {\n if (this.filter) {\n codecs.push(this.filter.protocol.multicodec);\n }\n else {\n log.error(\"Filter codec not included in dial codec: protocol not mounted locally\");\n }\n }\n log.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);\n return this.libp2p.dialProtocol(peerId, codecs);\n }\n async start() {\n await this.libp2p.start();\n }\n async stop() {\n ReliabilityMonitorManager.stopAll();\n this.connectionManager.stop();\n await this.libp2p.stop();\n }\n async waitForPeers(protocols, timeoutMs) {\n return waitForRemotePeer(this, protocols, timeoutMs);\n }\n isStarted() {\n return this.libp2p.status == \"started\";\n }\n isConnected() {\n return this.connectionManager.isConnected();\n }\n mapToPeerIdOrMultiaddr(peerId) {\n return isPeerId(peerId) ? peerId : multiaddr(peerId);\n }\n}\n//# sourceMappingURL=waku.js.map","/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nexport class CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nexport class AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nexport class UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nexport class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nexport class InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nexport const ERR_TIMEOUT = 'ERR_TIMEOUT';\nexport const ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nexport const ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nexport const ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(`${title} must be valid boolean, got \"${value}\".`);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error(`expected valid ${title}: ${min} <= n < ${max}, got ${typeof n} ${n}`);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\nexport function FpLegendre(order) {\n // (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n // (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * NOTE: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject, bitLen } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const validateW = (W) => {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error(`Wrong window size=${W}, should be [1..${bits}]`);\n };\n const opts = (W) => {\n validateW(W);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, n, transform) {\n const W = pointWindowSizes.get(P) || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return this.wNAF(W, comp, n);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM).\n * MSM is basically (Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param field field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, field, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length)\n throw new Error('arrays of points and scalars must have equal length');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error(`wrong scalar at index ${i}`);\n });\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error(`wrong point at index ${i}`);\n });\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(c.ZERO); // +1 for zero array\n const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize;\n let sum = c.ZERO;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(c.ZERO);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = c.ZERO; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport { mod, Field } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n/**\n * ed25519 curve with EdDSA signatures.\n */\nexport const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nexport const ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n}))();\nexport const ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n})))();\nexport const x25519 = /* @__PURE__ */ (() => montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map","/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto-browser.js.map","import { concat } from 'uint8arrays/concat';\nimport { fromString } from 'uint8arrays/from-string';\nimport webcrypto from '../webcrypto.js';\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nexport const derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nexport function create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = webcrypto.get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return concat([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = fromString(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map","import { base64 } from 'multiformats/bases/base64';\nimport * as ciphers from '../ciphers/aes-gcm.js';\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nexport async function exporter(privateKey, password) {\n const cipher = ciphers.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { enumeration, encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return decodeMessage(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return decodeMessage(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","import { CodeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { isPromise } from '../util.js';\nimport * as crypto from './ed25519.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nexport class Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, crypto.publicKeyLength);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, crypto.privateKeyLength);\n this._publicKey = ensureKey(publicKey, crypto.publicKeyLength);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = identity.digest(this.public.bytes);\n return base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureKey(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nexport async function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map","import { CodeError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport * as utils from './rsa-utils.js';\nexport { utils };\nexport async function generateKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nexport async function unmarshalPrivateKey(key) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return webcrypto.get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nexport function keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/*!\n Copyright (c) Peculiar Ventures, LLC\n*/\n\nfunction getUTCDate(date) {\r\n return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));\r\n}\r\nfunction getParametersValue(parameters, name, defaultValue) {\r\n var _a;\r\n if ((parameters instanceof Object) === false) {\r\n return defaultValue;\r\n }\r\n return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;\r\n}\r\nfunction bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {\r\n let result = \"\";\r\n for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {\r\n const str = item.toString(16).toUpperCase();\r\n if (str.length === 1) {\r\n result += \"0\";\r\n }\r\n result += str;\r\n if (insertSpace) {\r\n result += \" \";\r\n }\r\n }\r\n return result.trim();\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof ArrayBuffer)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be \\\"ArrayBuffer\\\"\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction utilFromBase(inputBuffer, inputBase) {\r\n let result = 0;\r\n if (inputBuffer.length === 1) {\r\n return inputBuffer[0];\r\n }\r\n for (let i = (inputBuffer.length - 1); i >= 0; i--) {\r\n result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);\r\n }\r\n return result;\r\n}\r\nfunction utilToBase(value, base, reserved = (-1)) {\r\n const internalReserved = reserved;\r\n let internalValue = value;\r\n let result = 0;\r\n let biggest = Math.pow(2, base);\r\n for (let i = 1; i < 8; i++) {\r\n if (value < biggest) {\r\n let retBuf;\r\n if (internalReserved < 0) {\r\n retBuf = new ArrayBuffer(i);\r\n result = i;\r\n }\r\n else {\r\n if (internalReserved < i) {\r\n return (new ArrayBuffer(0));\r\n }\r\n retBuf = new ArrayBuffer(internalReserved);\r\n result = internalReserved;\r\n }\r\n const retView = new Uint8Array(retBuf);\r\n for (let j = (i - 1); j >= 0; j--) {\r\n const basis = Math.pow(2, j * base);\r\n retView[result - j - 1] = Math.floor(internalValue / basis);\r\n internalValue -= (retView[result - j - 1]) * basis;\r\n }\r\n return retBuf;\r\n }\r\n biggest *= Math.pow(2, base);\r\n }\r\n return new ArrayBuffer(0);\r\n}\r\nfunction utilConcatBuf(...buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const buffer of buffers) {\r\n outputLength += buffer.byteLength;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const buffer of buffers) {\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retBuf;\r\n}\r\nfunction utilConcatView(...views) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const view of views) {\r\n outputLength += view.length;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const view of views) {\r\n retView.set(view, prevLength);\r\n prevLength += view.length;\r\n }\r\n return retView;\r\n}\r\nfunction utilDecodeTC() {\r\n const buf = new Uint8Array(this.valueHex);\r\n if (this.valueHex.byteLength >= 2) {\r\n const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);\r\n const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);\r\n if (condition1 || condition2) {\r\n this.warnings.push(\"Needlessly long format\");\r\n }\r\n }\r\n const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const bigIntView = new Uint8Array(bigIntBuffer);\r\n for (let i = 0; i < this.valueHex.byteLength; i++) {\r\n bigIntView[i] = 0;\r\n }\r\n bigIntView[0] = (buf[0] & 0x80);\r\n const bigInt = utilFromBase(bigIntView, 8);\r\n const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const smallIntView = new Uint8Array(smallIntBuffer);\r\n for (let j = 0; j < this.valueHex.byteLength; j++) {\r\n smallIntView[j] = buf[j];\r\n }\r\n smallIntView[0] &= 0x7F;\r\n const smallInt = utilFromBase(smallIntView, 8);\r\n return (smallInt - bigInt);\r\n}\r\nfunction utilEncodeTC(value) {\r\n const modValue = (value < 0) ? (value * (-1)) : value;\r\n let bigInt = 128;\r\n for (let i = 1; i < 8; i++) {\r\n if (modValue <= bigInt) {\r\n if (value < 0) {\r\n const smallInt = bigInt - modValue;\r\n const retBuf = utilToBase(smallInt, 8, i);\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] |= 0x80;\r\n return retBuf;\r\n }\r\n let retBuf = utilToBase(modValue, 8, i);\r\n let retView = new Uint8Array(retBuf);\r\n if (retView[0] & 0x80) {\r\n const tempBuf = retBuf.slice(0);\r\n const tempView = new Uint8Array(tempBuf);\r\n retBuf = new ArrayBuffer(retBuf.byteLength + 1);\r\n retView = new Uint8Array(retBuf);\r\n for (let k = 0; k < tempBuf.byteLength; k++) {\r\n retView[k + 1] = tempView[k];\r\n }\r\n retView[0] = 0x00;\r\n }\r\n return retBuf;\r\n }\r\n bigInt *= Math.pow(2, 8);\r\n }\r\n return (new ArrayBuffer(0));\r\n}\r\nfunction isEqualBuffer(inputBuffer1, inputBuffer2) {\r\n if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {\r\n return false;\r\n }\r\n const view1 = new Uint8Array(inputBuffer1);\r\n const view2 = new Uint8Array(inputBuffer2);\r\n for (let i = 0; i < view1.length; i++) {\r\n if (view1[i] !== view2[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction padNumber(inputNumber, fullLength) {\r\n const str = inputNumber.toString(10);\r\n if (fullLength < str.length) {\r\n return \"\";\r\n }\r\n const dif = fullLength - str.length;\r\n const padding = new Array(dif);\r\n for (let i = 0; i < dif; i++) {\r\n padding[i] = \"0\";\r\n }\r\n const paddingString = padding.join(\"\");\r\n return paddingString.concat(str);\r\n}\r\nconst base64Template = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\nconst base64UrlTemplate = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\";\r\nfunction toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {\r\n let i = 0;\r\n let flag1 = 0;\r\n let flag2 = 0;\r\n let output = \"\";\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n if (skipLeadingZeros) {\r\n let nonZeroPosition = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n if (input.charCodeAt(i) !== 0) {\r\n nonZeroPosition = i;\r\n break;\r\n }\r\n }\r\n input = input.slice(nonZeroPosition);\r\n }\r\n while (i < input.length) {\r\n const chr1 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag1 = 1;\r\n }\r\n const chr2 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag2 = 1;\r\n }\r\n const chr3 = input.charCodeAt(i++);\r\n const enc1 = chr1 >> 2;\r\n const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);\r\n let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);\r\n let enc4 = chr3 & 0x3F;\r\n if (flag1 === 1) {\r\n enc3 = enc4 = 64;\r\n }\r\n else {\r\n if (flag2 === 1) {\r\n enc4 = 64;\r\n }\r\n }\r\n if (skipPadding) {\r\n if (enc3 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}`;\r\n }\r\n else {\r\n if (enc4 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n return output;\r\n}\r\nfunction fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n function indexOf(toSearch) {\r\n for (let i = 0; i < 64; i++) {\r\n if (template.charAt(i) === toSearch)\r\n return i;\r\n }\r\n return 64;\r\n }\r\n function test(incoming) {\r\n return ((incoming === 64) ? 0x00 : incoming);\r\n }\r\n let i = 0;\r\n let output = \"\";\r\n while (i < input.length) {\r\n const enc1 = indexOf(input.charAt(i++));\r\n const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);\r\n const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);\r\n const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);\r\n output += String.fromCharCode(chr1);\r\n if (enc3 !== 64) {\r\n output += String.fromCharCode(chr2);\r\n }\r\n if (enc4 !== 64) {\r\n output += String.fromCharCode(chr3);\r\n }\r\n }\r\n if (cutTailZeros) {\r\n const outputLength = output.length;\r\n let nonZeroStart = (-1);\r\n for (let i = (outputLength - 1); i >= 0; i--) {\r\n if (output.charCodeAt(i) !== 0) {\r\n nonZeroStart = i;\r\n break;\r\n }\r\n }\r\n if (nonZeroStart !== (-1)) {\r\n output = output.slice(0, nonZeroStart + 1);\r\n }\r\n else {\r\n output = \"\";\r\n }\r\n }\r\n return output;\r\n}\r\nfunction arrayBufferToString(buffer) {\r\n let resultString = \"\";\r\n const view = new Uint8Array(buffer);\r\n for (const element of view) {\r\n resultString += String.fromCharCode(element);\r\n }\r\n return resultString;\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n const stringLength = str.length;\r\n const resultBuffer = new ArrayBuffer(stringLength);\r\n const resultView = new Uint8Array(resultBuffer);\r\n for (let i = 0; i < stringLength; i++) {\r\n resultView[i] = str.charCodeAt(i);\r\n }\r\n return resultBuffer;\r\n}\r\nconst log2 = Math.log(2);\r\nfunction nearestPowerOf2(length) {\r\n const base = (Math.log(length) / log2);\r\n const floor = Math.floor(base);\r\n const round = Math.round(base);\r\n return ((floor === round) ? floor : round);\r\n}\r\nfunction clearProps(object, propsArray) {\r\n for (const prop of propsArray) {\r\n delete object[prop];\r\n }\r\n}\n\nexport { arrayBufferToString, bufferToHexCodes, checkBufferParams, clearProps, fromBase64, getParametersValue, getUTCDate, isEqualBuffer, nearestPowerOf2, padNumber, stringToArrayBuffer, toBase64, utilConcatBuf, utilConcatView, utilDecodeTC, utilEncodeTC, utilFromBase, utilToBase };\n","/*!\n * Copyright (c) 2014, GMO GlobalSign\n * Copyright (c) 2015-2022, Peculiar Ventures\n * All rights reserved.\n * \n * Author 2014-2019, Yury Strozhevsky\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * \n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\nimport * as pvtsutils from 'pvtsutils';\nimport * as pvutils from 'pvutils';\n\nfunction assertBigInt() {\r\n if (typeof BigInt === \"undefined\") {\r\n throw new Error(\"BigInt is not defined. Your environment doesn't implement BigInt.\");\r\n }\r\n}\r\nfunction concat(buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n outputLength += buffer.byteLength;\r\n }\r\n const retView = new Uint8Array(outputLength);\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retView.buffer;\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof Uint8Array)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be 'Uint8Array'\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\n\nclass ViewWriter {\r\n constructor() {\r\n this.items = [];\r\n }\r\n write(buf) {\r\n this.items.push(buf);\r\n }\r\n final() {\r\n return concat(this.items);\r\n }\r\n}\n\nconst powers2 = [new Uint8Array([1])];\r\nconst digitsString = \"0123456789\";\r\nconst NAME = \"name\";\r\nconst VALUE_HEX_VIEW = \"valueHexView\";\r\nconst IS_HEX_ONLY = \"isHexOnly\";\r\nconst ID_BLOCK = \"idBlock\";\r\nconst TAG_CLASS = \"tagClass\";\r\nconst TAG_NUMBER = \"tagNumber\";\r\nconst IS_CONSTRUCTED = \"isConstructed\";\r\nconst FROM_BER = \"fromBER\";\r\nconst TO_BER = \"toBER\";\r\nconst LOCAL = \"local\";\r\nconst EMPTY_STRING = \"\";\r\nconst EMPTY_BUFFER = new ArrayBuffer(0);\r\nconst EMPTY_VIEW = new Uint8Array(0);\r\nconst END_OF_CONTENT_NAME = \"EndOfContent\";\r\nconst OCTET_STRING_NAME = \"OCTET STRING\";\r\nconst BIT_STRING_NAME = \"BIT STRING\";\n\nfunction HexBlock(BaseClass) {\r\n var _a;\r\n return _a = class Some extends BaseClass {\r\n constructor(...args) {\r\n var _a;\r\n super(...args);\r\n const params = args[0] || {};\r\n this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;\r\n }\r\n get valueHex() {\r\n return this.valueHexView.slice().buffer;\r\n }\r\n set valueHex(value) {\r\n this.valueHexView = new Uint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const endLength = inputOffset + inputLength;\r\n this.valueHexView = view.subarray(inputOffset, endLength);\r\n if (!this.valueHexView.length) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n this.blockLength = inputLength;\r\n return endLength;\r\n }\r\n toBER(sizeOnly = false) {\r\n if (!this.isHexOnly) {\r\n this.error = \"Flag 'isHexOnly' is not set, abort\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength);\r\n }\r\n return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)\r\n ? this.valueHexView.buffer\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isHexOnly: this.isHexOnly,\r\n valueHex: pvtsutils.Convert.ToHex(this.valueHexView),\r\n };\r\n }\r\n },\r\n _a.NAME = \"hexBlock\",\r\n _a;\r\n}\n\nclass LocalBaseBlock {\r\n constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {\r\n this.blockLength = blockLength;\r\n this.error = error;\r\n this.warnings = warnings;\r\n this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode);\r\n }\r\n static blockName() {\r\n return this.NAME;\r\n }\r\n get valueBeforeDecode() {\r\n return this.valueBeforeDecodeView.slice().buffer;\r\n }\r\n set valueBeforeDecode(value) {\r\n this.valueBeforeDecodeView = new Uint8Array(value);\r\n }\r\n toJSON() {\r\n return {\r\n blockName: this.constructor.NAME,\r\n blockLength: this.blockLength,\r\n error: this.error,\r\n warnings: this.warnings,\r\n valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView),\r\n };\r\n }\r\n}\r\nLocalBaseBlock.NAME = \"baseBlock\";\n\nclass ValueBlock extends LocalBaseBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n toBER(sizeOnly, writer) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n}\r\nValueBlock.NAME = \"valueBlock\";\n\nclass LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ idBlock = {}, } = {}) {\r\n var _a, _b, _c, _d;\r\n super();\r\n if (idBlock) {\r\n this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;\r\n this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;\r\n this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;\r\n this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;\r\n }\r\n else {\r\n this.tagClass = -1;\r\n this.tagNumber = -1;\r\n this.isConstructed = false;\r\n }\r\n }\r\n toBER(sizeOnly = false) {\r\n let firstOctet = 0;\r\n switch (this.tagClass) {\r\n case 1:\r\n firstOctet |= 0x00;\r\n break;\r\n case 2:\r\n firstOctet |= 0x40;\r\n break;\r\n case 3:\r\n firstOctet |= 0x80;\r\n break;\r\n case 4:\r\n firstOctet |= 0xC0;\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (this.isConstructed)\r\n firstOctet |= 0x20;\r\n if (this.tagNumber < 31 && !this.isHexOnly) {\r\n const retView = new Uint8Array(1);\r\n if (!sizeOnly) {\r\n let number = this.tagNumber;\r\n number &= 0x1F;\r\n firstOctet |= number;\r\n retView[0] = firstOctet;\r\n }\r\n return retView.buffer;\r\n }\r\n if (!this.isHexOnly) {\r\n const encodedBuf = pvutils.utilToBase(this.tagNumber, 7);\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const size = encodedBuf.byteLength;\r\n const retView = new Uint8Array(size + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n for (let i = 0; i < (size - 1); i++)\r\n retView[i + 1] = encodedView[i] | 0x80;\r\n retView[size] = encodedView[size - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.byteLength + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n const curView = this.valueHexView;\r\n for (let i = 0; i < (curView.length - 1); i++)\r\n retView[i + 1] = curView[i] | 0x80;\r\n retView[this.valueHexView.byteLength] = curView[curView.length - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n const tagClassMask = intBuffer[0] & 0xC0;\r\n switch (tagClassMask) {\r\n case 0x00:\r\n this.tagClass = (1);\r\n break;\r\n case 0x40:\r\n this.tagClass = (2);\r\n break;\r\n case 0x80:\r\n this.tagClass = (3);\r\n break;\r\n case 0xC0:\r\n this.tagClass = (4);\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return -1;\r\n }\r\n this.isConstructed = (intBuffer[0] & 0x20) === 0x20;\r\n this.isHexOnly = false;\r\n const tagNumberMask = intBuffer[0] & 0x1F;\r\n if (tagNumberMask !== 0x1F) {\r\n this.tagNumber = (tagNumberMask);\r\n this.blockLength = 1;\r\n }\r\n else {\r\n let count = 1;\r\n let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);\r\n let tagNumberBufferMaxLength = 255;\r\n while (intBuffer[count] & 0x80) {\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n count++;\r\n if (count >= intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (count === tagNumberBufferMaxLength) {\r\n tagNumberBufferMaxLength += 255;\r\n const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);\r\n for (let i = 0; i < intTagNumberBuffer.length; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);\r\n }\r\n }\r\n this.blockLength = (count + 1);\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n const tempBufferView = new Uint8Array(count);\r\n for (let i = 0; i < count; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(count);\r\n intTagNumberBuffer.set(tempBufferView);\r\n if (this.blockLength <= 9)\r\n this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Tag too long, represented as hex-coded\");\r\n }\r\n }\r\n if (((this.tagClass === 1)) &&\r\n (this.isConstructed)) {\r\n switch (this.tagNumber) {\r\n case 1:\r\n case 2:\r\n case 5:\r\n case 6:\r\n case 9:\r\n case 13:\r\n case 14:\r\n case 23:\r\n case 24:\r\n case 31:\r\n case 32:\r\n case 33:\r\n case 34:\r\n this.error = \"Constructed encoding used for primitive type\";\r\n return -1;\r\n }\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n tagClass: this.tagClass,\r\n tagNumber: this.tagNumber,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalIdentificationBlock.NAME = \"identificationBlock\";\n\nclass LocalLengthBlock extends LocalBaseBlock {\r\n constructor({ lenBlock = {}, } = {}) {\r\n var _a, _b, _c;\r\n super();\r\n this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;\r\n this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;\r\n this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n if (intBuffer[0] === 0xFF) {\r\n this.error = \"Length block 0xFF is reserved by standard\";\r\n return -1;\r\n }\r\n this.isIndefiniteForm = intBuffer[0] === 0x80;\r\n if (this.isIndefiniteForm) {\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n this.longFormUsed = !!(intBuffer[0] & 0x80);\r\n if (this.longFormUsed === false) {\r\n this.length = (intBuffer[0]);\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n const count = intBuffer[0] & 0x7F;\r\n if (count > 8) {\r\n this.error = \"Too big integer\";\r\n return -1;\r\n }\r\n if ((count + 1) > intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n const lenOffset = inputOffset + 1;\r\n const lengthBufferView = view.subarray(lenOffset, lenOffset + count);\r\n if (lengthBufferView[count - 1] === 0x00)\r\n this.warnings.push(\"Needlessly long encoded length\");\r\n this.length = pvutils.utilFromBase(lengthBufferView, 8);\r\n if (this.longFormUsed && (this.length <= 127))\r\n this.warnings.push(\"Unnecessary usage of long length form\");\r\n this.blockLength = count + 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly = false) {\r\n let retBuf;\r\n let retView;\r\n if (this.length > 127)\r\n this.longFormUsed = true;\r\n if (this.isIndefiniteForm) {\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = 0x80;\r\n }\r\n return retBuf;\r\n }\r\n if (this.longFormUsed) {\r\n const encodedBuf = pvutils.utilToBase(this.length, 8);\r\n if (encodedBuf.byteLength > 127) {\r\n this.error = \"Too big length\";\r\n return (EMPTY_BUFFER);\r\n }\r\n retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);\r\n if (sizeOnly)\r\n return retBuf;\r\n const encodedView = new Uint8Array(encodedBuf);\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = encodedBuf.byteLength | 0x80;\r\n for (let i = 0; i < encodedBuf.byteLength; i++)\r\n retView[i + 1] = encodedView[i];\r\n return retBuf;\r\n }\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = this.length;\r\n }\r\n return retBuf;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n longFormUsed: this.longFormUsed,\r\n length: this.length,\r\n };\r\n }\r\n}\r\nLocalLengthBlock.NAME = \"lengthBlock\";\n\nconst typeStore = {};\n\nclass BaseBlock extends LocalBaseBlock {\r\n constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {\r\n super(parameters);\r\n this.name = name;\r\n this.optional = optional;\r\n if (primitiveSchema) {\r\n this.primitiveSchema = primitiveSchema;\r\n }\r\n this.idBlock = new LocalIdentificationBlock(parameters);\r\n this.lenBlock = new LocalLengthBlock(parameters);\r\n this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n if (!writer) {\r\n prepareIndefiniteForm(this);\r\n }\r\n const idBlockBuf = this.idBlock.toBER(sizeOnly);\r\n _writer.write(idBlockBuf);\r\n if (this.lenBlock.isIndefiniteForm) {\r\n _writer.write(new Uint8Array([0x80]).buffer);\r\n this.valueBlock.toBER(sizeOnly, _writer);\r\n _writer.write(new ArrayBuffer(2));\r\n }\r\n else {\r\n const valueBlockBuf = this.valueBlock.toBER(sizeOnly);\r\n this.lenBlock.length = valueBlockBuf.byteLength;\r\n const lenBlockBuf = this.lenBlock.toBER(sizeOnly);\r\n _writer.write(lenBlockBuf);\r\n _writer.write(valueBlockBuf);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n idBlock: this.idBlock.toJSON(),\r\n lenBlock: this.lenBlock.toJSON(),\r\n valueBlock: this.valueBlock.toJSON(),\r\n name: this.name,\r\n optional: this.optional,\r\n };\r\n if (this.primitiveSchema)\r\n object.primitiveSchema = this.primitiveSchema.toJSON();\r\n return object;\r\n }\r\n toString(encoding = \"ascii\") {\r\n if (encoding === \"ascii\") {\r\n return this.onAsciiEncoding();\r\n }\r\n return pvtsutils.Convert.ToHex(this.toBER());\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;\r\n }\r\n isEqual(other) {\r\n if (this === other) {\r\n return true;\r\n }\r\n if (!(other instanceof this.constructor)) {\r\n return false;\r\n }\r\n const thisRaw = this.toBER();\r\n const otherRaw = other.toBER();\r\n return pvutils.isEqualBuffer(thisRaw, otherRaw);\r\n }\r\n}\r\nBaseBlock.NAME = \"BaseBlock\";\r\nfunction prepareIndefiniteForm(baseBlock) {\r\n if (baseBlock instanceof typeStore.Constructed) {\r\n for (const value of baseBlock.valueBlock.value) {\r\n if (prepareIndefiniteForm(value)) {\r\n baseBlock.lenBlock.isIndefiniteForm = true;\r\n }\r\n }\r\n }\r\n return !!baseBlock.lenBlock.isIndefiniteForm;\r\n}\n\nclass BaseStringBlock extends BaseBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {\r\n super(parameters, stringValueBlockType);\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n this.fromBuffer(this.valueBlock.valueHexView);\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : '${this.valueBlock.value}'`;\r\n }\r\n}\r\nBaseStringBlock.NAME = \"BaseStringBlock\";\n\nclass LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ isHexOnly = true, ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = isHexOnly;\r\n }\r\n}\r\nLocalPrimitiveValueBlock.NAME = \"PrimitiveValueBlock\";\n\nvar _a$w;\r\nclass Primitive extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalPrimitiveValueBlock);\r\n this.idBlock.isConstructed = false;\r\n }\r\n}\r\n_a$w = Primitive;\r\n(() => {\r\n typeStore.Primitive = _a$w;\r\n})();\r\nPrimitive.NAME = \"PRIMITIVE\";\n\nfunction localChangeType(inputObject, newType) {\r\n if (inputObject instanceof newType) {\r\n return inputObject;\r\n }\r\n const newObject = new newType();\r\n newObject.idBlock = inputObject.idBlock;\r\n newObject.lenBlock = inputObject.lenBlock;\r\n newObject.warnings = inputObject.warnings;\r\n newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;\r\n return newObject;\r\n}\r\nfunction localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {\r\n const incomingOffset = inputOffset;\r\n let returnObject = new BaseBlock({}, ValueBlock);\r\n const baseBlock = new LocalBaseBlock();\r\n if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {\r\n returnObject.error = baseBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);\r\n if (!intBuffer.length) {\r\n returnObject.error = \"Zero buffer length\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.idBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.idBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.idBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.idBlock.blockLength;\r\n resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.lenBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.lenBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.lenBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.lenBlock.blockLength;\r\n if (!returnObject.idBlock.isConstructed &&\r\n returnObject.lenBlock.isIndefiniteForm) {\r\n returnObject.error = \"Indefinite length form used for primitive encoding form\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let newASN1Type = BaseBlock;\r\n switch (returnObject.idBlock.tagClass) {\r\n case 1:\r\n if ((returnObject.idBlock.tagNumber >= 37) &&\r\n (returnObject.idBlock.isHexOnly === false)) {\r\n returnObject.error = \"UNIVERSAL 37 and upper tags are reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n switch (returnObject.idBlock.tagNumber) {\r\n case 0:\r\n if ((returnObject.idBlock.isConstructed) &&\r\n (returnObject.lenBlock.length > 0)) {\r\n returnObject.error = \"Type [UNIVERSAL 0] is reserved\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n newASN1Type = typeStore.EndOfContent;\r\n break;\r\n case 1:\r\n newASN1Type = typeStore.Boolean;\r\n break;\r\n case 2:\r\n newASN1Type = typeStore.Integer;\r\n break;\r\n case 3:\r\n newASN1Type = typeStore.BitString;\r\n break;\r\n case 4:\r\n newASN1Type = typeStore.OctetString;\r\n break;\r\n case 5:\r\n newASN1Type = typeStore.Null;\r\n break;\r\n case 6:\r\n newASN1Type = typeStore.ObjectIdentifier;\r\n break;\r\n case 10:\r\n newASN1Type = typeStore.Enumerated;\r\n break;\r\n case 12:\r\n newASN1Type = typeStore.Utf8String;\r\n break;\r\n case 13:\r\n newASN1Type = typeStore.RelativeObjectIdentifier;\r\n break;\r\n case 14:\r\n newASN1Type = typeStore.TIME;\r\n break;\r\n case 15:\r\n returnObject.error = \"[UNIVERSAL 15] is reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n case 16:\r\n newASN1Type = typeStore.Sequence;\r\n break;\r\n case 17:\r\n newASN1Type = typeStore.Set;\r\n break;\r\n case 18:\r\n newASN1Type = typeStore.NumericString;\r\n break;\r\n case 19:\r\n newASN1Type = typeStore.PrintableString;\r\n break;\r\n case 20:\r\n newASN1Type = typeStore.TeletexString;\r\n break;\r\n case 21:\r\n newASN1Type = typeStore.VideotexString;\r\n break;\r\n case 22:\r\n newASN1Type = typeStore.IA5String;\r\n break;\r\n case 23:\r\n newASN1Type = typeStore.UTCTime;\r\n break;\r\n case 24:\r\n newASN1Type = typeStore.GeneralizedTime;\r\n break;\r\n case 25:\r\n newASN1Type = typeStore.GraphicString;\r\n break;\r\n case 26:\r\n newASN1Type = typeStore.VisibleString;\r\n break;\r\n case 27:\r\n newASN1Type = typeStore.GeneralString;\r\n break;\r\n case 28:\r\n newASN1Type = typeStore.UniversalString;\r\n break;\r\n case 29:\r\n newASN1Type = typeStore.CharacterString;\r\n break;\r\n case 30:\r\n newASN1Type = typeStore.BmpString;\r\n break;\r\n case 31:\r\n newASN1Type = typeStore.DATE;\r\n break;\r\n case 32:\r\n newASN1Type = typeStore.TimeOfDay;\r\n break;\r\n case 33:\r\n newASN1Type = typeStore.DateTime;\r\n break;\r\n case 34:\r\n newASN1Type = typeStore.Duration;\r\n break;\r\n default: {\r\n const newObject = returnObject.idBlock.isConstructed\r\n ? new typeStore.Constructed()\r\n : new typeStore.Primitive();\r\n newObject.idBlock = returnObject.idBlock;\r\n newObject.lenBlock = returnObject.lenBlock;\r\n newObject.warnings = returnObject.warnings;\r\n returnObject = newObject;\r\n }\r\n }\r\n break;\r\n case 2:\r\n case 3:\r\n case 4:\r\n default: {\r\n newASN1Type = returnObject.idBlock.isConstructed\r\n ? typeStore.Constructed\r\n : typeStore.Primitive;\r\n }\r\n }\r\n returnObject = localChangeType(returnObject, newASN1Type);\r\n resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);\r\n returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);\r\n return {\r\n offset: resultOffset,\r\n result: returnObject\r\n };\r\n}\r\nfunction fromBER(inputBuffer) {\r\n if (!inputBuffer.byteLength) {\r\n const result = new BaseBlock({}, ValueBlock);\r\n result.error = \"Input buffer has zero length\";\r\n return {\r\n offset: -1,\r\n result\r\n };\r\n }\r\n return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);\r\n}\n\nfunction checkLen(indefiniteLength, length) {\r\n if (indefiniteLength) {\r\n return 1;\r\n }\r\n return length;\r\n}\r\nclass LocalConstructedValueBlock extends ValueBlock {\r\n constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.isIndefiniteForm = isIndefiniteForm;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (this.valueBeforeDecodeView.length === 0) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n let currentOffset = inputOffset;\r\n while (checkLen(this.isIndefiniteForm, inputLength) > 0) {\r\n const returnObject = localFromBER(view, currentOffset, inputLength);\r\n if (returnObject.offset === -1) {\r\n this.error = returnObject.result.error;\r\n this.warnings.concat(returnObject.result.warnings);\r\n return -1;\r\n }\r\n currentOffset = returnObject.offset;\r\n this.blockLength += returnObject.result.blockLength;\r\n inputLength -= returnObject.result.blockLength;\r\n this.value.push(returnObject.result);\r\n if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {\r\n break;\r\n }\r\n }\r\n if (this.isIndefiniteForm) {\r\n if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {\r\n this.value.pop();\r\n }\r\n else {\r\n this.warnings.push(\"No EndOfContent block encoded\");\r\n }\r\n }\r\n return currentOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n for (let i = 0; i < this.value.length; i++) {\r\n this.value[i].toBER(sizeOnly, _writer);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n value: [],\r\n };\r\n for (const value of this.value) {\r\n object.value.push(value.toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalConstructedValueBlock.NAME = \"ConstructedValueBlock\";\n\nvar _a$v;\r\nclass Constructed extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalConstructedValueBlock);\r\n this.idBlock.isConstructed = true;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n const values = [];\r\n for (const value of this.valueBlock.value) {\r\n values.push(value.toString(\"ascii\").split(\"\\n\").map(o => ` ${o}`).join(\"\\n\"));\r\n }\r\n const blockName = this.idBlock.tagClass === 3\r\n ? `[${this.idBlock.tagNumber}]`\r\n : this.constructor.NAME;\r\n return values.length\r\n ? `${blockName} :\\n${values.join(\"\\n\")}`\r\n : `${blockName} :`;\r\n }\r\n}\r\n_a$v = Constructed;\r\n(() => {\r\n typeStore.Constructed = _a$v;\r\n})();\r\nConstructed.NAME = \"CONSTRUCTED\";\n\nclass LocalEndOfContentValueBlock extends ValueBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n return inputOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return EMPTY_BUFFER;\r\n }\r\n}\r\nLocalEndOfContentValueBlock.override = \"EndOfContentValueBlock\";\n\nvar _a$u;\r\nclass EndOfContent extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalEndOfContentValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 0;\r\n }\r\n}\r\n_a$u = EndOfContent;\r\n(() => {\r\n typeStore.EndOfContent = _a$u;\r\n})();\r\nEndOfContent.NAME = END_OF_CONTENT_NAME;\n\nvar _a$t;\r\nclass Null extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, ValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 5;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (this.lenBlock.length > 0)\r\n this.warnings.push(\"Non-zero length of value block for Null type\");\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n this.blockLength += inputLength;\r\n if ((inputOffset + inputLength) > inputBuffer.byteLength) {\r\n this.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return -1;\r\n }\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuf = new ArrayBuffer(2);\r\n if (!sizeOnly) {\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] = 0x05;\r\n retView[1] = 0x00;\r\n }\r\n if (writer) {\r\n writer.write(retBuf);\r\n }\r\n return retBuf;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME}`;\r\n }\r\n}\r\n_a$t = Null;\r\n(() => {\r\n typeStore.Null = _a$t;\r\n})();\r\nNull.NAME = \"NULL\";\n\nclass LocalBooleanValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n if (parameters.valueHex) {\r\n this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex);\r\n }\r\n else {\r\n this.valueHexView = new Uint8Array(1);\r\n }\r\n if (value) {\r\n this.value = value;\r\n }\r\n }\r\n get value() {\r\n for (const octet of this.valueHexView) {\r\n if (octet > 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n set value(value) {\r\n this.valueHexView[0] = value ? 0xFF : 0x00;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (inputLength > 1)\r\n this.warnings.push(\"Boolean value encoded in more then 1 octet\");\r\n this.isHexOnly = true;\r\n pvutils.utilDecodeTC.call(this);\r\n this.blockLength = inputLength;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER() {\r\n return this.valueHexView.slice();\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalBooleanValueBlock.NAME = \"BooleanValueBlock\";\n\nvar _a$s;\r\nclass Boolean extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalBooleanValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 1;\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.getValue}`;\r\n }\r\n}\r\n_a$s = Boolean;\r\n(() => {\r\n typeStore.Boolean = _a$s;\r\n})();\r\nBoolean.NAME = \"BOOLEAN\";\n\nclass LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.isConstructed = isConstructed;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = 0;\r\n if (this.isConstructed) {\r\n this.isHexOnly = false;\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (let i = 0; i < this.value.length; i++) {\r\n const currentBlockName = this.value[i].constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== OCTET_STRING_NAME) {\r\n this.error = \"OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n }\r\n else {\r\n this.isHexOnly = true;\r\n resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n this.blockLength = inputLength;\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed)\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.byteLength)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalOctetStringValueBlock.NAME = \"OctetStringValueBlock\";\n\nvar _a$r;\r\nclass OctetString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalOctetStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 4;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n if (inputLength === 0) {\r\n if (this.idBlock.error.length === 0)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (this.lenBlock.error.length === 0)\r\n this.blockLength += this.lenBlock.blockLength;\r\n return inputOffset;\r\n }\r\n if (!this.valueBlock.isConstructed) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n const buf = view.subarray(inputOffset, inputOffset + inputLength);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === inputLength) {\r\n this.valueBlock.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`;\r\n }\r\n getValue() {\r\n if (!this.idBlock.isConstructed) {\r\n return this.valueBlock.valueHexView.slice().buffer;\r\n }\r\n const array = [];\r\n for (const content of this.valueBlock.value) {\r\n if (content instanceof OctetString) {\r\n array.push(content.valueBlock.valueHexView);\r\n }\r\n }\r\n return pvtsutils.BufferSourceConverter.concat(array);\r\n }\r\n}\r\n_a$r = OctetString;\r\n(() => {\r\n typeStore.OctetString = _a$r;\r\n})();\r\nOctetString.NAME = OCTET_STRING_NAME;\n\nclass LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.unusedBits = unusedBits;\r\n this.isConstructed = isConstructed;\r\n this.blockLength = this.valueHexView.byteLength;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n let resultOffset = -1;\r\n if (this.isConstructed) {\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (const value of this.value) {\r\n const currentBlockName = value.constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== BIT_STRING_NAME) {\r\n this.error = \"BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n const valueBlock = value.valueBlock;\r\n if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {\r\n this.error = \"Using of \\\"unused bits\\\" inside constructive BIT STRING allowed for least one only\";\r\n return -1;\r\n }\r\n this.unusedBits = valueBlock.unusedBits;\r\n }\r\n return resultOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.unusedBits = intBuffer[0];\r\n if (this.unusedBits > 7) {\r\n this.error = \"Unused bits for BitString must be in range 0-7\";\r\n return -1;\r\n }\r\n if (!this.unusedBits) {\r\n const buf = intBuffer.subarray(1);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {\r\n this.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n this.valueHexView = intBuffer.subarray(1);\r\n this.blockLength = intBuffer.length;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed) {\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength + 1);\r\n }\r\n if (!this.valueHexView.byteLength) {\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.length + 1);\r\n retView[0] = this.unusedBits;\r\n retView.set(this.valueHexView, 1);\r\n return retView.buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n unusedBits: this.unusedBits,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalBitStringValueBlock.NAME = \"BitStringValueBlock\";\n\nvar _a$q;\r\nclass BitString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalBitStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 3;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n else {\r\n const bits = [];\r\n const valueHex = this.valueBlock.valueHexView;\r\n for (const byte of valueHex) {\r\n bits.push(byte.toString(2).padStart(8, \"0\"));\r\n }\r\n const bitsStr = bits.join(\"\");\r\n return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;\r\n }\r\n }\r\n}\r\n_a$q = BitString;\r\n(() => {\r\n typeStore.BitString = _a$q;\r\n})();\r\nBitString.NAME = BIT_STRING_NAME;\n\nvar _a$p;\r\nfunction viewAdd(first, second) {\r\n const c = new Uint8Array([0]);\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n let firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value = 0;\r\n const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;\r\n let counter = 0;\r\n for (let i = max; i >= 0; i--, counter++) {\r\n switch (true) {\r\n case (counter < secondViewCopy.length):\r\n value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];\r\n break;\r\n default:\r\n value = firstViewCopy[firstViewCopyLength - counter] + c[0];\r\n }\r\n c[0] = value / 10;\r\n switch (true) {\r\n case (counter >= firstViewCopy.length):\r\n firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);\r\n break;\r\n default:\r\n firstViewCopy[firstViewCopyLength - counter] = value % 10;\r\n }\r\n }\r\n if (c[0] > 0)\r\n firstViewCopy = pvutils.utilConcatView(c, firstViewCopy);\r\n return firstViewCopy;\r\n}\r\nfunction power2(n) {\r\n if (n >= powers2.length) {\r\n for (let p = powers2.length; p <= n; p++) {\r\n const c = new Uint8Array([0]);\r\n let digits = (powers2[p - 1]).slice(0);\r\n for (let i = (digits.length - 1); i >= 0; i--) {\r\n const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);\r\n c[0] = newValue[0] / 10;\r\n digits[i] = newValue[0] % 10;\r\n }\r\n if (c[0] > 0)\r\n digits = pvutils.utilConcatView(c, digits);\r\n powers2.push(digits);\r\n }\r\n }\r\n return powers2[n];\r\n}\r\nfunction viewSub(first, second) {\r\n let b = 0;\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n const firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value;\r\n let counter = 0;\r\n for (let i = secondViewCopyLength; i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;\r\n switch (true) {\r\n case (value < 0):\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n break;\r\n default:\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n }\r\n }\r\n if (b > 0) {\r\n for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - b;\r\n if (value < 0) {\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n }\r\n else {\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n break;\r\n }\r\n }\r\n }\r\n return firstViewCopy.slice();\r\n}\r\nclass LocalIntegerValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n this._valueDec = 0;\r\n if (parameters.valueHex) {\r\n this.setValueHex();\r\n }\r\n if (value !== undefined) {\r\n this.valueDec = value;\r\n }\r\n }\r\n setValueHex() {\r\n if (this.valueHexView.length >= 4) {\r\n this.warnings.push(\"Too big Integer for decoding, hex only\");\r\n this.isHexOnly = true;\r\n this._valueDec = 0;\r\n }\r\n else {\r\n this.isHexOnly = false;\r\n if (this.valueHexView.length > 0) {\r\n this._valueDec = pvutils.utilDecodeTC.call(this);\r\n }\r\n }\r\n }\r\n set valueDec(v) {\r\n this._valueDec = v;\r\n this.isHexOnly = false;\r\n this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v));\r\n }\r\n get valueDec() {\r\n return this._valueDec;\r\n }\r\n fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {\r\n const offset = this.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (offset === -1)\r\n return offset;\r\n const view = this.valueHexView;\r\n if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {\r\n this.valueHexView = view.subarray(1);\r\n }\r\n else {\r\n if (expectedLength !== 0) {\r\n if (view.length < expectedLength) {\r\n if ((expectedLength - view.length) > 1)\r\n expectedLength = view.length + 1;\r\n this.valueHexView = view.subarray(expectedLength - view.length);\r\n }\r\n }\r\n }\r\n return offset;\r\n }\r\n toDER(sizeOnly = false) {\r\n const view = this.valueHexView;\r\n switch (true) {\r\n case ((view[0] & 0x80) !== 0):\r\n {\r\n const updatedView = new Uint8Array(this.valueHexView.length + 1);\r\n updatedView[0] = 0x00;\r\n updatedView.set(view, 1);\r\n this.valueHexView = updatedView;\r\n }\r\n break;\r\n case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):\r\n {\r\n this.valueHexView = this.valueHexView.subarray(1);\r\n }\r\n break;\r\n }\r\n return this.toBER(sizeOnly);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1) {\r\n return resultOffset;\r\n }\r\n this.setValueHex();\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.length)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n toString() {\r\n const firstBit = (this.valueHexView.length * 8) - 1;\r\n let digits = new Uint8Array((this.valueHexView.length * 8) / 3);\r\n let bitNumber = 0;\r\n let currentByte;\r\n const asn1View = this.valueHexView;\r\n let result = \"\";\r\n let flag = false;\r\n for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {\r\n currentByte = asn1View[byteNumber];\r\n for (let i = 0; i < 8; i++) {\r\n if ((currentByte & 1) === 1) {\r\n switch (bitNumber) {\r\n case firstBit:\r\n digits = viewSub(power2(bitNumber), digits);\r\n result = \"-\";\r\n break;\r\n default:\r\n digits = viewAdd(digits, power2(bitNumber));\r\n }\r\n }\r\n bitNumber++;\r\n currentByte >>= 1;\r\n }\r\n }\r\n for (let i = 0; i < digits.length; i++) {\r\n if (digits[i])\r\n flag = true;\r\n if (flag)\r\n result += digitsString.charAt(digits[i]);\r\n }\r\n if (flag === false)\r\n result += digitsString.charAt(0);\r\n return result;\r\n }\r\n}\r\n_a$p = LocalIntegerValueBlock;\r\nLocalIntegerValueBlock.NAME = \"IntegerValueBlock\";\r\n(() => {\r\n Object.defineProperty(_a$p.prototype, \"valueHex\", {\r\n set: function (v) {\r\n this.valueHexView = new Uint8Array(v);\r\n this.setValueHex();\r\n },\r\n get: function () {\r\n return this.valueHexView.slice().buffer;\r\n },\r\n });\r\n})();\n\nvar _a$o;\r\nclass Integer extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalIntegerValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 2;\r\n }\r\n toBigInt() {\r\n assertBigInt();\r\n return BigInt(this.valueBlock.toString());\r\n }\r\n static fromBigInt(value) {\r\n assertBigInt();\r\n const bigIntValue = BigInt(value);\r\n const writer = new ViewWriter();\r\n const hex = bigIntValue.toString(16).replace(/^-/, \"\");\r\n const view = new Uint8Array(pvtsutils.Convert.FromHex(hex));\r\n if (bigIntValue < 0) {\r\n const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));\r\n first[0] |= 0x80;\r\n const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`);\r\n const secondInt = firstInt + bigIntValue;\r\n const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16)));\r\n second[0] |= 0x80;\r\n writer.write(second);\r\n }\r\n else {\r\n if (view[0] & 0x80) {\r\n writer.write(new Uint8Array([0]));\r\n }\r\n writer.write(view);\r\n }\r\n const res = new Integer({\r\n valueHex: writer.final(),\r\n });\r\n return res;\r\n }\r\n convertToDER() {\r\n const integer = new Integer({ valueHex: this.valueBlock.valueHexView });\r\n integer.valueBlock.toDER();\r\n return integer;\r\n }\r\n convertFromDER() {\r\n return new Integer({\r\n valueHex: this.valueBlock.valueHexView[0] === 0\r\n ? this.valueBlock.valueHexView.subarray(1)\r\n : this.valueBlock.valueHexView,\r\n });\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;\r\n }\r\n}\r\n_a$o = Integer;\r\n(() => {\r\n typeStore.Integer = _a$o;\r\n})();\r\nInteger.NAME = \"INTEGER\";\n\nvar _a$n;\r\nclass Enumerated extends Integer {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 10;\r\n }\r\n}\r\n_a$n = Enumerated;\r\n(() => {\r\n typeStore.Enumerated = _a$n;\r\n})();\r\nEnumerated.NAME = \"ENUMERATED\";\n\nclass LocalSidValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n this.isFirstSid = isFirstSid;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++) {\r\n tempView[i] = this.valueHexView[i];\r\n }\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n set valueBigInt(value) {\r\n assertBigInt();\r\n let bits = BigInt(value).toString(2);\r\n while (bits.length % 7) {\r\n bits = \"0\" + bits;\r\n }\r\n const bytes = new Uint8Array(bits.length / 7);\r\n for (let i = 0; i < bytes.length; i++) {\r\n bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);\r\n }\r\n this.fromBER(bytes.buffer, 0, bytes.length);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n if (this.isFirstSid) {\r\n let sidValue = this.valueDec;\r\n if (this.valueDec <= 39)\r\n result = \"0.\";\r\n else {\r\n if (this.valueDec <= 79) {\r\n result = \"1.\";\r\n sidValue -= 40;\r\n }\r\n else {\r\n result = \"2.\";\r\n sidValue -= 80;\r\n }\r\n }\r\n result += sidValue.toString();\r\n }\r\n else\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n isFirstSid: this.isFirstSid,\r\n };\r\n }\r\n}\r\nLocalSidValueBlock.NAME = \"sidBlock\";\n\nclass LocalObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n if (this.value.length === 0)\r\n sidBlock.isFirstSid = true;\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n let flag = false;\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n if (flag) {\r\n const sidBlock = this.value[0];\r\n let plus = 0;\r\n switch (sidBlock.valueDec) {\r\n case 0:\r\n break;\r\n case 1:\r\n plus = 40;\r\n break;\r\n case 2:\r\n plus = 80;\r\n break;\r\n default:\r\n this.value = [];\r\n return;\r\n }\r\n const parsedSID = parseInt(sid, 10);\r\n if (isNaN(parsedSID))\r\n return;\r\n sidBlock.valueDec = parsedSID + plus;\r\n flag = false;\r\n }\r\n else {\r\n const sidBlock = new LocalSidValueBlock();\r\n if (sid > Number.MAX_SAFE_INTEGER) {\r\n assertBigInt();\r\n const sidValue = BigInt(sid);\r\n sidBlock.valueBigInt = sidValue;\r\n }\r\n else {\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return;\r\n }\r\n if (!this.value.length) {\r\n sidBlock.isFirstSid = true;\r\n flag = true;\r\n }\r\n this.value.push(sidBlock);\r\n }\r\n } while (pos2 !== -1);\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n if (this.value[i].isFirstSid)\r\n result = `2.{${sidStr} - 80}`;\r\n else\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++) {\r\n object.sidArray.push(this.value[i].toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalObjectIdentifierValueBlock.NAME = \"ObjectIdentifierValueBlock\";\n\nvar _a$m;\r\nclass ObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 6;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$m = ObjectIdentifier;\r\n(() => {\r\n typeStore.ObjectIdentifier = _a$m;\r\n})();\r\nObjectIdentifier.NAME = \"OBJECT IDENTIFIER\";\n\nclass LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ valueDec = 0, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (inputLength === 0)\r\n return inputOffset;\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength))\r\n return -1;\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++)\r\n tempView[i] = this.valueHexView[i];\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView.buffer;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n}\r\nLocalRelativeSidValueBlock.NAME = \"relativeSidBlock\";\n\nclass LocalRelativeObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return true;\r\n this.value.push(sidBlock);\r\n } while (pos2 !== -1);\r\n return true;\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++)\r\n object.sidArray.push(this.value[i].toJSON());\r\n return object;\r\n }\r\n}\r\nLocalRelativeObjectIdentifierValueBlock.NAME = \"RelativeObjectIdentifierValueBlock\";\n\nvar _a$l;\r\nclass RelativeObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalRelativeObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 13;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$l = RelativeObjectIdentifier;\r\n(() => {\r\n typeStore.RelativeObjectIdentifier = _a$l;\r\n})();\r\nRelativeObjectIdentifier.NAME = \"RelativeObjectIdentifier\";\n\nvar _a$k;\r\nclass Sequence extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 16;\r\n }\r\n}\r\n_a$k = Sequence;\r\n(() => {\r\n typeStore.Sequence = _a$k;\r\n})();\r\nSequence.NAME = \"SEQUENCE\";\n\nvar _a$j;\r\nclass Set extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 17;\r\n }\r\n}\r\n_a$j = Set;\r\n(() => {\r\n typeStore.Set = _a$j;\r\n})();\r\nSet.NAME = \"SET\";\n\nclass LocalStringValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = true;\r\n this.value = EMPTY_STRING;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalStringValueBlock.NAME = \"StringValueBlock\";\n\nclass LocalSimpleStringValueBlock extends LocalStringValueBlock {\r\n}\r\nLocalSimpleStringValueBlock.NAME = \"SimpleStringValueBlock\";\n\nclass LocalSimpleStringBlock extends BaseStringBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters, LocalSimpleStringValueBlock);\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLen = inputString.length;\r\n const view = this.valueBlock.valueHexView = new Uint8Array(strLen);\r\n for (let i = 0; i < strLen; i++)\r\n view[i] = inputString.charCodeAt(i);\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalSimpleStringBlock.NAME = \"SIMPLE STRING\";\n\nclass LocalUtf8StringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n try {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer);\r\n }\r\n catch (ex) {\r\n this.warnings.push(`Error during \"decodeURIComponent\": ${ex}, using raw string`);\r\n this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer);\r\n }\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString));\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUtf8StringValueBlock.NAME = \"Utf8StringValueBlock\";\n\nvar _a$i;\r\nclass Utf8String extends LocalUtf8StringValueBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 12;\r\n }\r\n}\r\n_a$i = Utf8String;\r\n(() => {\r\n typeStore.Utf8String = _a$i;\r\n})();\r\nUtf8String.NAME = \"UTF8String\";\n\nclass LocalBmpStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer);\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.value = inputString;\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString));\r\n }\r\n}\r\nLocalBmpStringValueBlock.NAME = \"BmpStringValueBlock\";\n\nvar _a$h;\r\nclass BmpString extends LocalBmpStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 30;\r\n }\r\n}\r\n_a$h = BmpString;\r\n(() => {\r\n typeStore.BmpString = _a$h;\r\n})();\r\nBmpString.NAME = \"BMPString\";\n\nclass LocalUniversalStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);\r\n const valueView = new Uint8Array(copyBuffer);\r\n for (let i = 0; i < valueView.length; i += 4) {\r\n valueView[i] = valueView[i + 3];\r\n valueView[i + 1] = valueView[i + 2];\r\n valueView[i + 2] = 0x00;\r\n valueView[i + 3] = 0x00;\r\n }\r\n this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLength = inputString.length;\r\n const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);\r\n for (let i = 0; i < strLength; i++) {\r\n const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8);\r\n const codeView = new Uint8Array(codeBuf);\r\n if (codeView.length > 4)\r\n continue;\r\n const dif = 4 - codeView.length;\r\n for (let j = (codeView.length - 1); j >= 0; j--)\r\n valueHexView[i * 4 + j + dif] = codeView[j];\r\n }\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUniversalStringValueBlock.NAME = \"UniversalStringValueBlock\";\n\nvar _a$g;\r\nclass UniversalString extends LocalUniversalStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 28;\r\n }\r\n}\r\n_a$g = UniversalString;\r\n(() => {\r\n typeStore.UniversalString = _a$g;\r\n})();\r\nUniversalString.NAME = \"UniversalString\";\n\nvar _a$f;\r\nclass NumericString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 18;\r\n }\r\n}\r\n_a$f = NumericString;\r\n(() => {\r\n typeStore.NumericString = _a$f;\r\n})();\r\nNumericString.NAME = \"NumericString\";\n\nvar _a$e;\r\nclass PrintableString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 19;\r\n }\r\n}\r\n_a$e = PrintableString;\r\n(() => {\r\n typeStore.PrintableString = _a$e;\r\n})();\r\nPrintableString.NAME = \"PrintableString\";\n\nvar _a$d;\r\nclass TeletexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 20;\r\n }\r\n}\r\n_a$d = TeletexString;\r\n(() => {\r\n typeStore.TeletexString = _a$d;\r\n})();\r\nTeletexString.NAME = \"TeletexString\";\n\nvar _a$c;\r\nclass VideotexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 21;\r\n }\r\n}\r\n_a$c = VideotexString;\r\n(() => {\r\n typeStore.VideotexString = _a$c;\r\n})();\r\nVideotexString.NAME = \"VideotexString\";\n\nvar _a$b;\r\nclass IA5String extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 22;\r\n }\r\n}\r\n_a$b = IA5String;\r\n(() => {\r\n typeStore.IA5String = _a$b;\r\n})();\r\nIA5String.NAME = \"IA5String\";\n\nvar _a$a;\r\nclass GraphicString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 25;\r\n }\r\n}\r\n_a$a = GraphicString;\r\n(() => {\r\n typeStore.GraphicString = _a$a;\r\n})();\r\nGraphicString.NAME = \"GraphicString\";\n\nvar _a$9;\r\nclass VisibleString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 26;\r\n }\r\n}\r\n_a$9 = VisibleString;\r\n(() => {\r\n typeStore.VisibleString = _a$9;\r\n})();\r\nVisibleString.NAME = \"VisibleString\";\n\nvar _a$8;\r\nclass GeneralString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 27;\r\n }\r\n}\r\n_a$8 = GeneralString;\r\n(() => {\r\n typeStore.GeneralString = _a$8;\r\n})();\r\nGeneralString.NAME = \"GeneralString\";\n\nvar _a$7;\r\nclass CharacterString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 29;\r\n }\r\n}\r\n_a$7 = CharacterString;\r\n(() => {\r\n typeStore.CharacterString = _a$7;\r\n})();\r\nCharacterString.NAME = \"CharacterString\";\n\nvar _a$6;\r\nclass UTCTime extends VisibleString {\r\n constructor({ value, valueDate, ...parameters } = {}) {\r\n super(parameters);\r\n this.year = 0;\r\n this.month = 0;\r\n this.day = 0;\r\n this.hour = 0;\r\n this.minute = 0;\r\n this.second = 0;\r\n if (value) {\r\n this.fromString(value);\r\n this.valueBlock.valueHexView = new Uint8Array(value.length);\r\n for (let i = 0; i < value.length; i++)\r\n this.valueBlock.valueHexView[i] = value.charCodeAt(i);\r\n }\r\n if (valueDate) {\r\n this.fromDate(valueDate);\r\n this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());\r\n }\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 23;\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)));\r\n }\r\n toBuffer() {\r\n const str = this.toString();\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buffer);\r\n for (let i = 0; i < str.length; i++)\r\n view[i] = str.charCodeAt(i);\r\n return buffer;\r\n }\r\n fromDate(inputDate) {\r\n this.year = inputDate.getUTCFullYear();\r\n this.month = inputDate.getUTCMonth() + 1;\r\n this.day = inputDate.getUTCDate();\r\n this.hour = inputDate.getUTCHours();\r\n this.minute = inputDate.getUTCMinutes();\r\n this.second = inputDate.getUTCSeconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));\r\n }\r\n fromString(inputString) {\r\n const parser = /(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/ig;\r\n const parserArray = parser.exec(inputString);\r\n if (parserArray === null) {\r\n this.error = \"Wrong input string for conversion\";\r\n return;\r\n }\r\n const year = parseInt(parserArray[1], 10);\r\n if (year >= 50)\r\n this.year = 1900 + year;\r\n else\r\n this.year = 2000 + year;\r\n this.month = parseInt(parserArray[2], 10);\r\n this.day = parseInt(parserArray[3], 10);\r\n this.hour = parseInt(parserArray[4], 10);\r\n this.minute = parseInt(parserArray[5], 10);\r\n this.second = parseInt(parserArray[6], 10);\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = new Array(7);\r\n outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);\r\n outputArray[1] = pvutils.padNumber(this.month, 2);\r\n outputArray[2] = pvutils.padNumber(this.day, 2);\r\n outputArray[3] = pvutils.padNumber(this.hour, 2);\r\n outputArray[4] = pvutils.padNumber(this.minute, 2);\r\n outputArray[5] = pvutils.padNumber(this.second, 2);\r\n outputArray[6] = \"Z\";\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n year: this.year,\r\n month: this.month,\r\n day: this.day,\r\n hour: this.hour,\r\n minute: this.minute,\r\n second: this.second,\r\n };\r\n }\r\n}\r\n_a$6 = UTCTime;\r\n(() => {\r\n typeStore.UTCTime = _a$6;\r\n})();\r\nUTCTime.NAME = \"UTCTime\";\n\nvar _a$5;\r\nclass GeneralizedTime extends UTCTime {\r\n constructor(parameters = {}) {\r\n var _b;\r\n super(parameters);\r\n (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 24;\r\n }\r\n fromDate(inputDate) {\r\n super.fromDate(inputDate);\r\n this.millisecond = inputDate.getUTCMilliseconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));\r\n }\r\n fromString(inputString) {\r\n let isUTC = false;\r\n let timeString = \"\";\r\n let dateTimeString = \"\";\r\n let fractionPart = 0;\r\n let parser;\r\n let hourDifference = 0;\r\n let minuteDifference = 0;\r\n if (inputString[inputString.length - 1] === \"Z\") {\r\n timeString = inputString.substring(0, inputString.length - 1);\r\n isUTC = true;\r\n }\r\n else {\r\n const number = new Number(inputString[inputString.length - 1]);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n timeString = inputString;\r\n }\r\n if (isUTC) {\r\n if (timeString.indexOf(\"+\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n if (timeString.indexOf(\"-\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n else {\r\n let multiplier = 1;\r\n let differencePosition = timeString.indexOf(\"+\");\r\n let differenceString = \"\";\r\n if (differencePosition === -1) {\r\n differencePosition = timeString.indexOf(\"-\");\r\n multiplier = -1;\r\n }\r\n if (differencePosition !== -1) {\r\n differenceString = timeString.substring(differencePosition + 1);\r\n timeString = timeString.substring(0, differencePosition);\r\n if ((differenceString.length !== 2) && (differenceString.length !== 4))\r\n throw new Error(\"Wrong input string for conversion\");\r\n let number = parseInt(differenceString.substring(0, 2), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n hourDifference = multiplier * number;\r\n if (differenceString.length === 4) {\r\n number = parseInt(differenceString.substring(2, 4), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n minuteDifference = multiplier * number;\r\n }\r\n }\r\n }\r\n let fractionPointPosition = timeString.indexOf(\".\");\r\n if (fractionPointPosition === -1)\r\n fractionPointPosition = timeString.indexOf(\",\");\r\n if (fractionPointPosition !== -1) {\r\n const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);\r\n if (isNaN(fractionPartCheck.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n fractionPart = fractionPartCheck.valueOf();\r\n dateTimeString = timeString.substring(0, fractionPointPosition);\r\n }\r\n else\r\n dateTimeString = timeString;\r\n switch (true) {\r\n case (dateTimeString.length === 8):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n break;\r\n case (dateTimeString.length === 10):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.minute = Math.floor(fractionResult);\r\n fractionResult = 60 * (fractionResult - this.minute);\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 12):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 14):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n const fractionResult = 1000 * fractionPart;\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n const parserArray = parser.exec(dateTimeString);\r\n if (parserArray === null)\r\n throw new Error(\"Wrong input string for conversion\");\r\n for (let j = 1; j < parserArray.length; j++) {\r\n switch (j) {\r\n case 1:\r\n this.year = parseInt(parserArray[j], 10);\r\n break;\r\n case 2:\r\n this.month = parseInt(parserArray[j], 10);\r\n break;\r\n case 3:\r\n this.day = parseInt(parserArray[j], 10);\r\n break;\r\n case 4:\r\n this.hour = parseInt(parserArray[j], 10) + hourDifference;\r\n break;\r\n case 5:\r\n this.minute = parseInt(parserArray[j], 10) + minuteDifference;\r\n break;\r\n case 6:\r\n this.second = parseInt(parserArray[j], 10);\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n }\r\n if (isUTC === false) {\r\n const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\r\n this.year = tempDate.getUTCFullYear();\r\n this.month = tempDate.getUTCMonth();\r\n this.day = tempDate.getUTCDay();\r\n this.hour = tempDate.getUTCHours();\r\n this.minute = tempDate.getUTCMinutes();\r\n this.second = tempDate.getUTCSeconds();\r\n this.millisecond = tempDate.getUTCMilliseconds();\r\n }\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = [];\r\n outputArray.push(pvutils.padNumber(this.year, 4));\r\n outputArray.push(pvutils.padNumber(this.month, 2));\r\n outputArray.push(pvutils.padNumber(this.day, 2));\r\n outputArray.push(pvutils.padNumber(this.hour, 2));\r\n outputArray.push(pvutils.padNumber(this.minute, 2));\r\n outputArray.push(pvutils.padNumber(this.second, 2));\r\n if (this.millisecond !== 0) {\r\n outputArray.push(\".\");\r\n outputArray.push(pvutils.padNumber(this.millisecond, 3));\r\n }\r\n outputArray.push(\"Z\");\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n millisecond: this.millisecond,\r\n };\r\n }\r\n}\r\n_a$5 = GeneralizedTime;\r\n(() => {\r\n typeStore.GeneralizedTime = _a$5;\r\n})();\r\nGeneralizedTime.NAME = \"GeneralizedTime\";\n\nvar _a$4;\r\nclass DATE extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 31;\r\n }\r\n}\r\n_a$4 = DATE;\r\n(() => {\r\n typeStore.DATE = _a$4;\r\n})();\r\nDATE.NAME = \"DATE\";\n\nvar _a$3;\r\nclass TimeOfDay extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 32;\r\n }\r\n}\r\n_a$3 = TimeOfDay;\r\n(() => {\r\n typeStore.TimeOfDay = _a$3;\r\n})();\r\nTimeOfDay.NAME = \"TimeOfDay\";\n\nvar _a$2;\r\nclass DateTime extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 33;\r\n }\r\n}\r\n_a$2 = DateTime;\r\n(() => {\r\n typeStore.DateTime = _a$2;\r\n})();\r\nDateTime.NAME = \"DateTime\";\n\nvar _a$1;\r\nclass Duration extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 34;\r\n }\r\n}\r\n_a$1 = Duration;\r\n(() => {\r\n typeStore.Duration = _a$1;\r\n})();\r\nDuration.NAME = \"Duration\";\n\nvar _a;\r\nclass TIME extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 14;\r\n }\r\n}\r\n_a = TIME;\r\n(() => {\r\n typeStore.TIME = _a;\r\n})();\r\nTIME.NAME = \"TIME\";\n\nclass Any {\r\n constructor({ name = EMPTY_STRING, optional = false, } = {}) {\r\n this.name = name;\r\n this.optional = optional;\r\n }\r\n}\n\nclass Choice extends Any {\r\n constructor({ value = [], ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n }\r\n}\n\nclass Repeated extends Any {\r\n constructor({ value = new Any(), local = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.local = local;\r\n }\r\n}\n\nclass RawData {\r\n constructor({ data = EMPTY_VIEW } = {}) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data);\r\n }\r\n get data() {\r\n return this.dataView.slice().buffer;\r\n }\r\n set data(value) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const endLength = inputOffset + inputLength;\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);\r\n return endLength;\r\n }\r\n toBER(sizeOnly) {\r\n return this.dataView.slice().buffer;\r\n }\r\n}\n\nfunction compareSchema(root, inputData, inputSchema) {\r\n if (inputSchema instanceof Choice) {\r\n for (let j = 0; j < inputSchema.value.length; j++) {\r\n const result = compareSchema(root, inputData, inputSchema.value[j]);\r\n if (result.verified) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n }\r\n {\r\n const _result = {\r\n verified: false,\r\n result: {\r\n error: \"Wrong values for Choice type\"\r\n },\r\n };\r\n if (inputSchema.hasOwnProperty(NAME))\r\n _result.name = inputSchema.name;\r\n return _result;\r\n }\r\n }\r\n if (inputSchema instanceof Any) {\r\n if (inputSchema.hasOwnProperty(NAME))\r\n root[inputSchema.name] = inputData;\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((root instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong root object\" }\r\n };\r\n }\r\n if ((inputData instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 data\" }\r\n };\r\n }\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((ID_BLOCK in inputSchema) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((FROM_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((TO_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const encodedId = inputSchema.idBlock.toBER(false);\r\n if (encodedId.byteLength === 0) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error encoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);\r\n if (decodedOffset === -1) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error decoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (!(IS_HEX_ONLY in inputSchema.idBlock)) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly) {\r\n if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const schemaView = inputSchema.idBlock.valueHexView;\r\n const asn1View = inputData.idBlock.valueHexView;\r\n if (schemaView.length !== asn1View.length) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < schemaView.length; i++) {\r\n if (schemaView[i] !== asn1View[1]) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n }\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n root[inputSchema.name] = inputData;\r\n }\r\n if (inputSchema instanceof typeStore.Constructed) {\r\n let admission = 0;\r\n let result = {\r\n verified: false,\r\n result: {\r\n error: \"Unknown error\",\r\n }\r\n };\r\n let maxLength = inputSchema.valueBlock.value.length;\r\n if (maxLength > 0) {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n maxLength = inputData.valueBlock.value.length;\r\n }\r\n }\r\n if (maxLength === 0) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((inputData.valueBlock.value.length === 0) &&\r\n (inputSchema.valueBlock.value.length !== 0)) {\r\n let _optional = true;\r\n for (let i = 0; i < inputSchema.valueBlock.value.length; i++)\r\n _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);\r\n if (_optional) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n root.error = \"Inconsistent object length\";\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < maxLength; i++) {\r\n if ((i - admission) >= inputData.valueBlock.value.length) {\r\n if (inputSchema.valueBlock.value[i].optional === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n root.error = \"Inconsistent length between ASN.1 data and schema\";\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n }\r\n else {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[0].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {\r\n let arrayRoot = {};\r\n if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))\r\n arrayRoot = inputData;\r\n else\r\n arrayRoot = root;\r\n if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === \"undefined\")\r\n arrayRoot[inputSchema.valueBlock.value[0].name] = [];\r\n arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);\r\n }\r\n }\r\n else {\r\n result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[i].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (result.verified === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.primitiveSchema &&\r\n (VALUE_HEX_VIEW in inputData.valueBlock)) {\r\n const asn1 = localFromBER(inputData.valueBlock.valueHexView);\r\n if (asn1.offset === -1) {\r\n const _result = {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return compareSchema(root, asn1.result, inputSchema.primitiveSchema);\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n}\r\nfunction verifySchema(inputBuffer, inputSchema) {\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema type\" }\r\n };\r\n }\r\n const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n if (asn1.offset === -1) {\r\n return {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n }\r\n return compareSchema(asn1.result, asn1.result, inputSchema);\r\n}\n\nexport { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema };\n","import { CodeError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { CodeError } from '@libp2p/interface';\nimport { pbkdf2Async } from '@noble/hashes/pbkdf2';\nimport { sha512 } from '@noble/hashes/sha512';\nimport * as asn1js from 'asn1js';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport randomBytes from '../random-bytes.js';\nimport webcrypto from '../webcrypto.js';\nimport { unmarshalRsaPrivateKey } from './rsa-class.js';\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: uint8ArrayToString(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: uint8ArrayToString(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: uint8ArrayToString(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: uint8ArrayToString(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: uint8ArrayToString(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: uint8ArrayToString(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: uint8ArrayToString(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: uint8ArrayToString(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nexport async function exportToPem(privateKey, password) {\n const crypto = webcrypto.get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js.Sequence({\n value: [\n // version (0)\n new asn1js.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // PrivateKey\n new asn1js.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = randomBytes(SALT_LENGTH);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = randomBytes(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js.Sequence({\n value: [\n // salt\n new asn1js.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js.Integer({ value: ITERATIONS }),\n // key length\n new asn1js.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js.Sequence({\n value: [\n // aes256-CBC\n new asn1js.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...uint8ArrayToString(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nexport async function importFromPem(pem, password) {\n const crypto = webcrypto.get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await pbkdf2Async(sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = uint8ArrayFromString(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return unmarshalRsaPrivateKey(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as pbm from './keys.js';\nimport * as crypto from './rsa.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nexport class RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.utils.jwkToPkix(this._key);\n }\n get bytes() {\n return pbm.PublicKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nexport class RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return crypto.getRandomValues(16);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return crypto.utils.jwkToPkcs1(this._key);\n }\n get bytes() {\n return pbm.PrivateKey.encode({\n Type: pbm.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return crypto.utils.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport async function unmarshalRsaPrivateKey(bytes) {\n const jwk = crypto.utils.pkcs1ToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport function unmarshalRsaPublicKey(bytes) {\n const jwk = crypto.utils.pkixToJwk(bytes);\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nexport async function fromJwk(jwk) {\n if (crypto.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nexport async function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await crypto.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport { validateBasic, wNAF, pippenger, } from './curve.js';\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, memoized, abool } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n return `${ut.numberToHexUnpadded(tag)}${lenLen}${len}${data}`;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected assertion');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('Invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const seq = `${tlv.encode(0x02, int.encode(sig.r))}${tlv.encode(0x02, int.encode(sig.s))}`;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = mod.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n ut.aInRange('scalar', sc, _0n, CURVE.n);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (sc === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, sc);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange(`num < 2^${CURVE.nBitLength}`, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n validateSigVerOpts(opts);\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { inRange, aInRange, bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { CodeError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { isPromise } from '../util.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n return secp.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nexport function compressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressPublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validatePrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nexport function validatePublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nexport function computePublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map","import { CodeError } from '@libp2p/interface';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { isPromise } from '../util.js';\nimport { exporter } from './exporter.js';\nimport * as keysProtobuf from './keys.js';\nimport * as crypto from './secp256k1.js';\nexport class Secp256k1PublicKey {\n _key;\n constructor(key) {\n crypto.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return crypto.compressPublicKey(this._key);\n }\n get bytes() {\n return keysProtobuf.PublicKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n async hash() {\n const p = sha256.digest(this.bytes);\n let bytes;\n if (isPromise(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nexport class Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? crypto.computePublicKey(key);\n crypto.validatePrivateKey(this._key);\n crypto.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return crypto.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return keysProtobuf.PrivateKey.encode({\n Type: keysProtobuf.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return uint8ArrayEquals(this.bytes, key.bytes);\n }\n hash() {\n const p = sha256.digest(this.bytes);\n if (isPromise(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return uint8ArrayToString(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return exporter(this.bytes, password);\n }\n else {\n throw new CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nexport async function generateKeyPair() {\n const privateKeyBytes = crypto.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map","/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { CodeError } from '@libp2p/interface';\nimport * as Ed25519 from './ed25519-class.js';\nimport generateEphemeralKeyPair from './ephemeral-keys.js';\nimport { importer } from './importer.js';\nimport { keyStretcher } from './key-stretcher.js';\nimport * as keysPBM from './keys.js';\nimport * as RSA from './rsa-class.js';\nimport { importFromPem } from './rsa-utils.js';\nimport * as Secp256k1 from './secp256k1-class.js';\nexport { keyStretcher };\nexport { generateEphemeralKeyPair };\nexport { keysPBM };\nexport { RsaPrivateKey, RsaPublicKey, MAX_RSA_KEY_SIZE } from './rsa-class.js';\nexport { Ed25519PrivateKey, Ed25519PublicKey } from './ed25519-class.js';\nexport { Secp256k1PrivateKey, Secp256k1PublicKey } from './secp256k1-class.js';\nexport const supportedKeys = {\n rsa: RSA,\n ed25519: Ed25519,\n secp256k1: Secp256k1\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nexport async function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nexport async function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return Ed25519.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function unmarshalPublicKey(buf) {\n const decoded = keysPBM.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport async function unmarshalPrivateKey(buf) {\n const decoded = keysPBM.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case keysPBM.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case keysPBM.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case keysPBM.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nexport async function importKey(encryptedKey, password) {\n try {\n const key = await importer(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return importFromPem(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies');\nexport * from './connection/index.js';\nexport * from './connection-encrypter/index.js';\nexport * from './connection-gater/index.js';\nexport * from './content-routing/index.js';\nexport * from './keys/index.js';\nexport * from './metrics/index.js';\nexport * from './peer-discovery/index.js';\nexport * from './peer-id/index.js';\nexport * from './peer-info/index.js';\nexport * from './peer-routing/index.js';\nexport * from './peer-store/index.js';\nexport * from './peer-store/tags.js';\nexport * from './pubsub/index.js';\nexport * from './record/index.js';\nexport * from './stream-handler/index.js';\nexport * from './stream-muxer/index.js';\nexport * from './topology/index.js';\nexport * from './transport/index.js';\nexport * from './errors.js';\nexport * from './event-target.js';\nexport * from './events.js';\nexport * from './startable.js';\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { CodeError } from '@libp2p/interface';\nimport { peerIdSymbol } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { bases } from 'multiformats/basics';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = identity.digest(uint8ArrayFromString(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other);\n }\n return other.toString() === this.toString();\n }\n}\nexport function createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nexport function peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nexport function peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = Digest.decode(base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nexport function peerIdFromBytes(buf) {\n try {\n const multihash = Digest.decode(buf);\n if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nexport function peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nexport async function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: Digest.create(identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map","/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code, name) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = name ?? 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal(promise, signal, opts) {\n if (signal == null) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName));\n }\n let listener;\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName);\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error);\n };\n signal.addEventListener('abort', listener);\n })\n ]);\n }\n finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\nimport deferred, {} from 'p-defer';\nimport { raceSignal } from 'race-signal';\nclass QueuelessPushable {\n readNext;\n haveNext;\n ended;\n nextResult;\n constructor() {\n this.ended = false;\n this.readNext = deferred();\n this.haveNext = deferred();\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n async next() {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise;\n }\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined');\n }\n const nextResult = this.nextResult;\n this.nextResult = undefined;\n // signal to the supplier that we read the value\n this.readNext.resolve();\n this.readNext = deferred();\n return nextResult;\n }\n async throw(err) {\n this.ended = true;\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => { });\n this.haveNext.reject(err);\n }\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n async return() {\n const result = {\n done: true,\n value: undefined\n };\n await this._push(undefined);\n return result;\n }\n async push(value, options) {\n await this._push(value, options);\n }\n async end(err, options) {\n if (err != null) {\n await this.throw(err);\n }\n else {\n // abortable return\n await this._push(undefined, options);\n }\n }\n async _push(value, options) {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable');\n }\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise;\n }\n if (value != null) {\n this.nextResult = { done: false, value };\n }\n else {\n this.ended = true;\n this.nextResult = { done: true, value: undefined };\n }\n // let the consumer know we have a new value\n this.haveNext.resolve();\n this.haveNext = deferred();\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(this.readNext.promise, options?.signal, options);\n }\n}\nexport function queuelessPushable() {\n return new QueuelessPushable();\n}\n//# sourceMappingURL=index.js.map","/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\nimport { queuelessPushable } from 'it-queueless-pushable';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { UnexpectedEOFError } from './errors.js';\n/**\n * @deprecated This will not be exported in a future release\n */\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * @deprecated This will not be exported in a future release\n */\nexport class AbortError extends CodeError {\n type;\n constructor(message) {\n super(message, 'ABORT_ERR');\n this.type = 'aborted';\n this.name = 'AbortError';\n }\n}\nexport function byteStream(duplex, opts) {\n const write = queuelessPushable();\n duplex.sink(write).catch(async (err) => {\n await write.end(err);\n });\n duplex.sink = async (source) => {\n for await (const buf of source) {\n await write.push(buf);\n }\n await write.end();\n };\n let source = duplex.source;\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]();\n }\n else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]();\n }\n const readBuffer = new Uint8ArrayList();\n const W = {\n read: async (bytes, options) => {\n options?.signal?.throwIfAborted();\n let listener;\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'));\n };\n options?.signal?.addEventListener('abort', listener);\n });\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n return new Uint8ArrayList();\n }\n return value;\n }\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n throw new UnexpectedEOFError('unexpected end of input');\n }\n readBuffer.append(value);\n }\n const buf = readBuffer.sublist(0, bytes);\n readBuffer.consume(bytes);\n return buf;\n }\n finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener);\n }\n }\n },\n write: async (data, options) => {\n options?.signal?.throwIfAborted();\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options);\n }\n else {\n await write.push(data.subarray(), options);\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source;\n duplex.source = (async function* () {\n if (opts?.yieldBytes === false) {\n yield readBuffer;\n }\n else {\n yield* readBuffer;\n }\n yield* originalStream;\n }());\n }\n return duplex;\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\nimport { byteStream } from 'it-byte-stream';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError } from './errors.js';\nexport function lpStream(duplex, opts = {}) {\n const bytes = byteStream(duplex, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? varint.decode;\n const encodeLength = opts?.lengthEncoder ?? varint.encode;\n const W = {\n read: async (options) => {\n let dataLength = -1;\n const lengthBuffer = new Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options));\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new InvalidDataLengthLengthError('message length length too long');\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new InvalidDataLengthError('message length too long');\n }\n return bytes.read(dataLength, options);\n },\n write: async (data, options) => {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n writeV: async (data, options) => {\n const list = new Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap: () => {\n return bytes.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","import defer from 'p-defer';\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair() {\n const deferred = defer();\n let piped = false;\n return {\n sink: async (source) => {\n if (piped) {\n throw new Error('already piped');\n }\n piped = true;\n deferred.resolve(source);\n },\n source: (async function* () {\n const source = await deferred.promise;\n yield* source;\n }())\n };\n}\n//# sourceMappingURL=index.js.map","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535;\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16;\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);\n//# sourceMappingURL=constants.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { bool as abool, bytes as abytes, number as anumber } from './_assert.js';\nimport { checkOpts, clean, copyBytes, u32 } from './utils.js';\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length, k, sigma;\n if (l === 32) {\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push((nonce = copyBytes(nonce)));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n//# sourceMappingURL=_arx.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, toBytes } from './utils.js';\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 {\n constructor(key) {\n this.blockLen = 16;\n this.outputLen = 16;\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.pos = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n//# sourceMappingURL=_poly1305.js.map","// prettier-ignore\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\nimport { poly1305 } from './_poly1305.js';\nimport { clean, createView, equalBytes, setBigUint64, wrapCipher, } from './utils.js';\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(s, k, i, o32) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00;\n o32[oi++] = x01;\n o32[oi++] = x02;\n o32[oi++] = x03;\n o32[oi++] = x12;\n o32[oi++] = x13;\n o32[oi++] = x14;\n o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left)\n h.update(ZEROS16.subarray(left));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, data, AAD) {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n clean(authKey, num);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n }\n else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n }\n else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));\n//# sourceMappingURL=chacha.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { toBytes } from './utils.js';\nimport { hmac } from './hmac.js';\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nexport function extract(hash, ikm, salt) {\n assertHash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nexport function expand(hash, prk, info, length = 32) {\n assertHash(hash);\n assertNumber(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","import { pureJsCrypto } from './js.js';\nexport const defaultCrypto = pureJsCrypto;\n//# sourceMappingURL=index.browser.js.map","import { chacha20poly1305 } from '@noble/ciphers/chacha';\nimport { x25519 } from '@noble/curves/ed25519';\nimport { extract, expand } from '@noble/hashes/hkdf';\nimport { sha256 } from '@noble/hashes/sha256';\nexport const pureJsCrypto = {\n hashSHA256(data) {\n return sha256(data.subarray());\n },\n getHKDF(ck, ikm) {\n const prk = extract(sha256, ikm, ck);\n const okmU8Array = expand(sha256, prk, undefined, 96);\n const okm = okmU8Array;\n const k1 = okm.subarray(0, 32);\n const k2 = okm.subarray(32, 64);\n const k3 = okm.subarray(64, 96);\n return [k1, k2, k3];\n },\n generateX25519KeyPair() {\n const secretKey = x25519.utils.randomPrivateKey();\n const publicKey = x25519.getPublicKey(secretKey);\n return {\n publicKey,\n privateKey: secretKey\n };\n },\n generateX25519KeyPairFromSeed(seed) {\n const publicKey = x25519.getPublicKey(seed);\n return {\n publicKey,\n privateKey: seed\n };\n },\n generateX25519SharedKey(privateKey, publicKey) {\n return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray());\n },\n chaCha20Poly1305Encrypt(plaintext, nonce, ad, k) {\n return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray());\n },\n chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst) {\n return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst);\n }\n};\n//# sourceMappingURL=js.js.map","import {} from 'uint8arraylist';\nimport { allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc';\nexport const uint16BEEncode = (value) => {\n const target = uint8ArrayAllocUnsafe(2);\n target[0] = value >> 8;\n target[1] = value;\n return target;\n};\nuint16BEEncode.bytes = 2;\nexport const uint16BEDecode = (data) => {\n if (data.length < 2)\n throw RangeError('Could not decode int16BE');\n if (data instanceof Uint8Array) {\n let value = 0;\n value += data[0] << 8;\n value += data[1];\n return value;\n }\n return data.getUint16(0);\n};\nuint16BEDecode.bytes = 2;\n//# sourceMappingURL=encoder.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { DUMP_SESSION_KEYS } from './constants.js';\nexport function logLocalStaticKeys(s, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (s) {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`);\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local static keys.');\n }\n}\nexport function logLocalEphemeralKeys(e, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`);\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local ephemeral keys.');\n }\n}\nexport function logRemoteStaticKey(rs, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (rs) {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote static public key.');\n }\n}\nexport function logRemoteEphemeralKey(re, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (re) {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote ephemeral keys.');\n }\n}\nexport function logCipherState(cs1, cs2, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`CIPHER_STATE_1 ${cs1.n.getUint64()} ${cs1.k && uint8ArrayToString(cs1.k, 'hex')}`);\n keyLogger(`CIPHER_STATE_2 ${cs2.n.getUint64()} ${cs2.k && uint8ArrayToString(cs2.k, 'hex')}`);\n}\n//# sourceMappingURL=logger.js.map","export class UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nexport class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\n//# sourceMappingURL=errors.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport const MIN_NONCE = 0;\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff;\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed';\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n n;\n bytes;\n view;\n constructor(n = MIN_NONCE) {\n this.n = n;\n this.bytes = uint8ArrayAlloc(12);\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n this.view.setUint32(4, n, true);\n }\n increment() {\n this.n++;\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true);\n }\n getBytes() {\n return this.bytes;\n }\n getUint64() {\n return this.n;\n }\n assertValue() {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE);\n }\n }\n}\n//# sourceMappingURL=nonce.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { InvalidCryptoExchangeError } from './errors.js';\nimport { Nonce } from './nonce.js';\n// Code in this file is a direct translation of a subset of the noise protocol https://noiseprotocol.org/noise.html,\n// agnostic to libp2p's usage of noise\nexport const ZEROLEN = uint8ArrayAlloc(0);\nexport class CipherState {\n k;\n n;\n crypto;\n constructor(crypto, k = undefined, n = 0) {\n this.crypto = crypto;\n this.k = k;\n this.n = new Nonce(n);\n }\n hasKey() {\n return Boolean(this.k);\n }\n encryptWithAd(ad, plaintext) {\n if (!this.hasKey()) {\n return plaintext;\n }\n this.n.assertValue();\n const e = this.crypto.encrypt(plaintext, this.n.getBytes(), ad, this.k);\n this.n.increment();\n return e;\n }\n decryptWithAd(ad, ciphertext, dst) {\n if (!this.hasKey()) {\n return ciphertext;\n }\n this.n.assertValue();\n const plaintext = this.crypto.decrypt(ciphertext, this.n.getBytes(), ad, this.k, dst);\n this.n.increment();\n return plaintext;\n }\n}\nexport class SymmetricState {\n cs;\n ck;\n h;\n crypto;\n constructor(crypto, protocolName) {\n this.crypto = crypto;\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8');\n this.h = hashProtocolName(crypto, protocolNameBytes);\n this.ck = this.h;\n this.cs = new CipherState(crypto);\n }\n mixKey(ikm) {\n const [ck, tempK] = this.crypto.hkdf(this.ck, ikm);\n this.ck = ck;\n this.cs = new CipherState(this.crypto, tempK);\n }\n mixHash(data) {\n this.h = this.crypto.hash(new Uint8ArrayList(this.h, data));\n }\n encryptAndHash(plaintext) {\n const ciphertext = this.cs.encryptWithAd(this.h, plaintext);\n this.mixHash(ciphertext);\n return ciphertext;\n }\n decryptAndHash(ciphertext) {\n const plaintext = this.cs.decryptWithAd(this.h, ciphertext);\n this.mixHash(ciphertext);\n return plaintext;\n }\n split() {\n const [tempK1, tempK2] = this.crypto.hkdf(this.ck, ZEROLEN);\n return [new CipherState(this.crypto, tempK1), new CipherState(this.crypto, tempK2)];\n }\n}\nexport class AbstractHandshakeState {\n ss;\n s;\n e;\n rs;\n re;\n initiator;\n crypto;\n constructor(init) {\n const { crypto, protocolName, prologue, initiator, s, e, rs, re } = init;\n this.crypto = crypto;\n this.ss = new SymmetricState(crypto, protocolName);\n this.ss.mixHash(prologue);\n this.initiator = initiator;\n this.s = s;\n this.e = e;\n this.rs = rs;\n this.re = re;\n }\n writeE() {\n if (this.e) {\n throw new Error('ephemeral keypair is already set');\n }\n const e = this.crypto.generateKeypair();\n this.ss.mixHash(e.publicKey);\n this.e = e;\n return e.publicKey;\n }\n writeS() {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n return this.ss.encryptAndHash(this.s.publicKey);\n }\n writeEE() {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.re));\n }\n writeES() {\n if (this.initiator) {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n else {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n }\n writeSE() {\n if (this.initiator) {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n else {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n }\n readE(message, offset = 0) {\n if (this.re) {\n throw new Error('remote ephemeral public key is already set');\n }\n if (message.byteLength < offset + 32) {\n throw new Error('message is not long enough');\n }\n this.re = message.sublist(offset, offset + 32);\n this.ss.mixHash(this.re);\n }\n readS(message, offset = 0) {\n if (this.rs) {\n throw new Error('remote static public key is already set');\n }\n const cipherLength = 32 + (this.ss.cs.hasKey() ? 16 : 0);\n if (message.byteLength < offset + cipherLength) {\n throw new Error('message is not long enough');\n }\n const temp = message.sublist(offset, offset + cipherLength);\n this.rs = this.ss.decryptAndHash(temp);\n return cipherLength;\n }\n readEE() {\n this.writeEE();\n }\n readES() {\n this.writeES();\n }\n readSE() {\n this.writeSE();\n }\n}\n/**\n * A IHandshakeState that's optimized for the XX pattern\n */\nexport class XXHandshakeState extends AbstractHandshakeState {\n // e\n writeMessageA(payload) {\n return new Uint8ArrayList(this.writeE(), this.ss.encryptAndHash(payload));\n }\n // e, ee, s, es\n writeMessageB(payload) {\n const e = this.writeE();\n this.writeEE();\n const encS = this.writeS();\n this.writeES();\n return new Uint8ArrayList(e, encS, this.ss.encryptAndHash(payload));\n }\n // s, se\n writeMessageC(payload) {\n const encS = this.writeS();\n this.writeSE();\n return new Uint8ArrayList(encS, this.ss.encryptAndHash(payload));\n }\n // e\n readMessageA(message) {\n try {\n this.readE(message);\n return this.ss.decryptAndHash(message.sublist(32));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 0 validation fail: ${e.message}`);\n }\n }\n // e, ee, s, es\n readMessageB(message) {\n try {\n this.readE(message);\n this.readEE();\n const consumed = this.readS(message, 32);\n this.readES();\n return this.ss.decryptAndHash(message.sublist(32 + consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 1 validation fail: ${e.message}`);\n }\n }\n // s, se\n readMessageC(message) {\n try {\n const consumed = this.readS(message);\n this.readSE();\n return this.ss.decryptAndHash(message.sublist(consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 2 validation fail: ${e.message}`);\n }\n }\n}\nfunction hashProtocolName(crypto, protocolName) {\n if (protocolName.length <= 32) {\n const h = uint8ArrayAlloc(32);\n h.set(protocolName);\n return h;\n }\n else {\n return crypto.hash(protocolName);\n }\n}\n//# sourceMappingURL=protocol.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var NoiseExtensions;\n(function (NoiseExtensions) {\n let _codec;\n NoiseExtensions.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n webtransportCerthashes: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.webtransportCerthashes.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseExtensions.encode = (obj) => {\n return encodeMessage(obj, NoiseExtensions.codec());\n };\n NoiseExtensions.decode = (buf) => {\n return decodeMessage(buf, NoiseExtensions.codec());\n };\n})(NoiseExtensions || (NoiseExtensions = {}));\nexport var NoiseHandshakePayload;\n(function (NoiseHandshakePayload) {\n let _codec;\n NoiseHandshakePayload.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.identityKey);\n }\n if ((obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.identitySig);\n }\n if (obj.extensions != null) {\n w.uint32(34);\n NoiseExtensions.codec().encode(obj.extensions, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n identityKey: uint8ArrayAlloc(0),\n identitySig: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.identityKey = reader.bytes();\n break;\n }\n case 2: {\n obj.identitySig = reader.bytes();\n break;\n }\n case 4: {\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseHandshakePayload.encode = (obj) => {\n return encodeMessage(obj, NoiseHandshakePayload.codec());\n };\n NoiseHandshakePayload.decode = (buf) => {\n return decodeMessage(buf, NoiseHandshakePayload.codec());\n };\n})(NoiseHandshakePayload || (NoiseHandshakePayload = {}));\n//# sourceMappingURL=payload.js.map","import { unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport {} from 'uint8arraylist';\nimport { equals, toString } from 'uint8arrays';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { UnexpectedPeerError } from './errors.js';\nimport { NoiseHandshakePayload } from './proto/payload.js';\nexport async function createHandshakePayload(privateKey, staticPublicKey, extensions) {\n const identitySig = await privateKey.sign(getSignaturePayload(staticPublicKey));\n return NoiseHandshakePayload.encode({\n identityKey: privateKey.public.bytes,\n identitySig,\n extensions\n });\n}\nexport async function decodeHandshakePayload(payloadBytes, remoteStaticKey, remoteIdentityKey) {\n try {\n const payload = NoiseHandshakePayload.decode(payloadBytes);\n if (remoteIdentityKey) {\n const remoteIdentityKeyBytes = remoteIdentityKey.subarray();\n if (!equals(remoteIdentityKeyBytes, payload.identityKey)) {\n throw new Error(`Payload identity key ${toString(payload.identityKey, 'hex')} does not match expected remote identity key ${toString(remoteIdentityKeyBytes, 'hex')}`);\n }\n }\n if (!remoteStaticKey) {\n throw new Error('Remote static does not exist');\n }\n const signaturePayload = getSignaturePayload(remoteStaticKey);\n const publicKey = unmarshalPublicKey(payload.identityKey);\n if (!(await publicKey.verify(signaturePayload, payload.identitySig))) {\n throw new Error('Invalid payload signature');\n }\n return payload;\n }\n catch (e) {\n throw new UnexpectedPeerError(e.message);\n }\n}\nexport function getSignaturePayload(publicKey) {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:');\n if (publicKey instanceof Uint8Array) {\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length);\n }\n publicKey.prepend(prefix);\n return publicKey;\n}\n//# sourceMappingURL=utils.js.map","import { unmarshalPrivateKey } from '@libp2p/crypto/keys';\nimport { CodeError, serviceCapabilities, isPeerId } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { decode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { duplexPair } from 'it-pair/duplex';\nimport { pipe } from 'it-pipe';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js';\nimport { defaultCrypto } from './crypto/index.js';\nimport { wrapCrypto } from './crypto.js';\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js';\nimport { registerMetrics } from './metrics.js';\nimport { performHandshakeInitiator, performHandshakeResponder } from './performHandshake.js';\nimport { decryptStream, encryptStream } from './streaming.js';\nexport class Noise {\n protocol = '/noise';\n crypto;\n prologue;\n staticKey;\n extensions;\n metrics;\n components;\n constructor(components, init = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes } = init;\n const { metrics } = components;\n this.components = components;\n const _crypto = crypto ?? defaultCrypto;\n this.crypto = wrapCrypto(_crypto);\n this.extensions = extensions;\n this.metrics = metrics ? registerMetrics(metrics) : undefined;\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKey = _crypto.generateX25519KeyPairFromSeed(staticNoiseKey);\n }\n else {\n this.staticKey = _crypto.generateX25519KeyPair();\n }\n this.prologue = prologueBytes ?? uint8ArrayAlloc(0);\n }\n [Symbol.toStringTag] = '@chainsafe/libp2p-noise';\n [serviceCapabilities] = [\n '@libp2p/connection-encryption',\n '@chainsafe/libp2p-noise'\n ];\n async secureOutbound(...args) {\n const { localPeer, connection, remotePeer, signal } = this.parseArgs(args);\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n if (!localPeer.privateKey) {\n throw new CodeError('local peerId does not contain private key', 'ERR_NO_PRIVATE_KEY');\n }\n const privateKey = await unmarshalPrivateKey(localPeer.privateKey);\n const remoteIdentityKey = remotePeer?.publicKey;\n const handshake = await this.performHandshakeInitiator(wrappedConnection, privateKey, remoteIdentityKey, {\n signal\n });\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n return {\n conn: connection,\n remoteExtensions: handshake.payload.extensions,\n remotePeer: await peerIdFromKeys(handshake.payload.identityKey)\n };\n }\n async secureInbound(...args) {\n const { localPeer, connection, remotePeer, signal } = this.parseArgs(args);\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n if (!localPeer.privateKey) {\n throw new CodeError('local peerId does not contain private key', 'ERR_NO_PRIVATE_KEY');\n }\n const privateKey = await unmarshalPrivateKey(localPeer.privateKey);\n const remoteIdentityKey = remotePeer?.publicKey;\n const handshake = await this.performHandshakeResponder(wrappedConnection, privateKey, remoteIdentityKey, {\n signal\n });\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n return {\n conn: connection,\n remoteExtensions: handshake.payload.extensions,\n remotePeer: await peerIdFromKeys(handshake.payload.identityKey)\n };\n }\n /**\n * Perform XX handshake as initiator.\n */\n async performHandshakeInitiator(connection, \n // TODO: pass private key in noise constructor via Components\n privateKey, remoteIdentityKey, options) {\n let result;\n try {\n result = await performHandshakeInitiator({\n connection,\n privateKey,\n remoteIdentityKey,\n log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: this.extensions\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n /**\n * Perform XX handshake as responder.\n */\n async performHandshakeResponder(connection, \n // TODO: pass private key in noise constructor via Components\n privateKey, remoteIdentityKey, options) {\n let result;\n try {\n result = await performHandshakeResponder({\n connection,\n privateKey,\n remoteIdentityKey,\n log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: this.extensions\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n async createSecureConnection(connection, handshake) {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair();\n const network = connection.unwrap();\n await pipe(secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n (source) => decode(source, { lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n );\n return user;\n }\n /**\n * Detect call signature in `libp2p@1.x.x` or `libp2p@2.x.x` style.\n *\n * TODO: remove this after `libp2p@2.x.x` is released and only support the\n * newer style\n */\n parseArgs(args) {\n // if the first argument is a peer id, we're using the libp2p@1.x.x style\n if (isPeerId(args[0])) {\n return {\n localPeer: args[0],\n connection: args[1],\n remotePeer: args[2]\n };\n }\n else {\n // handle upcoming changes in libp2p@2.x.x where the first argument is the\n // connection and the second is optionally the remote peer\n // @see https://github.com/libp2p/js-libp2p/pull/2304\n return {\n localPeer: this.components.peerId,\n connection: args[0],\n remotePeer: args[1]?.remotePeer,\n signal: args[1]?.signal\n };\n }\n }\n}\n//# sourceMappingURL=noise.js.map","export function wrapCrypto(crypto) {\n return {\n generateKeypair: crypto.generateX25519KeyPair,\n dh: (keypair, publicKey) => crypto.generateX25519SharedKey(keypair.privateKey, publicKey).subarray(0, 32),\n encrypt: crypto.chaCha20Poly1305Encrypt,\n decrypt: crypto.chaCha20Poly1305Decrypt,\n hash: crypto.hashSHA256,\n hkdf: crypto.getHKDF\n };\n}\n//# sourceMappingURL=crypto.js.map","export function registerMetrics(metrics) {\n return {\n xxHandshakeSuccesses: metrics.registerCounter('libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n xxHandshakeErrors: metrics.registerCounter('libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n encryptedPackets: metrics.registerCounter('libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n decryptedPackets: metrics.registerCounter('libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n decryptErrors: metrics.registerCounter('libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n };\n}\n//# sourceMappingURL=metrics.js.map","import { logLocalStaticKeys, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey, logCipherState } from './logger.js';\nimport { ZEROLEN, XXHandshakeState } from './protocol.js';\nimport { createHandshakePayload, decodeHandshakePayload } from './utils.js';\nexport async function performHandshakeInitiator(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remoteIdentityKey, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: true,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Initiator starting to send first message.');\n await connection.write(xx.writeMessageA(ZEROLEN), options);\n log.trace('Stage 0 - Initiator finished sending first message.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 1 - Initiator waiting to receive first message from responder...');\n const plaintext = xx.readMessageB(await connection.read(options));\n log.trace('Stage 1 - Initiator received the message.');\n logRemoteEphemeralKey(xx.re, log);\n logRemoteStaticKey(xx.rs, log);\n log.trace(\"Initiator going to check remote's signature...\");\n const receivedPayload = await decodeHandshakePayload(plaintext, xx.rs, remoteIdentityKey);\n log.trace('All good with the signature!');\n log.trace('Stage 2 - Initiator sending third handshake message.');\n await connection.write(xx.writeMessageC(payload), options);\n log.trace('Stage 2 - Initiator sent message with signed payload.');\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: receivedPayload,\n encrypt: (plaintext) => cs1.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs2.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\nexport async function performHandshakeResponder(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remoteIdentityKey, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: false,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Responder waiting to receive first message.');\n xx.readMessageA(await connection.read(options));\n log.trace('Stage 0 - Responder received first message.');\n logRemoteEphemeralKey(xx.re, log);\n log.trace('Stage 1 - Responder sending out first message with signed payload and static key.');\n await connection.write(xx.writeMessageB(payload), options);\n log.trace('Stage 1 - Responder sent the second handshake message with signed payload.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 2 - Responder waiting for third handshake message...');\n const plaintext = xx.readMessageC(await connection.read(options));\n log.trace('Stage 2 - Responder received the message, finished handshake.');\n const receivedPayload = await decodeHandshakePayload(plaintext, xx.rs, remoteIdentityKey);\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: receivedPayload,\n encrypt: (plaintext) => cs2.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs1.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\n//# sourceMappingURL=performHandshake.js.map","import { pair } from './index.js';\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair() {\n const a = pair();\n const b = pair();\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ];\n}\n//# sourceMappingURL=duplex.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from './constants.js';\nimport { uint16BEEncode } from './encoder.js';\nconst CHACHA_TAG_LENGTH = 16;\n// Returns generator that encrypts payload from the user\nexport function encryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG;\n if (end > chunk.length) {\n end = chunk.length;\n }\n let data;\n if (chunk instanceof Uint8Array) {\n data = handshake.encrypt(chunk.subarray(i, end));\n }\n else {\n data = handshake.encrypt(chunk.sublist(i, end));\n }\n metrics?.encryptedPackets.increment();\n yield new Uint8ArrayList(uint16BEEncode(data.byteLength), data);\n }\n }\n };\n}\n// Decrypt received payload to the user\nexport function decryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES;\n if (end > chunk.length) {\n end = chunk.length;\n }\n if (end - CHACHA_TAG_LENGTH < i) {\n throw new Error('Invalid chunk');\n }\n const encrypted = chunk.sublist(i, end);\n // memory allocation is not cheap so reuse the encrypted Uint8Array\n // see https://github.com/ChainSafe/js-libp2p-noise/pull/242#issue-1422126164\n // this is ok because chacha20 reads bytes one by one and don't reread after that\n // it's also tested in https://github.com/ChainSafe/as-chacha20poly1305/pull/1/files#diff-25252846b58979dcaf4e41d47b3eadd7e4f335e7fb98da6c049b1f9cd011f381R48\n const dst = chunk.subarray(i, end - CHACHA_TAG_LENGTH);\n try {\n const plaintext = handshake.decrypt(encrypted, dst);\n metrics?.decryptedPackets.increment();\n yield plaintext;\n }\n catch (e) {\n metrics?.decryptErrors.increment();\n throw e;\n }\n }\n }\n };\n}\n//# sourceMappingURL=streaming.js.map","import { Noise } from './noise.js';\nexport { pureJsCrypto } from './crypto/js.js';\nexport function noise(init = {}) {\n return (components) => new Noise(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');\n//# sourceMappingURL=index.js.map","import { multiaddr } from '@multiformats/multiaddr';\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4');\nexport const DNS6 = base('dns6');\nexport const DNSADDR = base('dnsaddr');\nexport const DNS = or(base('dns'), DNSADDR, DNS4, DNS6);\nexport const IP = or(base('ip4'), base('ip6'));\nexport const TCP = or(and(IP, base('tcp')), and(DNS, base('tcp')));\nexport const UDP = and(IP, base('udp'));\nexport const UTP = and(UDP, base('utp'));\nexport const QUIC = and(UDP, base('quic'));\nexport const QUICV1 = and(UDP, base('quic-v1'));\nconst _WebSockets = or(and(TCP, base('ws')), and(DNS, base('ws')));\nexport const WebSockets = or(and(_WebSockets, base('p2p')), _WebSockets);\nconst _WebSocketsSecure = or(and(TCP, base('wss')), and(DNS, base('wss')), and(TCP, base('tls'), base('ws')), and(DNS, base('tls'), base('ws')));\nexport const WebSocketsSecure = or(and(_WebSocketsSecure, base('p2p')), _WebSocketsSecure);\nexport const HTTP = or(and(TCP, base('http')), and(IP, base('http')), and(DNS, base('http')));\nexport const HTTPS = or(and(TCP, base('https')), and(IP, base('https')), and(DNS, base('https')));\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'));\nexport const WebRTCDirect = or(and(_WebRTCDirect, base('p2p')), _WebRTCDirect);\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'));\nexport const WebTransport = or(and(_WebTransport, base('p2p')), _WebTransport);\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(and(WebSockets, base('p2p-webrtc-star'), base('p2p')), and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')), and(WebSockets, base('p2p-webrtc-star')), and(WebSocketsSecure, base('p2p-webrtc-star')));\nexport const WebSocketStar = or(and(WebSockets, base('p2p-websocket-star'), base('p2p')), and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')), and(WebSockets, base('p2p-websocket-star')), and(WebSocketsSecure, base('p2p-websocket-star')));\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(and(HTTP, base('p2p-webrtc-direct'), base('p2p')), and(HTTPS, base('p2p-webrtc-direct'), base('p2p')), and(HTTP, base('p2p-webrtc-direct')), and(HTTPS, base('p2p-webrtc-direct')));\nexport const Reliable = or(_WebSockets, _WebSocketsSecure, HTTP, HTTPS, P2PWebRTCStar, P2PWebRTCDirect, TCP, UTP, QUIC, DNS, WebRTCDirect, WebTransport);\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(and(Reliable, base('p2p-stardust'), base('p2p')), and(Reliable, base('p2p-stardust')));\nconst _P2P = or(and(Reliable, base('p2p')), P2PWebRTCStar, P2PWebRTCDirect, WebRTCDirect, WebTransport, base('p2p'));\nconst _Circuit = or(and(_P2P, base('p2p-circuit'), _P2P), and(_P2P, base('p2p-circuit')), and(base('p2p-circuit'), _P2P), and(Reliable, base('p2p-circuit')), and(base('p2p-circuit'), Reliable), base('p2p-circuit'));\nconst CircuitRecursive = () => or(and(_Circuit, CircuitRecursive), _Circuit);\nexport const Circuit = CircuitRecursive();\nexport const P2P = or(and(Circuit, _P2P, Circuit), and(_P2P, Circuit), and(Circuit, _P2P), Circuit, _P2P);\nexport const IPFS = P2P;\nexport const WebRTC = or(and(Circuit, base('webrtc'), base('p2p')), and(Circuit, base('webrtc')), and(Reliable, base('webrtc'), base('p2p')), and(Reliable, base('webrtc')), base('webrtc'));\n/*\n * Validation funcs\n */\nfunction makeMatchesFunction(partialMatch) {\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const out = partialMatch(ma.protoNames());\n if (out === null) {\n return false;\n }\n if (out === true || out === false) {\n return out;\n }\n return out.length === 0;\n }\n return matches;\n}\nfunction and(...args) {\n function partialMatch(a) {\n if (a.length < args.length) {\n return null;\n }\n let out = a;\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (Array.isArray(out)) {\n a = out;\n }\n if (out === null) {\n return true;\n }\n return false;\n });\n return out;\n }\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n}\nfunction or(...args) {\n function partialMatch(a) {\n let out = null;\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (res != null) {\n out = res;\n return true;\n }\n return false;\n });\n return out;\n }\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n return result;\n}\nfunction base(n) {\n const name = n;\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const pnames = ma.protoNames();\n if (pnames.length === 1 && pnames[0] === name) {\n return true;\n }\n return false;\n }\n function partialMatch(protos) {\n if (protos.length === 0) {\n return null;\n }\n if (protos[0] === name) {\n return protos.slice(1);\n }\n return null;\n }\n return {\n toString: function () { return name; },\n matches,\n partialMatch\n };\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\nimport { TypedEventEmitter, peerDiscoverySymbol, serviceCapabilities } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { P2P } from '@multiformats/mafmt';\nimport { multiaddr } from '@multiformats/multiaddr';\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap';\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nconst DEFAULT_BOOTSTRAP_TAG_TTL = 120000;\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000;\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter {\n static tag = 'bootstrap';\n log;\n timer;\n list;\n timeout;\n components;\n _init;\n constructor(components, options = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses');\n }\n super();\n this.components = components;\n this.log = components.logger.forComponent('libp2p:bootstrap');\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT;\n this.list = [];\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr');\n continue;\n }\n const ma = multiaddr(candidate);\n const peerIdStr = ma.getPeerId();\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id');\n continue;\n }\n const peerData = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma]\n };\n this.list.push(peerData);\n }\n this._init = options;\n }\n [peerDiscoverySymbol] = this;\n [Symbol.toStringTag] = '@libp2p/bootstrap';\n [serviceCapabilities] = [\n '@libp2p/peer-discovery'\n ];\n isStarted() {\n return Boolean(this.timer);\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted()) {\n return;\n }\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout);\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err);\n });\n }, this.timeout);\n }\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers() {\n if (this.timer == null) {\n return;\n }\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n }\n });\n // check we are still running\n if (this.timer == null) {\n return;\n }\n this.safeDispatchEvent('peer', { detail: peerData });\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n this.timer = undefined;\n }\n}\nexport function bootstrap(init) {\n return (components) => new Bootstrap(components, init);\n}\n//# sourceMappingURL=index.js.map","// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return encodeMessage(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf) => {\n return decodeMessage(buf, AddressInfo.codec());\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes();\n break;\n case 2:\n obj.seq = reader.uint64();\n break;\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()));\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return encodeMessage(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf) => {\n return decodeMessage(buf, PeerRecord.codec());\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map","import { peerIdFromBytes } from '@libp2p/peer-id';\nimport { arrayEquals } from '@libp2p/utils/array-equals';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { ENVELOPE_DOMAIN_PEER_RECORD, ENVELOPE_PAYLOAD_TYPE_PEER_RECORD } from './consts.js';\nimport { PeerRecord as Protobuf } from './peer-record.js';\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = Protobuf.decode(buf);\n const peerId = peerIdFromBytes(peerRecord.peerId);\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => multiaddr(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.payloadType = reader.bytes();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n case 5:\n obj.signature = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return encodeMessage(obj, Envelope.codec());\n };\n Envelope.decode = (buf) => {\n return decodeMessage(buf, Envelope.codec());\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { CodeError } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string';\nimport { codes } from '../errors.js';\nimport { Envelope as Protobuf } from './envelope.js';\nexport class RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = Protobuf.decode(data);\n const peerId = await peerIdFromKeys(envelopeData.publicKey);\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, peerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const key = await unmarshalPrivateKey(peerId.privateKey);\n const signature = await key.sign(signData.subarray());\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new CodeError('envelope signature is not valid for the given domain', codes.ERR_SIGNATURE_NOT_VALID);\n }\n return envelope;\n };\n peerId;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { peerId, payloadType, payload, signature } = init;\n this.peerId = peerId;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return uint8ArrayEquals(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n const key = unmarshalPublicKey(this.peerId.publicKey);\n return key.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = uint8arraysFromString(domain);\n const domainLength = varint.encode(domainUint8Array.byteLength);\n const payloadTypeLength = varint.encode(payloadType.length);\n const payloadLength = varint.encode(payload.length);\n return new Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map","export const codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n};\n//# sourceMappingURL=errors.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma) => {\n return ma.toString().split('/').slice(1);\n};\nexport const func = (fn) => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false;\n }\n if (fn(vals[0])) {\n return vals.slice(1);\n }\n return false;\n },\n pattern: 'fn'\n };\n};\nexport const literal = (str) => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n };\n};\nexport const string = () => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n };\n};\nexport const number = () => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n };\n};\nexport const peerId = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false;\n }\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n base58btc.decode(`z${vals[1]}`);\n }\n catch (err) {\n return false;\n }\n }\n else {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/p2p/{peerid}'\n };\n};\nexport const certhash = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'certhash') {\n return false;\n }\n try {\n base64url.decode(vals[1]);\n }\n catch {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/certhash/{certhash}'\n };\n};\nexport const optional = (matcher) => {\n return {\n match: (vals) => {\n const result = matcher.match(vals);\n if (result === false) {\n return vals;\n }\n return result;\n },\n pattern: `optional(${matcher.pattern})`\n };\n};\nexport const or = (...matchers) => {\n return {\n match: (vals) => {\n let matches;\n for (const matcher of matchers) {\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n continue;\n }\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result;\n }\n }\n if (matches == null) {\n return false;\n }\n return matches;\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nexport const and = (...matchers) => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n return false;\n }\n vals = result;\n }\n return vals;\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nexport function fmt(...matchers) {\n function match(ma) {\n let parts = toParts(ma);\n for (const matcher of matchers) {\n const result = matcher.match(parts);\n if (result === false) {\n return false;\n }\n parts = result;\n }\n return parts;\n }\n function matches(ma) {\n const result = match(ma);\n return result !== false;\n }\n function exactMatch(ma) {\n const result = match(ma);\n if (result === false) {\n return false;\n }\n return result.length === 0;\n }\n return {\n matchers,\n matches,\n exactMatch\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\nimport { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { and, or, literal, string, peerId, optional, fmt, func, number, certhash } from './utils.js';\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string());\nconst _DNS6 = and(literal('dns6'), string());\nconst _DNSADDR = and(literal('dnsaddr'), string());\nconst _DNS = and(literal('dns'), string());\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(peerId()));\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(peerId()));\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(peerId()));\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()));\nconst _IP4 = and(literal('ip4'), func(isIPv4));\nconst _IP6 = and(literal('ip6'), func(isIPv6));\nconst _IP = or(_IP4, _IP6);\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()))));\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4);\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6);\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP);\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number());\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number());\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(peerId())));\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP);\nconst _QUIC = and(_UDP, literal('quic'));\nconst _QUICV1 = and(_UDP, literal('quic-v1'));\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1);\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC);\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUICV1 = fmt(_QUICV1);\nconst _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUICV1);\nconst _WebSockets = or(and(_WEB, literal('ws'), optional(peerId())));\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets);\nconst _WebSocketsSecure = or(and(_WEB, literal('wss'), optional(peerId())), and(_WEB, literal('tls'), literal('ws'), optional(peerId())));\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure);\nconst _WebRTCDirect = and(_UDP, literal('webrtc-direct'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect);\nconst _WebTransport = and(_QUICV1, literal('webtransport'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport);\nconst _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(peerId())), and(QUIC_V0_OR_V1, optional(peerId())), and(_IP_OR_DOMAIN, optional(peerId())), _WebRTCDirect, _WebTransport, peerId());\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P);\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId());\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit);\nconst _WebRTC = or(and(_P2P, literal('p2p-circuit'), literal('webrtc'), optional(peerId())), and(_P2P, literal('webrtc'), optional(peerId())), literal('webrtc'));\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC);\nconst _HTTP = or(and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('http'), optional(peerId())));\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP);\nconst _HTTPS = or(and(_IP_OR_DOMAIN, literal('tcp'), or(and(literal('443'), literal('http')), and(number(), literal('https'))), optional(peerId())), and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('https'), optional(peerId())));\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS);\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed Protobuf encoded\n * messages over streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-protobuf-stream'\n * import { MessageType } from './src/my-message-type.js'\n *\n * // RequestType and ResponseType have been generate from `.proto` files and have\n * // `.encode` and `.decode` methods for serialization/deserialization\n *\n * const stream = pbStream(duplex)\n *\n * // write a message to the stream\n * stream.write({\n * foo: 'bar'\n * }, MessageType)\n *\n * // read a message from the stream\n * const res = await stream.read(MessageType)\n * ```\n */\nimport { lpStream } from 'it-length-prefixed-stream';\nexport function pbStream(duplex, opts) {\n const lp = lpStream(duplex, opts);\n const W = {\n read: async (proto, options) => {\n // readLP, decode\n const value = await lp.read(options);\n return proto.decode(value);\n },\n write: async (message, proto, options) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options);\n },\n writeV: async (messages, proto, options) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options);\n },\n pb: (proto) => {\n return {\n read: async (options) => W.read(proto, options),\n write: async (d, options) => W.write(d, proto, options),\n writeV: async (d, options) => W.writeV(d, proto, options),\n unwrap: () => W\n };\n },\n unwrap: () => {\n return lp.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Identify;\n(function (Identify) {\n let _codec;\n Identify.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.protocolVersion != null) {\n w.uint32(42);\n w.string(obj.protocolVersion);\n }\n if (obj.agentVersion != null) {\n w.uint32(50);\n w.string(obj.agentVersion);\n }\n if (obj.publicKey != null) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (obj.observedAddr != null) {\n w.uint32(34);\n w.bytes(obj.observedAddr);\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26);\n w.string(value);\n }\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(66);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n listenAddrs: [],\n protocols: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 5:\n obj.protocolVersion = reader.string();\n break;\n case 6:\n obj.agentVersion = reader.string();\n break;\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.listenAddrs.push(reader.bytes());\n break;\n case 4:\n obj.observedAddr = reader.bytes();\n break;\n case 3:\n obj.protocols.push(reader.string());\n break;\n case 8:\n obj.signedPeerRecord = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Identify.encode = (obj) => {\n return encodeMessage(obj, Identify.codec());\n };\n Identify.decode = (buf) => {\n return decodeMessage(buf, Identify.codec());\n };\n})(Identify || (Identify = {}));\n//# sourceMappingURL=message.js.map","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","import { CodeError } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe';\nimport { IDENTIFY_PROTOCOL_VERSION, MAX_IDENTIFY_MESSAGE_SIZE, MAX_PUSH_CONCURRENCY } from './consts.js';\nexport const defaultValues = {\n protocolPrefix: 'ipfs',\n timeout: 5000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxObservedAddresses: 10,\n maxMessageSize: MAX_IDENTIFY_MESSAGE_SIZE,\n runOnConnectionOpen: true,\n runOnSelfUpdate: true,\n runOnTransientConnection: true,\n concurrency: MAX_PUSH_CONCURRENCY\n};\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nexport function getCleanMultiaddr(addr) {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr);\n }\n catch {\n }\n }\n}\nexport function getAgentVersion(nodeInfo, agentVersion) {\n if (agentVersion != null) {\n return agentVersion;\n }\n agentVersion = `${nodeInfo.name}/${nodeInfo.version}`;\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (isNode || isElectronMain) {\n agentVersion += ` UserAgent=${globalThis.process.version}`;\n }\n else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`;\n }\n return agentVersion;\n}\nexport async function consumeIdentifyMessage(peerStore, events, log, connection, message) {\n log('received identify from %p', connection.remotePeer);\n if (message == null) {\n throw new CodeError('message was null or undefined', 'ERR_INVALID_MESSAGE');\n }\n const peer = {};\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: multiaddr(buf)\n }));\n }\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols;\n }\n if (message.publicKey != null) {\n peer.publicKey = message.publicKey;\n const peerId = await peerIdFromKeys(message.publicKey);\n if (!peerId.equals(connection.remotePeer)) {\n throw new CodeError('public key did not match remote PeerId', 'ERR_INVALID_PUBLIC_KEY');\n }\n }\n let output;\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n log('received signedPeerRecord from %p', connection.remotePeer);\n let peerRecordEnvelope = message.signedPeerRecord;\n const envelope = await RecordEnvelope.openAndCertify(peerRecordEnvelope, PeerRecord.DOMAIN);\n let peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n // Verify peerId\n if (!peerRecord.peerId.equals(envelope.peerId)) {\n throw new CodeError('signing key does not match PeerId in the PeerRecord', 'ERR_INVALID_SIGNING_KEY');\n }\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new CodeError('signing key does not match remote PeerId', 'ERR_INVALID_PEER_RECORD_KEY');\n }\n let existingPeer;\n try {\n existingPeer = await peerStore.get(peerRecord.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata;\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n peerRecord = storedRecord;\n peerRecordEnvelope = existingPeer.peerRecordEnvelope;\n }\n }\n }\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope;\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }));\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n };\n }\n else {\n log('%p did not send a signed peer record', connection.remotePeer);\n }\n log('patching %p with', connection.remotePeer, peer);\n await peerStore.patch(connection.remotePeer, peer);\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata = {};\n if (message.agentVersion != null) {\n metadata.AgentVersion = uint8ArrayFromString(message.agentVersion);\n }\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = uint8ArrayFromString(message.protocolVersion);\n }\n log('merging %p metadata', connection.remotePeer, metadata);\n await peerStore.merge(connection.remotePeer, {\n metadata\n });\n }\n const result = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => multiaddr(buf)),\n observedAddr: message.observedAddr == null ? undefined : multiaddr(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n };\n events.safeDispatchEvent('peer:identify', { detail: result });\n return result;\n}\nexport class AbstractIdentify {\n host;\n protocol;\n started;\n timeout;\n peerId;\n peerStore;\n registrar;\n addressManager;\n maxInboundStreams;\n maxOutboundStreams;\n maxMessageSize;\n maxObservedAddresses;\n events;\n runOnTransientConnection;\n log;\n constructor(components, init) {\n this.protocol = init.protocol;\n this.started = false;\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.registrar = components.registrar;\n this.addressManager = components.addressManager;\n this.events = components.events;\n this.log = init.log;\n this.timeout = init.timeout ?? defaultValues.timeout;\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams;\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams;\n this.maxMessageSize = init.maxMessageSize ?? defaultValues.maxMessageSize;\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses;\n this.runOnTransientConnection = init.runOnTransientConnection ?? defaultValues.runOnTransientConnection;\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: getAgentVersion(components.nodeInfo, init.agentVersion)\n };\n }\n isStarted() {\n return this.started;\n }\n async start() {\n if (this.started) {\n return;\n }\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: uint8ArrayFromString(this.host.agentVersion),\n ProtocolVersion: uint8ArrayFromString(this.host.protocolVersion)\n }\n });\n await this.registrar.handle(this.protocol, (data) => {\n void this.handleProtocol(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.registrar.unhandle(this.protocol);\n this.started = false;\n }\n}\n//# sourceMappingURL=utils.js.map","export const PROTOCOL_VERSION = 'ipfs/0.1.0'; // deprecated\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0'; // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0'; // deprecated\nexport const IDENTIFY_PROTOCOL_VERSION = '0.1.0';\nexport const MULTICODEC_IDENTIFY_PROTOCOL_NAME = 'id';\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME = 'id/push';\nexport const MULTICODEC_IDENTIFY_PROTOCOL_VERSION = '1.0.0';\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION = '1.0.0';\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nexport const MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8;\n// https://github.com/libp2p/go-libp2p/blob/0385ec924bad172f74a74db09939e97c079b1420/p2p/protocol/identify/id.go#L47C7-L47C25\nexport const MAX_PUSH_CONCURRENCY = 32;\n//# sourceMappingURL=consts.js.map","/* eslint-disable complexity */\nimport { CodeError, serviceCapabilities, setMaxListeners } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport { protocols } from '@multiformats/multiaddr';\nimport { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher';\nimport { pbStream } from 'it-protobuf-stream';\nimport { MULTICODEC_IDENTIFY_PROTOCOL_NAME, MULTICODEC_IDENTIFY_PROTOCOL_VERSION } from './consts.js';\nimport { Identify as IdentifyMessage } from './pb/message.js';\nimport { AbstractIdentify, consumeIdentifyMessage, defaultValues, getCleanMultiaddr } from './utils.js';\nexport class Identify extends AbstractIdentify {\n constructor(components, init = {}) {\n super(components, {\n ...init,\n protocol: `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,\n log: components.logger.forComponent('libp2p:identify')\n });\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail;\n this.identify(connection).catch(err => { this.log.error('error during identify trigged by connection:open', err); });\n });\n }\n }\n [serviceCapabilities] = [\n '@libp2p/identify'\n ];\n async _identify(connection, options = {}) {\n let stream;\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = pbStream(stream, {\n maxDataLength: this.maxMessageSize\n }).pb(IdentifyMessage);\n const message = await pb.read(options);\n await stream.close(options);\n return message;\n }\n catch (err) {\n this.log.error('error while reading identify message', err);\n stream?.abort(err);\n throw err;\n }\n }\n async identify(connection, options = {}) {\n const message = await this._identify(connection, options);\n const { publicKey, protocols, observedAddr } = message;\n if (publicKey == null) {\n throw new CodeError('public key was missing from identify message', 'ERR_MISSING_PUBLIC_KEY');\n }\n const id = await peerIdFromKeys(publicKey);\n if (!connection.remotePeer.equals(id)) {\n throw new CodeError('identified peer does not match the expected peer', 'ERR_INVALID_PEER');\n }\n if (this.peerId.equals(id)) {\n throw new CodeError('identified peer is our own peer id?', 'ERR_INVALID_PEER');\n }\n // Get the observedAddr if there is one\n const cleanObservedAddr = getCleanMultiaddr(observedAddr);\n this.log('identify completed for peer %p and protocols %o', id, protocols);\n this.log('our observed address is %a', cleanObservedAddr);\n if (cleanObservedAddr != null &&\n this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {\n this.log('storing our observed address %a', cleanObservedAddr);\n this.addressManager.addObservedAddr(cleanObservedAddr);\n }\n return consumeIdentifyMessage(this.peerStore, this.events, this.log, connection, message);\n }\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async handleProtocol(data) {\n const { connection, stream } = data;\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n try {\n const publicKey = this.peerId.publicKey ?? new Uint8Array(0);\n const peerData = await this.peerStore.get(this.peerId);\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code));\n let signedPeerRecord = peerData.peerRecordEnvelope;\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs\n });\n const envelope = await RecordEnvelope.seal(peerRecord, this.peerId);\n signedPeerRecord = envelope.marshal().subarray();\n }\n let observedAddr = connection.remoteAddr.bytes;\n if (!IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined;\n }\n const pb = pbStream(stream).pb(IdentifyMessage);\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n this.log.error('could not respond to identify request', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=identify.js.map","/**\n * @packageDocumentation\n *\n * Use the `identify` function to add support for the [Identify protocol](https://github.com/libp2p/specs/blob/master/identify/README.md) to libp2p.\n *\n * This protocol allows network peers to discover the multiaddrs the current node listens on, and the protocols it supports.\n *\n * A second function, `identifyPush` is also exported to add support for [identify/push](https://github.com/libp2p/specs/blob/master/identify/README.md#identifypush).\n *\n * This protocol will send updates to all connected peers when the multiaddrs or protocols of the current node change.\n *\n * > [!TIP]\n * > For maximum network compatibility you should configure both protocols\n *\n * @example Enabling identify\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identify: identify()\n * }\n * })\n * ```\n *\n * @example Enabling identify push\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identifyPush } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identifyPush: identifyPush()\n * }\n * })\n * ```\n */\nimport { IdentifyPush as IdentifyPushClass } from './identify-push.js';\nimport { Identify as IdentifyClass } from './identify.js';\nexport function identify(init = {}) {\n return (components) => new IdentifyClass(components, init);\n}\nexport function identifyPush(init = {}) {\n return (components) => new IdentifyPushClass(components, init);\n}\n//# sourceMappingURL=index.js.map","import { getIterator } from 'get-iterator';\nimport { isPromise } from './is-promise.js';\nexport function closeSource(source, log) {\n const res = getIterator(source).return?.();\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err);\n });\n }\n}\n//# sourceMappingURL=close-source.js.map","export function getIterator(obj) {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]();\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]();\n }\n if (typeof obj.next === 'function') {\n return obj; // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable');\n}\n//# sourceMappingURL=index.js.map","export function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=is-promise.js.map","// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15\nconst randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);\n\nconst createAbortError = () => {\n\tconst error = new Error('Delay aborted');\n\terror.name = 'AbortError';\n\treturn error;\n};\n\nconst clearMethods = new WeakMap();\n\nexport function createDelay({clearTimeout: defaultClear, setTimeout: defaultSet} = {}) {\n\t// We cannot use `async` here as we need the promise identity.\n\treturn (milliseconds, {value, signal} = {}) => {\n\t\t// TODO: Use `signal?.throwIfAborted()` when targeting Node.js 18.\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(createAbortError());\n\t\t}\n\n\t\tlet timeoutId;\n\t\tlet settle;\n\t\tlet rejectFunction;\n\t\tconst clear = defaultClear ?? clearTimeout;\n\n\t\tconst signalListener = () => {\n\t\t\tclear(timeoutId);\n\t\t\trejectFunction(createAbortError());\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t\t}\n\t\t};\n\n\t\tconst delayPromise = new Promise((resolve, reject) => {\n\t\t\tsettle = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t};\n\n\t\t\trejectFunction = reject;\n\t\t\ttimeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);\n\t\t});\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t\t}\n\n\t\tclearMethods.set(delayPromise, () => {\n\t\t\tclear(timeoutId);\n\t\t\ttimeoutId = null;\n\t\t\tsettle();\n\t\t});\n\n\t\treturn delayPromise;\n\t};\n}\n\nconst delay = createDelay();\n\nexport default delay;\n\nexport async function rangeDelay(minimum, maximum, options = {}) {\n\treturn delay(randomInteger(minimum, maximum), options);\n}\n\nexport function clearDelay(promise) {\n\tclearMethods.get(promise)?.();\n}\n","import { CodeError } from '@libp2p/interface';\nimport delay from 'delay';\nexport class RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await delay(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nclass MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map","export var MessageTypes;\n(function (MessageTypes) {\n MessageTypes[MessageTypes[\"NEW_STREAM\"] = 0] = \"NEW_STREAM\";\n MessageTypes[MessageTypes[\"MESSAGE_RECEIVER\"] = 1] = \"MESSAGE_RECEIVER\";\n MessageTypes[MessageTypes[\"MESSAGE_INITIATOR\"] = 2] = \"MESSAGE_INITIATOR\";\n MessageTypes[MessageTypes[\"CLOSE_RECEIVER\"] = 3] = \"CLOSE_RECEIVER\";\n MessageTypes[MessageTypes[\"CLOSE_INITIATOR\"] = 4] = \"CLOSE_INITIATOR\";\n MessageTypes[MessageTypes[\"RESET_RECEIVER\"] = 5] = \"RESET_RECEIVER\";\n MessageTypes[MessageTypes[\"RESET_INITIATOR\"] = 6] = \"RESET_INITIATOR\";\n})(MessageTypes || (MessageTypes = {}));\nexport const MessageTypeNames = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n});\nexport const InitiatorMessageTypes = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n});\nexport const ReceiverMessageTypes = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n});\n//# sourceMappingURL=message-types.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { MessageTypeNames, MessageTypes } from './message-types.js';\nexport const MAX_MSG_SIZE = 1 << 20; // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20; // 4MB\nexport class Decoder {\n _buffer;\n _headerInfo;\n _maxMessageSize;\n _maxUnprocessedMessageQueueSize;\n constructor(maxMessageSize = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList();\n this._headerInfo = null;\n this._maxMessageSize = maxMessageSize;\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize;\n }\n write(chunk) {\n if (chunk == null || chunk.length === 0) {\n return [];\n }\n this._buffer.append(chunk);\n if (this._buffer.byteLength > this._maxUnprocessedMessageQueueSize) {\n throw Object.assign(new Error('unprocessed message queue size too large!'), { code: 'ERR_MSG_QUEUE_TOO_BIG' });\n }\n const msgs = [];\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer);\n }\n catch (err) {\n if (err.code === 'ERR_MSG_TOO_BIG') {\n throw err;\n }\n break; // We haven't received enough data yet\n }\n }\n const { id, type, length, offset } = this._headerInfo;\n const bufferedDataLength = this._buffer.length - offset;\n if (bufferedDataLength < length) {\n break; // not enough data yet\n }\n const msg = {\n id,\n type\n };\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.sublist(offset, offset + length);\n }\n msgs.push(msg);\n this._buffer.consume(offset + length);\n this._headerInfo = null;\n }\n return msgs;\n }\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader(data) {\n const { value: h, offset } = readVarInt(data);\n const { value: length, offset: end } = readVarInt(data, offset);\n const type = h & 7;\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`);\n }\n // test message type varint + data length\n if (length > this._maxMessageSize) {\n throw Object.assign(new Error('message size too large!'), { code: 'ERR_MSG_TOO_BIG' });\n }\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length };\n }\n}\nconst MSB = 0x80;\nconst REST = 0x7F;\nfunction readVarInt(buf, offset = 0) {\n let res = 0;\n let shift = 0;\n let counter = offset;\n let b;\n const l = buf.length;\n do {\n if (counter >= l || shift > 49) {\n offset = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf.get(counter++);\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB);\n offset = counter - offset;\n return {\n value: res,\n offset\n };\n}\n//# sourceMappingURL=decode.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { MessageTypes } from './message-types.js';\nconst POOL_SIZE = 10 * 1024;\nclass Encoder {\n _pool;\n _poolOffset;\n constructor() {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n /**\n * Encodes the given message and adds it to the passed list\n */\n write(msg, list) {\n const pool = this._pool;\n let offset = this._poolOffset;\n varint.encode(msg.id << 3 | msg.type, pool, offset);\n offset += varint.encodingLength(msg.id << 3 | msg.type);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset);\n offset += varint.encodingLength(msg.data.length);\n }\n else {\n varint.encode(0, pool, offset);\n offset += varint.encodingLength(0);\n }\n const header = pool.subarray(this._poolOffset, offset);\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n else {\n this._poolOffset = offset;\n }\n list.append(header);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n list.append(msg.data);\n }\n }\n}\nconst encoder = new Encoder();\n/**\n * Encode and yield one or more messages\n */\nexport async function* encode(source) {\n for await (const message of source) {\n const list = new Uint8ArrayList();\n encoder.write(message, list);\n yield list;\n }\n}\n//# sourceMappingURL=encode.js.map","import { CodeError } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport defer, {} from 'p-defer';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { closeSource } from './close-source.js';\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET';\nconst ERR_SINK_INVALID_STATE = 'ERR_SINK_INVALID_STATE';\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000;\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\nexport class AbstractStream {\n id;\n direction;\n timeline;\n protocol;\n metadata;\n source;\n status;\n readStatus;\n writeStatus;\n log;\n sinkController;\n sinkEnd;\n closed;\n endErr;\n streamSource;\n onEnd;\n onCloseRead;\n onCloseWrite;\n onReset;\n onAbort;\n sendCloseWriteTimeout;\n sendingData;\n constructor(init) {\n this.sinkController = new AbortController();\n this.sinkEnd = defer();\n this.closed = defer();\n this.log = init.log;\n // stream status\n this.status = 'open';\n this.readStatus = 'ready';\n this.writeStatus = 'ready';\n this.id = init.id;\n this.metadata = init.metadata ?? {};\n this.direction = init.direction;\n this.timeline = {\n open: Date.now()\n };\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT;\n this.onEnd = init.onEnd;\n this.onCloseRead = init?.onCloseRead;\n this.onCloseWrite = init?.onCloseWrite;\n this.onReset = init?.onReset;\n this.onAbort = init?.onAbort;\n this.source = this.streamSource = pushable({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err);\n }\n else {\n this.log.trace('source ended');\n }\n this.onSourceEnd(err);\n }\n });\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this);\n }\n async sink(source) {\n if (this.writeStatus !== 'ready') {\n throw new CodeError(`writable end state is \"${this.writeStatus}\" not \"ready\"`, ERR_SINK_INVALID_STATE);\n }\n try {\n this.writeStatus = 'writing';\n const options = {\n signal: this.sinkController.signal\n };\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options);\n if (isPromise(res)) {\n await res;\n }\n }\n const abortListener = () => {\n closeSource(source, this.log);\n };\n try {\n this.sinkController.signal.addEventListener('abort', abortListener);\n this.log.trace('sink reading from source');\n for await (let data of source) {\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data;\n const res = this.sendData(data, options);\n if (isPromise(res)) {\n this.sendingData = pDefer();\n await res;\n this.sendingData.resolve();\n this.sendingData = undefined;\n }\n }\n }\n finally {\n this.sinkController.signal.removeEventListener('abort', abortListener);\n }\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus);\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing';\n this.log.trace('send close write to remote');\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n });\n this.writeStatus = 'closed';\n }\n this.onSinkEnd();\n }\n catch (err) {\n this.log.trace('sink ended with error, calling abort with error', err);\n this.abort(err);\n throw err;\n }\n finally {\n this.log.trace('resolve sink end');\n this.sinkEnd.resolve();\n }\n }\n onSourceEnd(err) {\n if (this.timeline.closeRead != null) {\n return;\n }\n this.timeline.closeRead = Date.now();\n this.readStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseRead?.();\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('source ended, waiting for sink to end');\n }\n }\n onSinkEnd(err) {\n if (this.timeline.closeWrite != null) {\n return;\n }\n this.timeline.closeWrite = Date.now();\n this.writeStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseWrite?.();\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('sink ended, waiting for source to end');\n }\n }\n // Close for both Reading and Writing\n async close(options) {\n this.log.trace('closing gracefully');\n this.status = 'closing';\n // wait for read and write ends to close\n await raceSignal(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal);\n this.status = 'closed';\n this.log.trace('closed gracefully');\n }\n async closeRead(options = {}) {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return;\n }\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus);\n const readStatus = this.readStatus;\n this.readStatus = 'closing';\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote');\n await this.sendCloseRead(options);\n }\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength);\n this.streamSource.end();\n }\n this.log.trace('closed readable end of stream');\n }\n async closeWrite(options = {}) {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return;\n }\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus);\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array');\n await raceSignal(this.sink([]), options.signal);\n }\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await raceSignal(this.sendingData.promise, options.signal);\n }\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink');\n this.sinkController.abort();\n await raceSignal(this.sinkEnd.promise, options.signal);\n }\n this.writeStatus = 'closed';\n this.log.trace('closed writable end of stream');\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n this.log('abort with error', err);\n // try to send a reset message\n this.log('try to send reset to remote');\n const res = this.sendReset();\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err);\n });\n }\n this.status = 'aborted';\n this.timeline.abort = Date.now();\n this._closeSinkAndSource(err);\n this.onAbort?.(err);\n }\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n const err = new CodeError('stream reset', ERR_STREAM_RESET);\n this.status = 'reset';\n this.timeline.reset = Date.now();\n this._closeSinkAndSource(err);\n this.onReset?.();\n }\n _closeSinkAndSource(err) {\n this._closeSink(err);\n this._closeSource(err);\n }\n _closeSink(err) {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source');\n this.sinkController.abort();\n }\n this.onSinkEnd(err);\n }\n _closeSource(err) {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength);\n this.readStatus = 'closing';\n this.streamSource.end(err);\n }\n }\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite() {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed');\n return;\n }\n this.log.trace('remote close write');\n this._closeSource();\n }\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead() {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed');\n return;\n }\n this.log.trace('remote close read');\n this._closeSink();\n }\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed');\n return;\n }\n this.log.trace('stream destroyed');\n this._closeSinkAndSource();\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush(data) {\n this.streamSource.push(data);\n }\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength() {\n return this.streamSource.readableLength;\n }\n}\n//# sourceMappingURL=abstract-stream.js.map","import { AbstractStream } from '@libp2p/utils/abstract-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_MSG_SIZE } from './decode.js';\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js';\nexport class MplexStream extends AbstractStream {\n name;\n streamId;\n send;\n types;\n maxDataSize;\n constructor(init) {\n super(init);\n this.types = init.direction === 'outbound' ? InitiatorMessageTypes : ReceiverMessageTypes;\n this.send = init.send;\n this.name = init.name;\n this.streamId = init.streamId;\n this.maxDataSize = init.maxDataSize;\n }\n async sendNewStream() {\n await this.send({ id: this.streamId, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(this.name)) });\n }\n async sendData(data) {\n data = data.sublist();\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize);\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n });\n data.consume(toSend);\n }\n }\n async sendReset() {\n await this.send({ id: this.streamId, type: this.types.RESET });\n }\n async sendCloseWrite() {\n await this.send({ id: this.streamId, type: this.types.CLOSE });\n }\n async sendCloseRead() {\n // mplex does not support close read, only close write\n }\n}\nexport function createStream(options) {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options;\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name ?? id}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n });\n}\n//# sourceMappingURL=stream.js.map","import { CodeError } from '@libp2p/interface';\nimport { closeSource } from '@libp2p/utils/close-source';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { pipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nimport { toString as uint8ArrayToString } from 'uint8arrays';\nimport { Decoder } from './decode.js';\nimport { encode } from './encode.js';\nimport { MessageTypes, MessageTypeNames } from './message-types.js';\nimport { createStream } from './stream.js';\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB\nconst DISCONNECT_THRESHOLD = 5;\nconst CLOSE_TIMEOUT = 500;\nfunction printMessage(msg) {\n const output = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n };\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray());\n }\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16');\n }\n return output;\n}\nexport class MplexStreamMuxer {\n protocol = '/mplex/6.7.0';\n sink;\n source;\n log;\n _streamId;\n _streams;\n _init;\n _source;\n closeController;\n rateLimiter;\n closeTimeout;\n logger;\n constructor(components, init) {\n init = init ?? {};\n this.log = components.logger.forComponent('libp2p:mplex');\n this.logger = components.logger;\n this._streamId = 0;\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n };\n this._init = init;\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT;\n /**\n * An iterable sink\n */\n this.sink = this._createSink();\n /**\n * An iterable source\n */\n this._source = pushable({\n objectMode: true,\n onEnd: () => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy();\n }\n for (const stream of this._streams.receivers.values()) {\n stream.destroy();\n }\n }\n });\n this.source = pipe(this._source, source => encode(source));\n /**\n * Close controller\n */\n this.closeController = new AbortController();\n this.rateLimiter = new RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n });\n }\n /**\n * Returns a Map of streams and their ids\n */\n get streams() {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams = [];\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream);\n }\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream);\n }\n return streams;\n }\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream(name) {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed');\n }\n const id = this._streamId++;\n name = name == null ? id.toString() : name.toString();\n const registry = this._streams.initiators;\n return this._newStream({ id, name, type: 'initiator', registry });\n }\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close(options) {\n if (this.closeController.signal.aborted) {\n return;\n }\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout);\n try {\n // try to gracefully close all streams\n await Promise.all(this.streams.map(async (s) => s.close({\n signal\n })));\n this._source.end();\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n });\n this.closeController.abort();\n }\n catch (err) {\n this.abort(err);\n }\n }\n abort(err) {\n if (this.closeController.signal.aborted) {\n return;\n }\n this.streams.forEach(s => { s.abort(err); });\n this.closeController.abort(err);\n }\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream(options) {\n const { id, name } = options;\n const registry = this._streams.receivers;\n return this._newStream({ id, name, type: 'receiver', registry });\n }\n _newStream(options) {\n const { id, name, type, registry } = options;\n this.log('new %s stream %s', type, id);\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS');\n }\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`);\n }\n const send = async (msg) => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg));\n }\n this._source.push(msg);\n };\n const onEnd = () => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);\n registry.delete(id);\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream);\n }\n };\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });\n registry.set(id, stream);\n return stream;\n }\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink() {\n const sink = async (source) => {\n const abortListener = () => {\n closeSource(source, this.log);\n };\n this.closeController.signal.addEventListener('abort', abortListener);\n try {\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg);\n }\n }\n this._source.end();\n }\n catch (err) {\n this.log('error in sink', err);\n this._source.end(err); // End the source with an error\n }\n finally {\n this.closeController.signal.removeEventListener('abort', abortListener);\n }\n };\n return sink;\n }\n async _handleIncoming(message) {\n const { id, type } = message;\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message));\n }\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open');\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n });\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1);\n }\n catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'));\n return;\n }\n return;\n }\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) });\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream);\n }\n return;\n }\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;\n const stream = list.get(id);\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, MessageTypeNames[type]);\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1);\n }\n catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'));\n return;\n }\n return;\n }\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE;\n try {\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n });\n // Inform the stream consumer they are not fast enough\n throw new CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL');\n }\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data);\n break;\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite();\n break;\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset();\n break;\n default:\n this.log('unknown message type %s', type);\n }\n }\n catch (err) {\n this.log.error('error while processing message', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=mplex.js.map","/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\nimport { serviceCapabilities } from '@libp2p/interface';\nimport { MplexStreamMuxer } from './mplex.js';\nclass Mplex {\n protocol = '/mplex/6.7.0';\n _init;\n components;\n constructor(components, init = {}) {\n this.components = components;\n this._init = init;\n }\n [Symbol.toStringTag] = '@libp2p/mplex';\n [serviceCapabilities] = [\n '@libp2p/stream-multiplexing'\n ];\n createStreamMuxer(init = {}) {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n });\n }\n}\nexport function mplex(init = {}) {\n return (components) => new Mplex(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Return the first value in an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import first from 'it-first'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const res = first(values)\n *\n * console.info(res) // 0\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import first from 'it-first'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const res = await first(values())\n *\n * console.info(res) // 0\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction first(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n })();\n }\n for (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n}\nexport default first;\n//# sourceMappingURL=index.js.map","export const PING_PROTOCOL = '/ipfs/ping/1.0.0';\nexport const PING_LENGTH = 32;\nexport const PROTOCOL_VERSION = '1.0.0';\nexport const PROTOCOL_NAME = 'ping';\nexport const PROTOCOL_PREFIX = 'ipfs';\nexport const TIMEOUT = 10000;\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2;\nexport const MAX_OUTBOUND_STREAMS = 1;\nexport const ERR_WRONG_PING_ACK = 'ERR_WRONG_PING_ACK';\n//# sourceMappingURL=constants.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { CodeError, ERR_INVALID_MESSAGE, ERR_TIMEOUT } from '@libp2p/interface';\nimport first from 'it-first';\nimport { pipe } from 'it-pipe';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS, ERR_WRONG_PING_ACK } from './constants.js';\nexport class PingService {\n protocol;\n components;\n started;\n timeout;\n maxInboundStreams;\n maxOutboundStreams;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.components = components;\n this.log = components.logger.forComponent('libp2p:ping');\n this.started = false;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? TIMEOUT;\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS;\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS;\n this.runOnTransientConnection = init.runOnTransientConnection ?? true;\n this.handleMessage = this.handleMessage.bind(this);\n }\n [Symbol.toStringTag] = '@libp2p/ping';\n async start() {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.components.registrar.unhandle(this.protocol);\n this.started = false;\n }\n isStarted() {\n return this.started;\n }\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage(data) {\n this.log('incoming ping from %p', data.connection.remotePeer);\n const { stream } = data;\n const start = Date.now();\n const signal = AbortSignal.timeout(this.timeout);\n signal.addEventListener('abort', () => {\n stream?.abort(new CodeError('ping timeout', ERR_TIMEOUT));\n });\n void pipe(stream, async function* (source) {\n let received = 0;\n for await (const buf of source) {\n received += buf.byteLength;\n if (received > PING_LENGTH) {\n stream?.abort(new CodeError('Too much data received', ERR_INVALID_MESSAGE));\n return;\n }\n yield buf;\n }\n }, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);\n stream?.abort(err);\n })\n .finally(() => {\n const ms = Date.now() - start;\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms);\n });\n }\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping(peer, options = {}) {\n this.log('pinging %p', peer);\n const start = Date.now();\n const data = randomBytes(PING_LENGTH);\n const connection = await this.components.connectionManager.openConnection(peer, options);\n let stream;\n let onAbort = () => { };\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n onAbort = () => {\n stream?.abort(new CodeError('ping timeout', ERR_TIMEOUT));\n };\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true });\n const result = await pipe([data], stream, async (source) => first(source));\n const ms = Date.now() - start;\n if (result == null) {\n throw new CodeError(`Did not receive a ping ack after ${ms}ms`, ERR_WRONG_PING_ACK);\n }\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new CodeError(`Received wrong ping ack after ${ms}ms`, ERR_WRONG_PING_ACK);\n }\n this.log('ping %p complete in %dms', connection.remotePeer, ms);\n return ms;\n }\n catch (err) {\n this.log.error('error while pinging %p', connection.remotePeer, err);\n stream?.abort(err);\n throw err;\n }\n finally {\n options.signal?.removeEventListener('abort', onAbort);\n if (stream != null) {\n await stream.close();\n }\n }\n }\n}\n//# sourceMappingURL=ping.js.map","/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\nimport { PingService as PingServiceClass } from './ping.js';\nexport function ping(init = {}) {\n return (components) => new PingServiceClass(components, init);\n}\nexport { PING_PROTOCOL } from './constants.js';\n//# sourceMappingURL=index.js.map","export const transportSymbol = Symbol.for('@libp2p/transport');\nexport function isTransport(other) {\n return other != null && Boolean(other[transportSymbol]);\n}\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport var FaultTolerance;\n(function (FaultTolerance) {\n /**\n * should be used for failing in any listen circumstance\n */\n FaultTolerance[FaultTolerance[\"FATAL_ALL\"] = 0] = \"FATAL_ALL\";\n /**\n * should be used for not failing when not listening\n */\n FaultTolerance[FaultTolerance[\"NO_FATAL\"] = 1] = \"NO_FATAL\";\n})(FaultTolerance || (FaultTolerance = {}));\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\nimport { multiaddr, protocols } from '@multiformats/multiaddr';\nconst ASSUME_HTTP_CODES = [\n protocols('tcp').code,\n protocols('dns').code,\n protocols('dnsaddr').code,\n protocols('dns4').code,\n protocols('dns6').code\n];\nfunction extractSNI(ma) {\n let sniProtoCode;\n try {\n sniProtoCode = protocols('sni').code;\n }\n catch (e) {\n // No SNI protocol in multiaddr\n return null;\n }\n for (const [proto, value] of ma) {\n if (proto === sniProtoCode && value !== undefined) {\n return value;\n }\n }\n return null;\n}\nfunction hasTLS(ma) {\n return ma.some(([proto, _]) => proto === protocols('tls').code);\n}\nfunction interpretNext(headProtoCode, headProtoVal, restMa) {\n const interpreter = interpreters[protocols(headProtoCode).name];\n if (interpreter === undefined) {\n throw new Error(`Can't interpret protocol ${protocols(headProtoCode).name}`);\n }\n const restVal = interpreter(headProtoVal, restMa);\n if (headProtoCode === protocols('ip6').code) {\n return `[${restVal}]`;\n }\n return restVal;\n}\nconst interpreters = {\n ip4: (value, restMa) => value,\n ip6: (value, restMa) => {\n if (restMa.length === 0) {\n return value;\n }\n return `[${value}]`;\n },\n tcp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n udp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n dnsaddr: (value, restMa) => value,\n dns4: (value, restMa) => value,\n dns6: (value, restMa) => value,\n dns: (value, restMa) => value,\n ipfs: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/ipfs/${value}`;\n },\n p2p: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p/${value}`;\n },\n http: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `https://${sni}`;\n }\n const protocol = maHasTLS ? 'https://' : 'http://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n 'http-path': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n const baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n const decodedValue = decodeURIComponent(value);\n return `${baseVal}/${decodedValue}`;\n },\n tls: (value, restMa) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n sni: (value, restMa) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n https: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `https://${baseVal}`;\n },\n ws: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `wss://${sni}`;\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n wss: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `wss://${baseVal}`;\n },\n 'p2p-websocket-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-websocket-star`;\n },\n 'p2p-webrtc-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-star`;\n },\n 'p2p-webrtc-direct': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-direct`;\n }\n};\nexport function multiaddrToUri(input, opts) {\n const ma = multiaddr(input);\n const parts = ma.stringTuples();\n const head = parts.pop();\n if (head === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n const protocol = protocols(head[0]);\n const interpreter = interpreters[protocol.name];\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`);\n }\n let uri = interpreter(head[1] ?? '', parts);\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '');\n if (head[1] === '443') {\n uri = `https://${uri}`;\n }\n else {\n uri = `http://${uri}`;\n }\n }\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString();\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1);\n }\n }\n return uri;\n}\n//# sourceMappingURL=index.js.map","export default async (socket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed');\n }\n // if open, return\n if (socket.readyState === 1) {\n return;\n }\n await new Promise((resolve, reject) => {\n function cleanup() {\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('error', handleErr);\n }\n function handleOpen() {\n cleanup();\n resolve();\n }\n function handleErr(event) {\n cleanup();\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`));\n }\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('error', handleErr);\n });\n};\n//# sourceMappingURL=ready.js.map","import ready from './ready.js';\nexport default (socket, options) => {\n options = options ?? {};\n options.closeOnEnd = options.closeOnEnd !== false;\n const sink = async (source) => {\n for await (const data of source) {\n try {\n await ready(socket);\n }\n catch (err) {\n if (err.message === 'socket closed')\n break;\n throw err;\n }\n // the ready promise resolved without error but the socket was closing so\n // exit the loop and don't send data\n if (socket.readyState === socket.CLOSING || socket.readyState === socket.CLOSED) {\n break;\n }\n socket.send(data);\n }\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve();\n }\n else {\n const err = Object.assign(new Error('ws error'), { event });\n reject(err);\n }\n });\n setTimeout(() => { socket.close(); });\n });\n }\n };\n return sink;\n};\n//# sourceMappingURL=sink.js.map","import { EventIterator } from 'event-iterator';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer(obj) {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number');\n}\nexport default (socket) => {\n socket.binaryType = 'arraybuffer';\n const connected = async () => {\n await new Promise((resolve, reject) => {\n if (isConnected) {\n resolve();\n return;\n }\n if (connError != null) {\n reject(connError);\n return;\n }\n const cleanUp = (cont) => {\n socket.removeEventListener('open', onOpen);\n socket.removeEventListener('error', onError);\n cont();\n };\n const onOpen = () => { cleanUp(resolve); };\n const onError = (event) => {\n cleanUp(() => { reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)); });\n };\n socket.addEventListener('open', onOpen);\n socket.addEventListener('error', onError);\n });\n };\n const source = (async function* () {\n const messages = new EventIterator(({ push, stop, fail }) => {\n const onMessage = (event) => {\n let data = null;\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data);\n }\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data);\n }\n if (event.data instanceof Uint8Array) {\n data = event.data;\n }\n if (data == null) {\n return;\n }\n push(data);\n };\n const onError = (event) => { fail(event.error ?? new Error('Socket error')); };\n socket.addEventListener('message', onMessage);\n socket.addEventListener('error', onError);\n socket.addEventListener('close', stop);\n return () => {\n socket.removeEventListener('message', onMessage);\n socket.removeEventListener('error', onError);\n socket.removeEventListener('close', stop);\n };\n }, { highWaterMark: Infinity });\n await connected();\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk;\n }\n }());\n let isConnected = socket.readyState === 1;\n let connError;\n socket.addEventListener('open', () => {\n isConnected = true;\n connError = null;\n });\n socket.addEventListener('close', () => {\n isConnected = false;\n connError = null;\n });\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`);\n }\n });\n return Object.assign(source, {\n connected\n });\n};\n//# sourceMappingURL=source.js.map","/* eslint-env browser */\nexport default WebSocket;\n//# sourceMappingURL=web-socket.browser.js.map","const map = { 'http:': 'ws:', 'https:': 'wss:' };\nconst defaultProtocol = 'ws:';\nexport default (url, location) => {\n if (url.startsWith('//')) {\n url = `${location?.protocol ?? defaultProtocol}${url}`;\n }\n if (url.startsWith('/') && location != null) {\n const proto = location.protocol ?? defaultProtocol;\n const host = location.host;\n const port = location.port != null && host?.endsWith(`:${location.port}`) !== true ? `:${location.port}` : '';\n url = `${proto}//${host}${port}${url}`;\n }\n const wsUrl = new URL(url);\n for (const [httpProto, wsProto] of Object.entries(map)) {\n if (wsUrl.protocol === httpProto) {\n wsUrl.protocol = wsProto;\n }\n }\n return wsUrl;\n};\n//# sourceMappingURL=ws-url.js.map","// load websocket library if we are not in the browser\nimport duplex from './duplex.js';\nimport WebSocket from './web-socket.js';\nimport wsurl from './ws-url.js';\nexport function connect(addr, opts) {\n const location = typeof window === 'undefined' ? undefined : window.location;\n opts = opts ?? {};\n const url = wsurl(addr, location);\n // it's necessary to stringify the URL object otherwise react-native crashes\n const socket = new WebSocket(url.toString(), opts.websocket);\n return duplex(socket, opts);\n}\n//# sourceMappingURL=client.js.map","import sink from './sink.js';\nimport source from './source.js';\nexport default (socket, options) => {\n options = options ?? {};\n const connectedSource = source(socket);\n let remoteAddress = options.remoteAddress;\n let remotePort = options.remotePort;\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url);\n remoteAddress = url.hostname;\n remotePort = parseInt(url.port, 10);\n }\n catch { }\n }\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port');\n }\n const duplex = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => { await connectedSource.connected(); },\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve();\n });\n socket.close();\n });\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate();\n }\n else {\n socket.close();\n }\n },\n remoteAddress,\n remotePort,\n socket\n };\n return duplex;\n};\n//# sourceMappingURL=duplex.js.map","/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent extends Event {\n type;\n detail;\n constructor(type, detail) {\n super(type);\n this.type = type;\n // @ts-expect-error detail may be undefined\n this.detail = detail;\n }\n}\n//# sourceMappingURL=index.js.map","import * as mafmt from '@multiformats/mafmt';\nimport { CODE_CIRCUIT, CODE_P2P, CODE_TCP, CODE_WS, CODE_WSS } from './constants.js';\nexport function all(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSockets.matches(testMa) ||\n mafmt.WebSocketsSecure.matches(testMa);\n });\n}\nexport function wss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSocketsSecure.matches(testMa);\n });\n}\nexport function dnsWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS));\n });\n}\nexport function dnsWsOrWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n if (ma.protoCodes().includes(CODE_CIRCUIT)) {\n return false;\n }\n const testMa = ma.decapsulateCode(CODE_P2P);\n // WS\n if (mafmt.WebSockets.matches(testMa)) {\n return mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WS));\n }\n // WSS\n return mafmt.WebSocketsSecure.matches(testMa) &&\n mafmt.DNS.matches(testMa.decapsulateCode(CODE_TCP).decapsulateCode(CODE_WSS));\n });\n}\n//# sourceMappingURL=filters.js.map","// p2p multi-address code\nexport const CODE_P2P = 421;\nexport const CODE_CIRCUIT = 290;\nexport const CODE_TCP = 6;\nexport const CODE_WS = 477;\nexport const CODE_WSS = 478;\n// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 500;\n//# sourceMappingURL=constants.js.map","/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/9090/ws')\n * await node.dial(ma)\n * ```\n *\n * ## Filters\n *\n * When run in a browser by default this module will only connect to secure web socket addresses.\n *\n * To change this you should pass a filter to the factory function.\n *\n * You can create your own address filters for this transports, or rely in the filters [provided](./src/filters.js).\n *\n * The available filters are:\n *\n * - `filters.all`\n * - Returns all TCP and DNS based addresses, both with `ws` or `wss`.\n * - `filters.dnsWss`\n * - Returns all DNS based addresses with `wss`.\n * - `filters.dnsWsOrWss`\n * - Returns all DNS based addresses, both with `ws` or `wss`.\n *\n * @example Allow dialing insecure WebSockets\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import * as filters from '@libp2p/websockets/filters'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets({\n * // connect to all sockets, even insecure ones\n * filter: filters.all\n * })\n * ]\n * })\n * ```\n */\nimport { CodeError, transportSymbol, serviceCapabilities } from '@libp2p/interface';\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri';\nimport { connect } from 'it-ws/client';\nimport pDefer from 'p-defer';\nimport { CustomProgressEvent } from 'progress-events';\nimport { raceSignal } from 'race-signal';\nimport { isBrowser, isWebWorker } from 'wherearewe';\nimport * as filters from './filters.js';\nimport { createListener } from './listener.js';\nimport { socketToMaConn } from './socket-to-conn.js';\nclass WebSockets {\n log;\n init;\n logger;\n metrics;\n components;\n constructor(components, init) {\n this.log = components.logger.forComponent('libp2p:websockets');\n this.logger = components.logger;\n this.components = components;\n this.init = init;\n if (components.metrics != null) {\n this.metrics = {\n dialerEvents: components.metrics.registerCounterGroup('libp2p_websockets_dialer_events_total', {\n label: 'event',\n help: 'Total count of WebSockets dialer events by type'\n })\n };\n }\n }\n [transportSymbol] = true;\n [Symbol.toStringTag] = '@libp2p/websockets';\n [serviceCapabilities] = [\n '@libp2p/transport'\n ];\n async dial(ma, options) {\n this.log('dialing %s', ma);\n options = options ?? {};\n const socket = await this._connect(ma, options);\n const maConn = socketToMaConn(socket, ma, {\n logger: this.logger,\n metrics: this.metrics?.dialerEvents\n });\n this.log('new outbound connection %s', maConn.remoteAddr);\n const conn = await options.upgrader.upgradeOutbound(maConn, options);\n this.log('outbound connection %s upgraded', maConn.remoteAddr);\n return conn;\n }\n async _connect(ma, options) {\n options?.signal?.throwIfAborted();\n const cOpts = ma.toOptions();\n this.log('dialing %s:%s', cOpts.host, cOpts.port);\n const errorPromise = pDefer();\n const rawSocket = connect(toUri(ma), this.init);\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new CodeError(`Could not connect to ${ma.toString()}`, 'ERR_CONNECTION_FAILED');\n this.log.error('connection error:', err);\n this.metrics?.dialerEvents.increment({ error: true });\n errorPromise.reject(err);\n });\n try {\n options.onProgress?.(new CustomProgressEvent('websockets:open-connection'));\n await raceSignal(Promise.race([rawSocket.connected(), errorPromise.promise]), options.signal);\n }\n catch (err) {\n if (options.signal?.aborted === true) {\n this.metrics?.dialerEvents.increment({ abort: true });\n }\n rawSocket.close()\n .catch(err => {\n this.log.error('error closing raw socket', err);\n });\n throw err;\n }\n this.log('connected %s', ma);\n this.metrics?.dialerEvents.increment({ connect: true });\n return rawSocket;\n }\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener(options) {\n return createListener({\n logger: this.logger,\n metrics: this.components.metrics\n }, {\n ...this.init,\n ...options\n });\n }\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n listenFilter(multiaddrs) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs];\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs);\n }\n // Browser\n if (isBrowser || isWebWorker) {\n return filters.wss(multiaddrs);\n }\n return filters.all(multiaddrs);\n }\n /**\n * Filter check for all Multiaddrs that this transport can dial\n */\n dialFilter(multiaddrs) {\n return this.listenFilter(multiaddrs);\n }\n}\nexport function webSockets(init = {}) {\n return (components) => {\n return new WebSockets(components, init);\n };\n}\n//# sourceMappingURL=index.js.map","import { CodeError } from '@libp2p/interface';\nimport { CLOSE_TIMEOUT } from './constants.js';\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn(stream, remoteAddr, options) {\n const log = options.logger.forComponent('libp2p:websockets:maconn');\n const metrics = options.metrics;\n const metricPrefix = options.metricPrefix ?? '';\n const maConn = {\n log,\n async sink(source) {\n try {\n await stream.sink((async function* () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf;\n }\n else {\n yield buf.subarray();\n }\n }\n })());\n }\n catch (err) {\n if (err.type !== 'aborted') {\n log.error(err);\n }\n }\n },\n source: stream.source,\n remoteAddr,\n timeline: { open: Date.now() },\n async close(options = {}) {\n const start = Date.now();\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n options = {\n ...options,\n signal\n };\n }\n const listener = () => {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s after %dms, destroying it manually', host, port, Date.now() - start);\n this.abort(new CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'));\n };\n options.signal?.addEventListener('abort', listener);\n try {\n await stream.close();\n }\n catch (err) {\n log.error('error closing WebSocket gracefully', err);\n this.abort(err);\n }\n finally {\n options.signal?.removeEventListener('abort', listener);\n maConn.timeline.close = Date.now();\n }\n },\n abort(err) {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s due to error', host, port, err);\n stream.destroy();\n maConn.timeline.close = Date.now();\n // ws WebSocket.terminate does not accept an Error arg to emit an 'error'\n // event on destroy like other node streams so we can't update a metric\n // with an event listener\n // https://github.com/websockets/ws/issues/1752#issuecomment-622380981\n metrics?.increment({ [`${metricPrefix}error`]: true });\n }\n };\n stream.socket.addEventListener('close', () => {\n metrics?.increment({ [`${metricPrefix}close`]: true });\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now();\n }\n }, { once: true });\n return maConn;\n}\n//# sourceMappingURL=socket-to-conn.js.map","export function createListener() {\n throw new Error('WebSocket Servers can not be created in the browser!');\n}\n//# sourceMappingURL=listener.browser.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map","// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\nexport default ms;\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n","/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms';\nimport setup from './common.js';\nconst storage = localstorage();\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n }\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false;\n }\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff);\n if (!this.useColors) {\n return;\n }\n const c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit');\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0;\n let lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, (match) => {\n if (match === '%%') {\n return;\n }\n index++;\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { });\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save(namespaces) {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces);\n }\n else {\n storage?.removeItem('debug');\n }\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load() {\n let r;\n try {\n r = storage?.getItem('debug');\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG;\n }\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\nfunction setupFormatters(formatters) {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v) {\n try {\n return JSON.stringify(v);\n }\n catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n };\n}\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log });\n//# sourceMappingURL=browser.js.map","/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms';\nexport default function setup(env) {\n createDebug.debug = createDebug;\n createDebug.default = createDebug;\n createDebug.coerce = coerce;\n createDebug.disable = disable;\n createDebug.enable = enable;\n createDebug.enabled = enabled;\n createDebug.humanize = humanize;\n createDebug.destroy = destroy;\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key];\n });\n /**\n * The currently active debug mode names, and names to skip.\n */\n createDebug.names = [];\n createDebug.skips = [];\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {};\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor(namespace) {\n let hash = 0;\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n }\n createDebug.selectColor = selectColor;\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug(namespace) {\n let prevTime;\n let enableOverride = null;\n let namespacesCache;\n let enabledCache;\n function debug(...args) {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return;\n }\n const self = debug;\n // Set `diff` timestamp\n const curr = Number(new Date());\n const ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n args[0] = createDebug.coerce(args[0]);\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O');\n }\n // Apply any `formatters` transformations\n let index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%';\n }\n index++;\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format];\n if (typeof formatter === 'function') {\n const val = args[index];\n match = formatter.call(self, val);\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args);\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log;\n logFn.apply(self, args);\n }\n debug.namespace = namespace;\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors();\n debug.color = createDebug.selectColor(namespace);\n debug.extend = extend;\n debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride;\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces;\n enabledCache = createDebug.enabled(namespace);\n }\n return enabledCache;\n },\n set: v => {\n enableOverride = v;\n }\n });\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug);\n }\n // @ts-expect-error some properties are added dynamically\n return debug;\n }\n function extend(namespace, delimiter) {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n newDebug.log = this.log;\n return newDebug;\n }\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable(namespaces) {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces);\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces;\n createDebug.names = [];\n createDebug.skips = [];\n let i;\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n const len = split.length;\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue;\n }\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n }\n else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n }\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable() {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',');\n createDebug.enable('');\n return namespaces;\n }\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled(name) {\n if (name[name.length - 1] === '*') {\n return true;\n }\n let i;\n let len;\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Convert regexp to namespace\n */\n function toNamespace(regexp) {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*');\n }\n /**\n * Coerce `val`.\n */\n function coerce(val) {\n if (val instanceof Error) {\n return val.stack ?? val.message;\n }\n return val;\n }\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy() {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n }\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters);\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load());\n // @ts-expect-error some properties are added dynamically\n return createDebug;\n}\n//# sourceMappingURL=common.js.map","/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n/**\n * Module dependencies.\n */\nimport weald from './node.js';\nexport default weald;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64 } from 'multiformats/bases/base64';\nimport debug from 'weald';\nimport { truncatePeerId } from './utils.js';\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v);\n};\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v) => {\n return v == null ? 'undefined' : base32.baseEncode(v);\n};\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v) => {\n return v == null ? 'undefined' : base64.baseEncode(v);\n};\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\nfunction createDisabledLogger(namespace) {\n const logger = () => { };\n logger.enabled = false;\n logger.color = '';\n logger.diff = 0;\n logger.log = () => { };\n logger.namespace = namespace;\n logger.destroy = () => true;\n logger.extend = () => logger;\n return logger;\n}\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger(peerId, options = {}) {\n return prefixLogger(truncatePeerId(peerId, options));\n}\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger(prefix) {\n return {\n forComponent(name) {\n return logger(`${prefix}:${name}`);\n }\n };\n}\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger() {\n return {\n forComponent(name) {\n return logger(name);\n }\n };\n}\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger(name) {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`);\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r) => r.toString()).find((n) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`);\n }\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n });\n}\nexport function disable() {\n debug.disable();\n}\nexport function enable(namespaces) {\n debug.enable(namespaces);\n}\nexport function enabled(namespaces) {\n return debug.enabled(namespaces);\n}\n//# sourceMappingURL=index.js.map","/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable(iter, map) {\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n const next = iter.next();\n const val = next.value;\n if (next.done === true || val == null) {\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n return {\n done: false,\n value: map(val)\n };\n }\n };\n return iterator;\n}\n//# sourceMappingURL=util.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { mapIterable } from './util.js';\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n set;\n constructor(set) {\n this.set = new Set();\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString());\n }\n }\n }\n get size() {\n return this.set.size;\n }\n [Symbol.iterator]() {\n return this.values();\n }\n add(peer) {\n this.set.add(peer.toString());\n }\n clear() {\n this.set.clear();\n }\n delete(peer) {\n this.set.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.set.entries(), (val) => {\n const peerId = peerIdFromString(val[0]);\n return [peerId, peerId];\n });\n }\n forEach(predicate) {\n this.set.forEach((str) => {\n const id = peerIdFromString(str);\n predicate(id, id, this);\n });\n }\n has(peer) {\n return this.set.has(peer.toString());\n }\n values() {\n return mapIterable(this.set.values(), (val) => {\n return peerIdFromString(val);\n });\n }\n intersection(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n difference(other) {\n const output = new PeerSet();\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n union(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n output.add(peerId);\n }\n for (const peerId of this) {\n output.add(peerId);\n }\n return output;\n }\n}\nexport function peerSet() {\n return new PeerSet();\n}\n//# sourceMappingURL=set.js.map","/**\n * @packageDocumentation\n *\n * Generate, import, and export PeerIDs.\n *\n * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.\n *\n * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.\n *\n * @example\n *\n * ```TypeScript\n * import { createEd25519PeerId } from '@libp2p/peer-id-factory'\n *\n * const peerId = await createEd25519PeerId()\n * console.log(peerId.toString())\n * ```\n *\n * ```bash\n * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD\n * ```\n */\nimport { generateKeyPair, marshalPrivateKey, unmarshalPrivateKey, marshalPublicKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { peerIdFromKeys, peerIdFromBytes } from '@libp2p/peer-id';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { PeerIdProto } from './proto.js';\nexport const createEd25519PeerId = async () => {\n const key = await generateKeyPair('Ed25519');\n const id = await createFromPrivKey(key);\n if (id.type === 'Ed25519') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport const createSecp256k1PeerId = async () => {\n const key = await generateKeyPair('secp256k1');\n const id = await createFromPrivKey(key);\n if (id.type === 'secp256k1') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport const createRSAPeerId = async (opts) => {\n const key = await generateKeyPair('RSA', opts?.bits ?? 2048);\n const id = await createFromPrivKey(key);\n if (id.type === 'RSA') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nexport async function createFromPubKey(publicKey) {\n return peerIdFromKeys(marshalPublicKey(publicKey));\n}\nexport async function createFromPrivKey(privateKey) {\n return peerIdFromKeys(marshalPublicKey(privateKey.public), marshalPrivateKey(privateKey));\n}\nexport function exportToProtobuf(peerId, excludePrivateKey) {\n return PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n });\n}\nexport async function createFromProtobuf(buf) {\n const { id, privKey, pubKey } = PeerIdProto.decode(buf);\n return createFromParts(id ?? new Uint8Array(0), privKey, pubKey);\n}\nexport async function createFromJSON(obj) {\n return createFromParts(uint8ArrayFromString(obj.id, 'base58btc'), obj.privKey != null ? uint8ArrayFromString(obj.privKey, 'base64pad') : undefined, obj.pubKey != null ? uint8ArrayFromString(obj.pubKey, 'base64pad') : undefined);\n}\nasync function createFromParts(multihash, privKey, pubKey) {\n if (privKey != null) {\n const key = await unmarshalPrivateKey(privKey);\n return createFromPrivKey(key);\n }\n else if (pubKey != null) {\n const key = unmarshalPublicKey(pubKey);\n return createFromPubKey(key);\n }\n const peerId = peerIdFromBytes(multihash);\n if (peerId.type !== 'Ed25519' && peerId.type !== 'secp256k1' && peerId.type !== 'RSA') {\n // should not be possible since `multihash` is derived from keys and these\n // are the cryptographic peer id types\n throw new Error('Supplied PeerID is invalid');\n }\n return peerId;\n}\n//# sourceMappingURL=index.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { mapIterable } from './util.js';\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n map;\n constructor(map) {\n this.map = new Map();\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value);\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n clear() {\n this.map.clear();\n }\n delete(peer) {\n return this.map.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.map.entries(), (val) => {\n return [peerIdFromString(val[0]), val[1]];\n });\n }\n forEach(fn) {\n this.map.forEach((value, key) => {\n fn(value, peerIdFromString(key), this);\n });\n }\n get(peer) {\n return this.map.get(peer.toString());\n }\n has(peer) {\n return this.map.has(peer.toString());\n }\n set(peer, value) {\n this.map.set(peer.toString(), value);\n }\n keys() {\n return mapIterable(this.map.keys(), (val) => {\n return peerIdFromString(val);\n });\n }\n values() {\n return this.map.values();\n }\n get size() {\n return this.map.size;\n }\n}\nexport function peerMap() {\n return new PeerMap();\n}\n//# sourceMappingURL=map.js.map","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n run,\n };\n if (this.size && this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n","const events = {};\nconst observable = (worker) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n if (worker.port != null) {\n worker.port.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n }\n};\nobservable.addEventListener = (type, fn) => {\n if (events[type] == null) {\n events[type] = [];\n }\n events[type].push(fn);\n};\nobservable.removeEventListener = (type, fn) => {\n if (events[type] == null) {\n return;\n }\n events[type] = events[type]\n .filter(listener => listener === fn);\n};\nobservable.dispatchEvent = function (type, worker, event) {\n if (events[type] == null) {\n return;\n }\n events[type].forEach(fn => fn(worker, event));\n};\nexport default observable;\n//# sourceMappingURL=index.js.map","export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read';\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read';\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read';\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write';\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write';\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write';\n//# sourceMappingURL=constants.js.map","import observer from 'observable-webworkers';\nimport { WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK } from './constants.js';\nimport { nanoid } from './utils.js';\nconst handleWorkerLockRequest = (emitter, masterEvent, requestType, releaseType, grantType) => {\n return (worker, event) => {\n if (event.data.type !== requestType) {\n return;\n }\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async () => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n });\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener);\n resolve();\n }\n };\n worker.addEventListener('message', releaseEventListener);\n });\n }\n }\n }));\n };\n};\nconst makeWorkerLockRequest = (name, requestType, grantType, releaseType) => {\n return async () => {\n const id = nanoid();\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n });\n return new Promise((resolve) => {\n const listener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n };\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener);\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n });\n });\n }\n };\n globalThis.addEventListener('message', listener);\n });\n };\n};\nconst defaultOptions = {\n singleProcess: false\n};\nexport default (options) => {\n options = Object.assign({}, defaultOptions, options);\n const isPrimary = Boolean(globalThis.document) || options.singleProcess;\n if (isPrimary) {\n const emitter = new EventTarget();\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK));\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK));\n return emitter;\n }\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n };\n};\n//# sourceMappingURL=browser.js.map","export const nanoid = (size = 21) => {\n return Math.random().toString().substring(2);\n};\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\nimport PQueue from 'p-queue';\nimport pTimeout from 'p-timeout';\nimport impl from './node.js';\nconst mutexes = {};\nlet implementation;\nasync function createReleaseable(queue, options) {\n let res;\n const p = new Promise((resolve) => {\n res = resolve;\n });\n void queue.add(async () => pTimeout((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve();\n });\n });\n })(), {\n milliseconds: options.timeout\n }));\n return p;\n}\nconst createMutex = (name, options) => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n };\n }\n const masterQueue = new PQueue({ concurrency: 1 });\n let readQueue;\n return {\n async readLock() {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options);\n }\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n });\n const localReadQueue = readQueue;\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options);\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start();\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null;\n }\n });\n });\n return readPromise;\n },\n async writeLock() {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null;\n return createReleaseable(masterQueue, options);\n }\n };\n};\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n};\nexport default function createMortice(options) {\n const opts = Object.assign({}, defaultOptions, options);\n if (implementation == null) {\n implementation = impl(opts);\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].readLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n implementation.addEventListener('requestWriteLock', async (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].writeLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n }\n }\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts);\n }\n return mutexes[opts.name];\n}\n//# sourceMappingURL=index.js.map","export const codes = {\n ERR_INVALID_PARAMETERS: 'ERR_INVALID_PARAMETERS'\n};\n//# sourceMappingURL=errors.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { encodeMessage, decodeMessage, message } from 'protons-runtime';\nexport var Peer;\n(function (Peer) {\n let Peer$metadataEntry;\n (function (Peer$metadataEntry) {\n let _codec;\n Peer$metadataEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.value);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n key: '',\n value: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string();\n break;\n case 2:\n obj.value = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$metadataEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$metadataEntry.codec());\n };\n Peer$metadataEntry.decode = (buf) => {\n return decodeMessage(buf, Peer$metadataEntry.codec());\n };\n })(Peer$metadataEntry = Peer.Peer$metadataEntry || (Peer.Peer$metadataEntry = {}));\n let Peer$tagsEntry;\n (function (Peer$tagsEntry) {\n let _codec;\n Peer$tagsEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if (obj.value != null) {\n w.uint32(18);\n Tag.codec().encode(obj.value, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n key: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.key = reader.string();\n break;\n case 2:\n obj.value = Tag.codec().decode(reader, reader.uint32());\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$tagsEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$tagsEntry.codec());\n };\n Peer$tagsEntry.decode = (buf) => {\n return decodeMessage(buf, Peer$tagsEntry.codec());\n };\n })(Peer$tagsEntry = Peer.Peer$tagsEntry || (Peer.Peer$tagsEntry = {}));\n let _codec;\n Peer.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10);\n Address.codec().encode(value, w);\n }\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(18);\n w.string(value);\n }\n }\n if (obj.publicKey != null) {\n w.uint32(34);\n w.bytes(obj.publicKey);\n }\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42);\n w.bytes(obj.peerRecordEnvelope);\n }\n if (obj.metadata != null && obj.metadata.size !== 0) {\n for (const [key, value] of obj.metadata.entries()) {\n w.uint32(50);\n Peer.Peer$metadataEntry.codec().encode({ key, value }, w);\n }\n }\n if (obj.tags != null && obj.tags.size !== 0) {\n for (const [key, value] of obj.tags.entries()) {\n w.uint32(58);\n Peer.Peer$tagsEntry.codec().encode({ key, value }, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n addresses: [],\n protocols: [],\n metadata: new Map(),\n tags: new Map()\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.addresses.push(Address.codec().decode(reader, reader.uint32()));\n break;\n case 2:\n obj.protocols.push(reader.string());\n break;\n case 4:\n obj.publicKey = reader.bytes();\n break;\n case 5:\n obj.peerRecordEnvelope = reader.bytes();\n break;\n case 6: {\n const entry = Peer.Peer$metadataEntry.codec().decode(reader, reader.uint32());\n obj.metadata.set(entry.key, entry.value);\n break;\n }\n case 7: {\n const entry = Peer.Peer$tagsEntry.codec().decode(reader, reader.uint32());\n obj.tags.set(entry.key, entry.value);\n break;\n }\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer.encode = (obj) => {\n return encodeMessage(obj, Peer.codec());\n };\n Peer.decode = (buf) => {\n return decodeMessage(buf, Peer.codec());\n };\n})(Peer || (Peer = {}));\nexport var Address;\n(function (Address) {\n let _codec;\n Address.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (obj.isCertified != null) {\n w.uint32(16);\n w.bool(obj.isCertified);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n case 2:\n obj.isCertified = reader.bool();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Address.encode = (obj) => {\n return encodeMessage(obj, Address.codec());\n };\n Address.decode = (buf) => {\n return decodeMessage(buf, Address.codec());\n };\n})(Address || (Address = {}));\nexport var Tag;\n(function (Tag) {\n let _codec;\n Tag.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.value != null && obj.value !== 0)) {\n w.uint32(8);\n w.uint32(obj.value);\n }\n if (obj.expiry != null) {\n w.uint32(16);\n w.uint64(obj.expiry);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n value: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.value = reader.uint32();\n break;\n case 2:\n obj.expiry = reader.uint64();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Tag.encode = (obj) => {\n return encodeMessage(obj, Tag.codec());\n };\n Tag.decode = (buf) => {\n return decodeMessage(buf, Tag.codec());\n };\n})(Tag || (Tag = {}));\n//# sourceMappingURL=peer.js.map","import { peerIdFromPeerId } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { Peer as PeerPB } from '../pb/peer.js';\nexport function bytesToPeer(peerId, buf) {\n const peer = PeerPB.decode(buf);\n if (peer.publicKey != null && peerId.publicKey == null) {\n peerId = peerIdFromPeerId({\n ...peerId,\n publicKey: peerId.publicKey\n });\n }\n const tags = new Map();\n // remove any expired tags\n const now = BigInt(Date.now());\n for (const [key, tag] of peer.tags.entries()) {\n if (tag.expiry != null && tag.expiry < now) {\n continue;\n }\n tags.set(key, tag);\n }\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr: ma, isCertified }) => {\n return {\n multiaddr: multiaddr(ma),\n isCertified: isCertified ?? false\n };\n }),\n metadata: peer.metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined,\n tags\n };\n}\n//# sourceMappingURL=bytes-to-peer.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst pathSepS = '/';\nconst pathSepB = new TextEncoder().encode(pathSepS);\nconst pathSep = pathSepB[0];\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n _buf;\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor(s, clean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s);\n }\n else if (s instanceof Uint8Array) {\n this._buf = s;\n }\n else {\n throw new Error('Invalid key, should be String of Uint8Array');\n }\n if (clean == null) {\n clean = true;\n }\n if (clean) {\n this.clean();\n }\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key');\n }\n }\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString(encoding = 'utf8') {\n return uint8ArrayToString(this._buf, encoding);\n }\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array() {\n return this._buf;\n }\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag]() {\n return `Key(${this.toString()})`;\n }\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces(list) {\n return new Key(list.join(pathSepS));\n }\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random() {\n return new Key(Math.random().toString().substring(2));\n }\n /**\n * @param {*} other\n */\n static asKey(other) {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other);\n }\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array());\n }\n return null;\n }\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean() {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB;\n }\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1);\n bytes.fill(pathSep, 0, 1);\n bytes.set(this._buf, 1);\n this._buf = bytes;\n }\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1);\n }\n }\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less(key) {\n const list1 = this.list();\n const list2 = key.list();\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false;\n }\n const c1 = list1[i];\n const c2 = list2[i];\n if (c1 < c2) {\n return true;\n }\n else if (c1 > c2) {\n return false;\n }\n }\n return list1.length < list2.length;\n }\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse() {\n return Key.withNamespaces(this.list().slice().reverse());\n }\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces() {\n return this.list();\n }\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace() {\n const ns = this.namespaces();\n return ns[ns.length - 1];\n }\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list() {\n return this.toString().split(pathSepS).slice(1);\n }\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type() {\n return namespaceType(this.baseNamespace());\n }\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name() {\n return namespaceValue(this.baseNamespace());\n }\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance(s) {\n return new Key(this.toString() + ':' + s);\n }\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path() {\n let p = this.parent().toString();\n if (!p.endsWith(pathSepS)) {\n p += pathSepS;\n }\n p += this.type();\n return new Key(p);\n }\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent() {\n const list = this.list();\n if (list.length === 1) {\n return new Key(pathSepS);\n }\n return new Key(list.slice(0, -1).join(pathSepS));\n }\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child(key) {\n if (this.toString() === pathSepS) {\n return key;\n }\n else if (key.toString() === pathSepS) {\n return this;\n }\n return new Key(this.toString() + key.toString(), false);\n }\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return other.toString().startsWith(this.toString());\n }\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return this.toString().startsWith(other.toString());\n }\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel() {\n return this.list().length === 1;\n }\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat(...keys) {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))]);\n }\n}\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType(ns) {\n const parts = ns.split(':');\n if (parts.length < 2) {\n return '';\n }\n return parts.slice(0, -1).join(':');\n}\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue(ns) {\n const parts = ns.split(':');\n return parts[parts.length - 1];\n}\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten(arr) {\n return ([]).concat(...arr);\n}\n//# sourceMappingURL=key.js.map","import { CodeError } from '@libp2p/interface';\nimport { isPeerId } from '@libp2p/interface';\nimport { Key } from 'interface-datastore/key';\nimport { codes } from '../errors.js';\nexport const NAMESPACE_COMMON = '/peers/';\nexport function peerIdToDatastoreKey(peerId) {\n if (!isPeerId(peerId) || peerId.type == null) {\n throw new CodeError('Invalid PeerId', codes.ERR_INVALID_PARAMETERS);\n }\n const b32key = peerId.toCID().toString();\n return new Key(`${NAMESPACE_COMMON}${b32key}`);\n}\n//# sourceMappingURL=peer-id-to-datastore-key.js.map","import { CodeError } from '@libp2p/interface';\nimport { isMultiaddr, multiaddr } from '@multiformats/multiaddr';\nimport { codes } from '../errors.js';\nexport async function dedupeFilterAndSortAddresses(peerId, filter, addresses) {\n const addressMap = new Map();\n for (const addr of addresses) {\n if (addr == null) {\n continue;\n }\n if (addr.multiaddr instanceof Uint8Array) {\n addr.multiaddr = multiaddr(addr.multiaddr);\n }\n if (!isMultiaddr(addr.multiaddr)) {\n throw new CodeError('Multiaddr was invalid', codes.ERR_INVALID_PARAMETERS);\n }\n if (!(await filter(peerId, addr.multiaddr))) {\n continue;\n }\n const isCertified = addr.isCertified ?? false;\n const maStr = addr.multiaddr.toString();\n const existingAddr = addressMap.get(maStr);\n if (existingAddr != null) {\n addr.isCertified = existingAddr.isCertified || isCertified;\n }\n else {\n addressMap.set(maStr, {\n multiaddr: addr.multiaddr,\n isCertified\n });\n }\n }\n return [...addressMap.values()]\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString());\n })\n .map(({ isCertified, multiaddr }) => ({\n isCertified,\n multiaddr: multiaddr.bytes\n }));\n}\n//# sourceMappingURL=dedupe-addresses.js.map","import { CodeError } from '@libp2p/interface';\nimport { equals as uint8arrayEquals } from 'uint8arrays/equals';\nimport { codes } from '../errors.js';\nimport { dedupeFilterAndSortAddresses } from './dedupe-addresses.js';\nexport async function toPeerPB(peerId, data, strategy, options) {\n if (data == null) {\n throw new CodeError('Invalid PeerData', codes.ERR_INVALID_PARAMETERS);\n }\n if (data.publicKey != null && peerId.publicKey != null && !uint8arrayEquals(data.publicKey, peerId.publicKey)) {\n throw new CodeError('publicKey bytes do not match peer id publicKey bytes', codes.ERR_INVALID_PARAMETERS);\n }\n const existingPeer = options.existingPeer;\n if (existingPeer != null && !peerId.equals(existingPeer.id)) {\n throw new CodeError('peer id did not match existing peer id', codes.ERR_INVALID_PARAMETERS);\n }\n let addresses = existingPeer?.addresses ?? [];\n let protocols = new Set(existingPeer?.protocols ?? []);\n let metadata = existingPeer?.metadata ?? new Map();\n let tags = existingPeer?.tags ?? new Map();\n let peerRecordEnvelope = existingPeer?.peerRecordEnvelope;\n // when patching, we replace the original fields with passed values\n if (strategy === 'patch') {\n if (data.multiaddrs != null || data.addresses != null) {\n addresses = [];\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n }\n if (data.protocols != null) {\n protocols = new Set(data.protocols);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n metadata = createSortedMap(metadataEntries, {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n tags = createSortedMap(tagsEntries, {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n // when merging, we join the original fields with passed values\n if (strategy === 'merge') {\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n if (data.protocols != null) {\n protocols = new Set([...protocols, ...data.protocols]);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n for (const [key, value] of metadataEntries) {\n if (value == null) {\n metadata.delete(key);\n }\n else {\n metadata.set(key, value);\n }\n }\n metadata = createSortedMap([...metadata.entries()], {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n const mergedTags = new Map(tags);\n for (const [key, value] of tagsEntries) {\n if (value == null) {\n mergedTags.delete(key);\n }\n else {\n mergedTags.set(key, value);\n }\n }\n tags = createSortedMap([...mergedTags.entries()], {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n const output = {\n addresses: await dedupeFilterAndSortAddresses(peerId, options.addressFilter ?? (async () => true), addresses),\n protocols: [...protocols.values()].sort((a, b) => {\n return a.localeCompare(b);\n }),\n metadata,\n tags,\n publicKey: existingPeer?.id.publicKey ?? data.publicKey ?? peerId.publicKey,\n peerRecordEnvelope\n };\n // Ed25519 and secp256k1 have their public key embedded in them so no need to duplicate it\n if (peerId.type !== 'RSA') {\n delete output.publicKey;\n }\n return output;\n}\n/**\n * In JS maps are ordered by insertion order so create a new map with the\n * keys inserted in alphabetical order.\n */\nfunction createSortedMap(entries, options) {\n const output = new Map();\n for (const [key, value] of entries) {\n if (value == null) {\n continue;\n }\n options.validate(key, value);\n }\n for (const [key, value] of entries.sort(([a], [b]) => {\n return a.localeCompare(b);\n })) {\n if (value != null) {\n output.set(key, options.map?.(key, value) ?? value);\n }\n }\n return output;\n}\nfunction validateMetadata(key, value) {\n if (typeof key !== 'string') {\n throw new CodeError('Metadata key must be a string', codes.ERR_INVALID_PARAMETERS);\n }\n if (!(value instanceof Uint8Array)) {\n throw new CodeError('Metadata value must be a Uint8Array', codes.ERR_INVALID_PARAMETERS);\n }\n}\nfunction validateTag(key, tag) {\n if (typeof key !== 'string') {\n throw new CodeError('Tag name must be a string', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.value != null) {\n if (parseInt(`${tag.value}`, 10) !== tag.value) {\n throw new CodeError('Tag value must be an integer', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.value < 0 || tag.value > 100) {\n throw new CodeError('Tag value must be between 0-100', codes.ERR_INVALID_PARAMETERS);\n }\n }\n if (tag.ttl != null) {\n if (parseInt(`${tag.ttl}`, 10) !== tag.ttl) {\n throw new CodeError('Tag ttl must be an integer', codes.ERR_INVALID_PARAMETERS);\n }\n if (tag.ttl < 0) {\n throw new CodeError('Tag ttl must be between greater than 0', codes.ERR_INVALID_PARAMETERS);\n }\n }\n}\nfunction mapTag(key, tag) {\n let expiry;\n if (tag.expiry != null) {\n expiry = tag.expiry;\n }\n if (tag.ttl != null) {\n expiry = BigInt(Date.now() + Number(tag.ttl));\n }\n return {\n value: tag.value ?? 0,\n expiry\n };\n}\n//# sourceMappingURL=to-peer-pb.js.map","import { CodeError } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { peerIdFromBytes } from '@libp2p/peer-id';\nimport mortice, {} from 'mortice';\nimport { base32 } from 'multiformats/bases/base32';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { codes } from './errors.js';\nimport { Peer as PeerPB } from './pb/peer.js';\nimport { bytesToPeer } from './utils/bytes-to-peer.js';\nimport { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js';\nimport { toPeerPB } from './utils/to-peer-pb.js';\nfunction decodePeer(key, value, cache) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2];\n const buf = base32.decode(base32Str);\n const peerId = peerIdFromBytes(buf);\n const cached = cache.get(peerId);\n if (cached != null) {\n return cached;\n }\n const peer = bytesToPeer(peerId, value);\n cache.set(peerId, peer);\n return peer;\n}\nfunction mapQuery(query, cache) {\n if (query == null) {\n return {};\n }\n return {\n prefix: NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, cache));\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache));\n })\n };\n}\nexport class PersistentStore {\n peerId;\n datastore;\n lock;\n addressFilter;\n constructor(components, init = {}) {\n this.peerId = components.peerId;\n this.datastore = components.datastore;\n this.addressFilter = init.addressFilter;\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n });\n }\n async has(peerId) {\n return this.datastore.has(peerIdToDatastoreKey(peerId));\n }\n async delete(peerId) {\n if (this.peerId.equals(peerId)) {\n throw new CodeError('Cannot delete self peer', codes.ERR_INVALID_PARAMETERS);\n }\n await this.datastore.delete(peerIdToDatastoreKey(peerId));\n }\n async load(peerId) {\n const buf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n return bytesToPeer(peerId, buf);\n }\n async save(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async patch(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async merge(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async *all(query) {\n const peerCache = new PeerMap();\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {\n const peer = decodePeer(key, value, peerCache);\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue;\n }\n yield peer;\n }\n }\n async #findExistingPeer(peerId) {\n try {\n const existingBuf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n const existingPeer = bytesToPeer(peerId, existingBuf);\n return {\n existingBuf,\n existingPeer\n };\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n return {};\n }\n async #saveIfDifferent(peerId, peer, existingBuf, existingPeer) {\n const buf = PeerPB.encode(peer);\n if (existingBuf != null && uint8ArrayEquals(buf, existingBuf)) {\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: false\n };\n }\n await this.datastore.put(peerIdToDatastoreKey(peerId), buf);\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: true\n };\n }\n}\n//# sourceMappingURL=store.js.map","/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport all from 'it-all';\nimport { PersistentStore } from './store.js';\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nexport class PersistentPeerStore {\n store;\n events;\n peerId;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.events = components.events;\n this.peerId = components.peerId;\n this.store = new PersistentStore(components, init);\n }\n [Symbol.toStringTag] = '@libp2p/peer-store';\n async forEach(fn, query) {\n this.log.trace('forEach await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('forEach got read lock');\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer);\n }\n }\n finally {\n this.log.trace('forEach release read lock');\n release();\n }\n }\n async all(query) {\n this.log.trace('all await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('all got read lock');\n try {\n return await all(this.store.all(query));\n }\n finally {\n this.log.trace('all release read lock');\n release();\n }\n }\n async delete(peerId) {\n this.log.trace('delete await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('delete got write lock');\n try {\n await this.store.delete(peerId);\n }\n finally {\n this.log.trace('delete release write lock');\n release();\n }\n }\n async has(peerId) {\n this.log.trace('has await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('has got read lock');\n try {\n return await this.store.has(peerId);\n }\n finally {\n this.log.trace('has release read lock');\n release();\n }\n }\n async get(peerId) {\n this.log.trace('get await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('get got read lock');\n try {\n return await this.store.load(peerId);\n }\n finally {\n this.log.trace('get release read lock');\n release();\n }\n }\n async save(id, data) {\n this.log.trace('save await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('save got write lock');\n try {\n const result = await this.store.save(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('save release write lock');\n release();\n }\n }\n async patch(id, data) {\n this.log.trace('patch await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('patch got write lock');\n try {\n const result = await this.store.patch(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('patch release write lock');\n release();\n }\n }\n async merge(id, data) {\n this.log.trace('merge await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('merge got write lock');\n try {\n const result = await this.store.merge(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('merge release write lock');\n release();\n }\n }\n async consumePeerRecord(buf, expectedPeer) {\n const envelope = await RecordEnvelope.openAndCertify(buf, PeerRecord.DOMAIN);\n if (expectedPeer?.equals(envelope.peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, envelope.peerId);\n return false;\n }\n const peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n let peer;\n try {\n peer = await this.get(envelope.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n return false;\n }\n }\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n });\n return true;\n }\n #emitIfUpdated(id, result) {\n if (!result.updated) {\n return;\n }\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result });\n }\n else {\n this.events.safeDispatchEvent('peer:update', { detail: result });\n }\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction drain(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n })();\n }\n else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\nexport default drain;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\nimport peek from 'it-peekable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction filter(source, fn) {\n let index = 0;\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source);\n const { value, done } = peekable.next();\n if (done === true) {\n return (function* () { }());\n }\n const res = fn(value, index++);\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function* () {\n if (await res) {\n yield value;\n }\n for await (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n const func = fn;\n return (function* () {\n if (res === true) {\n yield value;\n }\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry;\n }\n }\n })();\n}\nexport default filter;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\nfunction peekable(iterable) {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator];\n const queue = [];\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next();\n },\n push: (value) => {\n queue.push(value);\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n };\n }\n return iterator.next();\n },\n [symbol]() {\n return this;\n }\n };\n}\nexport default peekable;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\nimport all from 'it-all';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction sort(source, sorter) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n const arr = await all(source);\n yield* arr.sort(sorter);\n })();\n }\n return (function* () {\n const arr = all(source);\n yield* arr.sort(sorter);\n })();\n}\nexport default sort;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction take(source, limit) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for await (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n }\n return (function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n}\nexport default take;\n//# sourceMappingURL=index.js.map","import drain from 'it-drain';\nimport filter from 'it-filter';\nimport sort from 'it-sort';\nimport take from 'it-take';\nexport class BaseDatastore {\n put(key, val, options) {\n return Promise.reject(new Error('.put is not implemented'));\n }\n get(key, options) {\n return Promise.reject(new Error('.get is not implemented'));\n }\n has(key, options) {\n return Promise.reject(new Error('.has is not implemented'));\n }\n delete(key, options) {\n return Promise.reject(new Error('.delete is not implemented'));\n }\n async *putMany(source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options);\n yield key;\n }\n }\n async *getMany(source, options = {}) {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n };\n }\n }\n async *deleteMany(source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options);\n yield key;\n }\n }\n batch() {\n let puts = [];\n let dels = [];\n return {\n put(key, value) {\n puts.push({ key, value });\n },\n delete(key) {\n dels.push(key);\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options));\n puts = [];\n await drain(this.deleteMany(dels, options));\n dels = [];\n }\n };\n }\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_all(q, options) {\n throw new Error('._all is not implemented');\n }\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_allKeys(q, options) {\n throw new Error('._allKeys is not implemented');\n }\n query(q, options) {\n let it = this._all(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (e) => e.key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n let i = 0;\n const offset = q.offset;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n queryKeys(q, options) {\n let it = this._allKeys(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (key) => key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n const offset = q.offset;\n let i = 0;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n}\n//# sourceMappingURL=base.js.map","import { Key } from 'interface-datastore/key';\nimport { BaseDatastore } from './base.js';\nimport * as Errors from './errors.js';\nexport class MemoryDatastore extends BaseDatastore {\n data;\n constructor() {\n super();\n this.data = new Map();\n }\n put(key, val) {\n this.data.set(key.toString(), val);\n return key;\n }\n get(key) {\n const result = this.data.get(key.toString());\n if (result == null) {\n throw Errors.notFoundError();\n }\n return result;\n }\n has(key) {\n return this.data.has(key.toString());\n }\n delete(key) {\n this.data.delete(key.toString());\n }\n *_all() {\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value };\n }\n }\n *_allKeys() {\n for (const key of this.data.keys()) {\n yield new Key(key);\n }\n }\n}\n//# sourceMappingURL=memory.js.map","import errCode from 'err-code';\nexport function dbOpenFailedError(err) {\n err = err ?? new Error('Cannot open database');\n return errCode(err, 'ERR_DB_OPEN_FAILED');\n}\nexport function dbDeleteFailedError(err) {\n err = err ?? new Error('Delete failed');\n return errCode(err, 'ERR_DB_DELETE_FAILED');\n}\nexport function dbWriteFailedError(err) {\n err = err ?? new Error('Write failed');\n return errCode(err, 'ERR_DB_WRITE_FAILED');\n}\nexport function dbReadFailedError(err) {\n err = err ?? new Error('Read failed');\n return errCode(err, 'ERR_DB_READ_FAILED');\n}\nexport function notFoundError(err) {\n err = err ?? new Error('Not Found');\n return errCode(err, 'ERR_NOT_FOUND');\n}\nexport function abortedError(err) {\n err = err ?? new Error('Aborted');\n return errCode(err, 'ERR_ABORTED');\n}\n//# sourceMappingURL=errors.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { debounce } from './utils.js';\nconst defaultAddressFilter = (addrs) => addrs;\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId(ma, peerId) {\n const observedPeerIdStr = ma.getPeerId();\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = peerIdFromString(observedPeerIdStr);\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId.toString()}`));\n }\n }\n return ma;\n}\nexport class DefaultAddressManager {\n log;\n components;\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n listen;\n announce;\n observed;\n announceFilter;\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor(components, init = {}) {\n const { listen = [], announce = [] } = init;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:address-manager');\n this.listen = listen.map(ma => ma.toString());\n this.announce = new Set(announce.map(ma => ma.toString()));\n this.observed = new Map();\n this.announceFilter = init.announceFilter ?? defaultAddressFilter;\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = debounce(this._updatePeerStoreAddresses.bind(this), 1000);\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses();\n });\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses();\n });\n }\n [Symbol.toStringTag] = '@libp2p/address-manager';\n _updatePeerStoreAddresses() {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat([...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => multiaddr(str))).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`);\n }\n return ma;\n });\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err); });\n }\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs() {\n return Array.from(this.listen).map((a) => multiaddr(a));\n }\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs() {\n return Array.from(this.announce).map((a) => multiaddr(a));\n }\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs() {\n return Array.from(this.observed).map(([a]) => multiaddr(a));\n }\n /**\n * Add peer observed addresses\n */\n addObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return;\n }\n this.observed.set(addrString, {\n confident: false\n });\n }\n confirmObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n };\n const startingConfidence = metadata.confident;\n this.observed.set(addrString, {\n confident: true\n });\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses();\n }\n }\n removeObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n this.observed.delete(addrString);\n }\n getAddresses() {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString());\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString());\n }\n // add observed addresses we are confident in\n addrs = addrs.concat(Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma));\n // dedupe multiaddrs\n const addrSet = new Set(addrs);\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => multiaddr(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma;\n }\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma;\n }\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`);\n });\n }\n}\n//# sourceMappingURL=index.js.map","export function debounce(func, wait) {\n let timeout;\n return function () {\n const later = function () {\n timeout = undefined;\n func();\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n}\n//# sourceMappingURL=utils.js.map","import { CodeError, serviceCapabilities, serviceDependencies } from '@libp2p/interface';\nimport { isStartable } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nclass DefaultComponents {\n components = {};\n _started = false;\n constructor(init = {}) {\n this.components = {};\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value;\n }\n if (this.components.logger == null) {\n this.components.logger = defaultLogger();\n }\n }\n isStarted() {\n return this._started;\n }\n async _invokeStartableMethod(methodName) {\n await Promise.all(Object.values(this.components)\n .filter(obj => isStartable(obj))\n .map(async (startable) => {\n await startable[methodName]?.();\n }));\n }\n async beforeStart() {\n await this._invokeStartableMethod('beforeStart');\n }\n async start() {\n await this._invokeStartableMethod('start');\n this._started = true;\n }\n async afterStart() {\n await this._invokeStartableMethod('afterStart');\n }\n async beforeStop() {\n await this._invokeStartableMethod('beforeStop');\n }\n async stop() {\n await this._invokeStartableMethod('stop');\n this._started = false;\n }\n async afterStop() {\n await this._invokeStartableMethod('afterStop');\n }\n}\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n];\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n];\nexport function defaultComponents(init = {}) {\n const components = new DefaultComponents(init);\n const proxy = new Proxy(components, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop];\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new CodeError(`${prop} not set`, 'ERR_SERVICE_MISSING');\n }\n return service;\n }\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value;\n }\n else {\n Reflect.set(target, prop, value);\n }\n return true;\n }\n });\n // @ts-expect-error component keys are proxied\n return proxy;\n}\nexport function checkServiceDependencies(components) {\n const serviceCapabilities = {};\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceCapabilities(service)) {\n serviceCapabilities[capability] = true;\n }\n }\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceDependencies(service)) {\n if (serviceCapabilities[capability] !== true) {\n throw new CodeError(`Service \"${getServiceName(service)}\" required capability \"${capability}\" but it was not provided by any component, you may need to add additional configuration when creating your node.`, 'ERR_UNMET_SERVICE_DEPENDENCIES');\n }\n }\n }\n}\nfunction getServiceCapabilities(service) {\n if (Array.isArray(service?.[serviceCapabilities])) {\n return service[serviceCapabilities];\n }\n return [];\n}\nfunction getServiceDependencies(service) {\n if (Array.isArray(service?.[serviceDependencies])) {\n return service[serviceDependencies];\n }\n return [];\n}\nfunction getServiceName(service) {\n return service?.[Symbol.toStringTag] ?? service?.toString() ?? 'unknown';\n}\n//# sourceMappingURL=components.js.map","export function isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nexport async function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nexport async function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { Netmask } from 'netmask';\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n];\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new Netmask(ipRange));\nfunction ipv4Check(ipAddr) {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr))\n return true;\n }\n return false;\n}\nfunction isIpv4MappedIpv6(ipAddr) {\n return /^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(ipAddr);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2\n */\nfunction ipv4MappedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n if (parts.length < 2) {\n return false;\n }\n const octet34 = parts[parts.length - 1].padStart(4, '0');\n const octet12 = parts[parts.length - 2].padStart(4, '0');\n const ip4 = `${parseInt(octet12.substring(0, 2), 16)}.${parseInt(octet12.substring(2), 16)}.${parseInt(octet34.substring(0, 2), 16)}.${parseInt(octet34.substring(2), 16)}`;\n return ipv4Check(ip4);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.2 example 3\n */\nfunction isIpv4EmbeddedIpv6(ipAddr) {\n return /^::ffff:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr);\n}\nfunction ipv4EmbeddedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n const ip4 = parts[parts.length - 1];\n return ipv4Check(ip4);\n}\nfunction ipv6Check(ipAddr) {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr);\n}\nexport function isPrivateIp(ip) {\n if (isIPv4(ip))\n return ipv4Check(ip);\n else if (isIpv4MappedIpv6(ip))\n return ipv4MappedIpv6Check(ip);\n else if (isIpv4EmbeddedIpv6(ip))\n return ipv4EmbeddedIpv6Check(ip);\n else if (isIPv6(ip))\n return ipv6Check(ip);\n else\n return undefined;\n}\n//# sourceMappingURL=private-ip.js.map","import { isPrivateIp } from '@libp2p/utils/private-ip';\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nexport function connectionGater(gater = {}) {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr) => {\n const tuples = multiaddr.stringTuples();\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean(isPrivateIp(`${tuples[0][1]}`));\n }\n return false;\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n };\n}\n//# sourceMappingURL=connection-gater.browser.js.map","import { isPrivateIp } from '../private-ip.js';\n/**\n * Check if a given multiaddr has a private address.\n */\nexport function isPrivate(ma) {\n try {\n const { address } = ma.nodeAddress();\n return Boolean(isPrivateIp(address));\n }\n catch {\n return true;\n }\n}\n//# sourceMappingURL=is-private.js.map","/**\n * @packageDocumentation\n *\n * Provides strategies to sort a list of multiaddrs.\n *\n * @example\n *\n * ```typescript\n * import { publicAddressesFirst } from '@libp2p/utils/address-sort'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n *\n * const addresses = [\n * multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * multiaddr('/ip4/82.41.53.1/tcp/9000')\n * ].sort(publicAddressesFirst)\n *\n * console.info(addresses)\n * // ['/ip4/82.41.53.1/tcp/9000', '/ip4/127.0.0.1/tcp/9000']\n * ```\n */\nimport { Circuit } from '@multiformats/multiaddr-matcher';\nimport { isPrivate } from './multiaddr/is-private.js';\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nexport function publicAddressesFirst(a, b) {\n const isAPrivate = isPrivate(a.multiaddr);\n const isBPrivate = isPrivate(b.multiaddr);\n if (isAPrivate && !isBPrivate) {\n return 1;\n }\n else if (!isAPrivate && isBPrivate) {\n return -1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nexport function certifiedAddressesFirst(a, b) {\n if (a.isCertified && !b.isCertified) {\n return -1;\n }\n else if (!a.isCertified && b.isCertified) {\n return 1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * start of the array.\n */\nexport function circuitRelayAddressesLast(a, b) {\n const isACircuit = Circuit.exactMatch(a.multiaddr);\n const isBCircuit = Circuit.exactMatch(b.multiaddr);\n if (isACircuit && !isBCircuit) {\n return 1;\n }\n else if (!isACircuit && isBCircuit) {\n return -1;\n }\n return 0;\n}\nexport function defaultAddressSort(a, b) {\n const publicResult = publicAddressesFirst(a, b);\n if (publicResult !== 0) {\n return publicResult;\n }\n const relayResult = circuitRelayAddressesLast(a, b);\n if (relayResult !== 0) {\n return relayResult;\n }\n const certifiedResult = certifiedAddressesFirst(a, b);\n return certifiedResult;\n}\n//# sourceMappingURL=address-sort.js.map","import { RecordType } from '../index.js';\nexport function getTypes(types) {\n const DEFAULT_TYPES = [\n RecordType.A\n ];\n if (types == null) {\n return DEFAULT_TYPES;\n }\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES;\n }\n return types;\n }\n return [\n types\n ];\n}\n//# sourceMappingURL=get-types.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RecordType } from '../index.js';\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60;\nexport function toDNSResponse(obj) {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n };\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n };\n })\n };\n}\n//# sourceMappingURL=to-dns-response.js.map","/* eslint-env browser */\nimport PQueue from 'p-queue';\nimport { CustomProgressEvent } from 'progress-events';\nimport { RecordType } from '../index.js';\nimport { getTypes } from '../utils/get-types.js';\nimport { toDNSResponse } from '../utils/to-dns-response.js';\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4;\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps(url, init = {}) {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n });\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams();\n searchParams.set('name', fqdn);\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type]);\n });\n options.onProgress?.(new CustomProgressEvent('dns:query', { detail: fqdn }));\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`);\n }\n const response = toDNSResponse(await res.json());\n options.onProgress?.(new CustomProgressEvent('dns:response', { detail: response }));\n return response;\n }, {\n signal: options.signal\n });\n if (response == null) {\n throw new Error('No DNS response received');\n }\n return response;\n };\n}\n//# sourceMappingURL=dns-json-over-https.js.map","/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\nimport { DNS as DNSClass } from './dns.js';\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport var RecordType;\n(function (RecordType) {\n RecordType[RecordType[\"A\"] = 1] = \"A\";\n RecordType[RecordType[\"CNAME\"] = 5] = \"CNAME\";\n RecordType[RecordType[\"TXT\"] = 16] = \"TXT\";\n RecordType[RecordType[\"AAAA\"] = 28] = \"AAAA\";\n})(RecordType || (RecordType = {}));\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32;\nexport function dns(init = {}) {\n return new DNSClass(init);\n}\n//# sourceMappingURL=index.js.map","import hashlru from 'hashlru';\nimport { RecordType } from '../index.js';\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js';\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n lru;\n constructor(maxSize) {\n this.lru = hashlru(maxSize);\n }\n get(fqdn, types) {\n let foundAllAnswers = true;\n const answers = [];\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type);\n if (cached.length === 0) {\n foundAllAnswers = false;\n break;\n }\n answers.push(...cached);\n }\n if (foundAllAnswers) {\n return toDNSResponse({ answers });\n }\n }\n getAnswers(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n const answers = this.lru.get(key);\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now();\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }));\n if (cachedAnswers.length === 0) {\n this.lru.remove(key);\n }\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers;\n }\n return [];\n }\n add(domain, answer) {\n const key = `${domain.toLowerCase()}-${answer.type}`;\n const answers = this.lru.get(key) ?? [];\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n });\n this.lru.set(key, answers);\n }\n remove(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n this.lru.remove(key);\n }\n clear() {\n this.lru.clear();\n }\n}\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache(size) {\n return new CachedAnswers(size);\n}\n//# sourceMappingURL=cache.js.map","import { CustomProgressEvent } from 'progress-events';\nimport { defaultResolver } from './resolvers/default.js';\nimport { cache } from './utils/cache.js';\nimport { getTypes } from './utils/get-types.js';\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000;\nexport class DNS {\n resolvers;\n cache;\n constructor(init) {\n this.resolvers = {};\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE);\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver];\n }\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`;\n }\n this.resolvers[tld] = resolver;\n });\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver();\n }\n }\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query(domain, options = {}) {\n const types = getTypes(options.types);\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined;\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent('dns:cache', { detail: cached }));\n return cached;\n }\n const tld = `${domain.split('.').pop()}.`;\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1;\n });\n const errors = [];\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break;\n }\n try {\n const result = await resolver(domain, {\n ...options,\n types\n });\n for (const answer of result.Answer) {\n this.cache.add(domain, answer);\n }\n return result;\n }\n catch (err) {\n errors.push(err);\n options.onProgress?.(new CustomProgressEvent('dns:error', { detail: err }));\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateError(errors, `DNS lookup of ${domain} ${types} failed`);\n }\n}\n//# sourceMappingURL=dns.js.map","import { dnsJsonOverHttps } from './dns-json-over-https.js';\nexport function defaultResolver() {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ];\n}\n//# sourceMappingURL=default.browser.js.map","import { dns, RecordType } from '@multiformats/dns';\nimport { multiaddr } from '../index.js';\nimport { getProtocol } from '../protocols-table.js';\nconst MAX_RECURSIVE_DEPTH = 32;\nconst { code: dnsaddrCode } = getProtocol('dnsaddr');\nclass RecursionLimitError extends Error {\n constructor(message = 'Max recursive depth reached') {\n super(message);\n this.name = 'RecursionLimitError';\n }\n}\nexport const dnsaddrResolver = async function dnsaddrResolver(ma, options = {}) {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH;\n if (recursionLimit === 0) {\n throw new RecursionLimitError('Max recursive depth reached');\n }\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? [];\n const resolver = options?.dns ?? dns();\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n RecordType.TXT\n ]\n });\n const peerId = ma.getPeerId();\n const output = [];\n for (const answer of result.Answer) {\n const addr = answer.data\n .replace(/[\"']/g, '')\n .trim()\n .split('=')[1];\n if (addr == null) {\n continue;\n }\n if (peerId != null && !addr.includes(peerId)) {\n continue;\n }\n const ma = multiaddr(addr);\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n });\n output.push(...resolved.map(ma => ma.toString()));\n }\n else {\n output.push(ma.toString());\n }\n }\n return output;\n};\n//# sourceMappingURL=dnsaddr.js.map","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","export var messages;\n(function (messages) {\n messages[\"NOT_STARTED_YET\"] = \"The libp2p node is not started yet\";\n messages[\"ERR_PROTECTOR_REQUIRED\"] = \"Private network is enforced, but no protector was provided\";\n messages[\"NOT_FOUND\"] = \"Not found\";\n})(messages || (messages = {}));\nexport var codes;\n(function (codes) {\n codes[\"ERR_PROTECTOR_REQUIRED\"] = \"ERR_PROTECTOR_REQUIRED\";\n codes[\"ERR_PEER_DIAL_INTERCEPTED\"] = \"ERR_PEER_DIAL_INTERCEPTED\";\n codes[\"ERR_CONNECTION_INTERCEPTED\"] = \"ERR_CONNECTION_INTERCEPTED\";\n codes[\"ERR_INVALID_PROTOCOLS_FOR_STREAM\"] = \"ERR_INVALID_PROTOCOLS_FOR_STREAM\";\n codes[\"ERR_CONNECTION_ENDED\"] = \"ERR_CONNECTION_ENDED\";\n codes[\"ERR_CONNECTION_FAILED\"] = \"ERR_CONNECTION_FAILED\";\n codes[\"ERR_NODE_NOT_STARTED\"] = \"ERR_NODE_NOT_STARTED\";\n codes[\"ERR_ALREADY_ABORTED\"] = \"ERR_ALREADY_ABORTED\";\n codes[\"ERR_TOO_MANY_ADDRESSES\"] = \"ERR_TOO_MANY_ADDRESSES\";\n codes[\"ERR_NO_VALID_ADDRESSES\"] = \"ERR_NO_VALID_ADDRESSES\";\n codes[\"ERR_RELAYED_DIAL\"] = \"ERR_RELAYED_DIAL\";\n codes[\"ERR_DIALED_SELF\"] = \"ERR_DIALED_SELF\";\n codes[\"ERR_DISCOVERED_SELF\"] = \"ERR_DISCOVERED_SELF\";\n codes[\"ERR_DUPLICATE_TRANSPORT\"] = \"ERR_DUPLICATE_TRANSPORT\";\n codes[\"ERR_ENCRYPTION_FAILED\"] = \"ERR_ENCRYPTION_FAILED\";\n codes[\"ERR_HOP_REQUEST_FAILED\"] = \"ERR_HOP_REQUEST_FAILED\";\n codes[\"ERR_INVALID_KEY\"] = \"ERR_INVALID_KEY\";\n codes[\"ERR_INVALID_MESSAGE\"] = \"ERR_INVALID_MESSAGE\";\n codes[\"ERR_INVALID_PARAMETERS\"] = \"ERR_INVALID_PARAMETERS\";\n codes[\"ERR_INVALID_PEER\"] = \"ERR_INVALID_PEER\";\n codes[\"ERR_MUXER_UNAVAILABLE\"] = \"ERR_MUXER_UNAVAILABLE\";\n codes[\"ERR_NOT_FOUND\"] = \"ERR_NOT_FOUND\";\n codes[\"ERR_TRANSPORT_UNAVAILABLE\"] = \"ERR_TRANSPORT_UNAVAILABLE\";\n codes[\"ERR_TRANSPORT_DIAL_FAILED\"] = \"ERR_TRANSPORT_DIAL_FAILED\";\n codes[\"ERR_UNSUPPORTED_PROTOCOL\"] = \"ERR_UNSUPPORTED_PROTOCOL\";\n codes[\"ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED\"] = \"ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED\";\n codes[\"ERR_INVALID_MULTIADDR\"] = \"ERR_INVALID_MULTIADDR\";\n codes[\"ERR_SIGNATURE_NOT_VALID\"] = \"ERR_SIGNATURE_NOT_VALID\";\n codes[\"ERR_FIND_SELF\"] = \"ERR_FIND_SELF\";\n codes[\"ERR_NO_ROUTERS_AVAILABLE\"] = \"ERR_NO_ROUTERS_AVAILABLE\";\n codes[\"ERR_CONNECTION_NOT_MULTIPLEXED\"] = \"ERR_CONNECTION_NOT_MULTIPLEXED\";\n codes[\"ERR_NO_DIAL_TOKENS\"] = \"ERR_NO_DIAL_TOKENS\";\n codes[\"ERR_INVALID_CMS\"] = \"ERR_INVALID_CMS\";\n codes[\"ERR_MISSING_KEYS\"] = \"ERR_MISSING_KEYS\";\n codes[\"ERR_NO_KEY\"] = \"ERR_NO_KEY\";\n codes[\"ERR_INVALID_KEY_NAME\"] = \"ERR_INVALID_KEY_NAME\";\n codes[\"ERR_INVALID_KEY_TYPE\"] = \"ERR_INVALID_KEY_TYPE\";\n codes[\"ERR_KEY_ALREADY_EXISTS\"] = \"ERR_KEY_ALREADY_EXISTS\";\n codes[\"ERR_INVALID_KEY_SIZE\"] = \"ERR_INVALID_KEY_SIZE\";\n codes[\"ERR_KEY_NOT_FOUND\"] = \"ERR_KEY_NOT_FOUND\";\n codes[\"ERR_OLD_KEY_NAME_INVALID\"] = \"ERR_OLD_KEY_NAME_INVALID\";\n codes[\"ERR_NEW_KEY_NAME_INVALID\"] = \"ERR_NEW_KEY_NAME_INVALID\";\n codes[\"ERR_PASSWORD_REQUIRED\"] = \"ERR_PASSWORD_REQUIRED\";\n codes[\"ERR_PEM_REQUIRED\"] = \"ERR_PEM_REQUIRED\";\n codes[\"ERR_CANNOT_READ_KEY\"] = \"ERR_CANNOT_READ_KEY\";\n codes[\"ERR_MISSING_PRIVATE_KEY\"] = \"ERR_MISSING_PRIVATE_KEY\";\n codes[\"ERR_MISSING_PUBLIC_KEY\"] = \"ERR_MISSING_PUBLIC_KEY\";\n codes[\"ERR_INVALID_OLD_PASS_TYPE\"] = \"ERR_INVALID_OLD_PASS_TYPE\";\n codes[\"ERR_INVALID_NEW_PASS_TYPE\"] = \"ERR_INVALID_NEW_PASS_TYPE\";\n codes[\"ERR_INVALID_PASS_LENGTH\"] = \"ERR_INVALID_PASS_LENGTH\";\n codes[\"ERR_NOT_IMPLEMENTED\"] = \"ERR_NOT_IMPLEMENTED\";\n codes[\"ERR_WRONG_PING_ACK\"] = \"ERR_WRONG_PING_ACK\";\n codes[\"ERR_INVALID_RECORD\"] = \"ERR_INVALID_RECORD\";\n codes[\"ERR_ALREADY_SUCCEEDED\"] = \"ERR_ALREADY_SUCCEEDED\";\n codes[\"ERR_NO_HANDLER_FOR_PROTOCOL\"] = \"ERR_NO_HANDLER_FOR_PROTOCOL\";\n codes[\"ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS\"] = \"ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS\";\n codes[\"ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS\"] = \"ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS\";\n codes[\"ERR_CONNECTION_DENIED\"] = \"ERR_CONNECTION_DENIED\";\n codes[\"ERR_TRANSFER_LIMIT_EXCEEDED\"] = \"ERR_TRANSFER_LIMIT_EXCEEDED\";\n})(codes || (codes = {}));\n//# sourceMappingURL=errors.js.map","import { CodeError, FaultTolerance } from '@libp2p/interface';\nimport { peerIdFromKeys } from '@libp2p/peer-id';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport mergeOptions from 'merge-options';\nimport { codes, messages } from './errors.js';\nconst DefaultConfig = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: dnsaddrResolver\n },\n addressSorter: defaultAddressSort\n },\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n }\n};\nexport async function validateConfig(opts) {\n const resultingOptions = mergeOptions(DefaultConfig, opts);\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED);\n }\n if (resultingOptions.privateKey != null && !(await peerIdFromKeys(resultingOptions.privateKey.public.bytes, resultingOptions.privateKey.bytes)).equals(resultingOptions.peerId)) {\n throw new CodeError('Private key doesn\\'t match peer id', codes.ERR_INVALID_KEY);\n }\n return resultingOptions;\n}\n//# sourceMappingURL=config.js.map","import { CodeError, isPeerId } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { isMultiaddr } from '@multiformats/multiaddr';\nimport { codes } from './errors.js';\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nexport function getPeerAddress(peer) {\n if (isPeerId(peer)) {\n return { peerId: peer, multiaddrs: [] };\n }\n if (!Array.isArray(peer)) {\n peer = [peer];\n }\n let peerId;\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId();\n peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr);\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!isMultiaddr(ma)) {\n throw new CodeError('Invalid Multiaddr', codes.ERR_INVALID_MULTIADDR);\n }\n const maPeerIdStr = ma.getPeerId();\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS);\n }\n }\n else {\n const maPeerId = peerIdFromString(maPeerIdStr);\n if (peerId?.equals(maPeerId) !== true) {\n throw new CodeError('Multiaddrs must all have the same peer id or have no peer id', codes.ERR_INVALID_PARAMETERS);\n }\n }\n });\n }\n return {\n peerId,\n multiaddrs: peer\n };\n}\n//# sourceMappingURL=get-peer.js.map","/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent(emitter, eventName, signal, opts) {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n if (signal?.aborted === true) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n function removeListeners() {\n signal?.removeEventListener('abort', abortListener);\n emitter.removeEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.removeEventListener(opts.errorEvent, errorEventListener);\n }\n }\n const eventListener = (evt) => {\n try {\n if (opts?.filter?.(evt) === false) {\n return;\n }\n }\n catch (err) {\n removeListeners();\n reject(err);\n return;\n }\n removeListeners();\n resolve(evt);\n };\n const errorEventListener = (evt) => {\n removeListeners();\n reject(evt.detail);\n };\n const abortListener = () => {\n removeListeners();\n reject(error);\n };\n signal?.addEventListener('abort', abortListener);\n emitter.addEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.addEventListener(opts.errorEvent, errorEventListener);\n }\n });\n}\n//# sourceMappingURL=index.js.map","import { AbortError } from '@libp2p/interface';\nimport pDefer from 'p-defer';\nexport class JobRecipient {\n deferred;\n signal;\n constructor(signal) {\n this.signal = signal;\n this.deferred = pDefer();\n this.onAbort = this.onAbort.bind(this);\n this.signal?.addEventListener('abort', this.onAbort);\n }\n onAbort() {\n this.deferred.reject(this.signal?.reason ?? new AbortError());\n }\n cleanup() {\n this.signal?.removeEventListener('abort', this.onAbort);\n }\n}\n//# sourceMappingURL=recipient.js.map","import { AbortError, setMaxListeners } from '@libp2p/interface';\nimport { raceSignal } from 'race-signal';\nimport { JobRecipient } from './recipient.js';\n/**\n * Returns a random string\n */\nfunction randomId() {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`;\n}\nexport class Job {\n id;\n fn;\n options;\n recipients;\n status;\n timeline;\n controller;\n constructor(fn, options) {\n this.id = randomId();\n this.status = 'queued';\n this.fn = fn;\n this.options = options;\n this.recipients = [];\n this.timeline = {\n created: Date.now()\n };\n this.controller = new AbortController();\n setMaxListeners(Infinity, this.controller.signal);\n this.onAbort = this.onAbort.bind(this);\n }\n abort(err) {\n this.controller.abort(err);\n }\n onAbort() {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true);\n }, true);\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError());\n this.cleanup();\n }\n }\n async join(options = {}) {\n const recipient = new JobRecipient(options.signal);\n this.recipients.push(recipient);\n options.signal?.addEventListener('abort', this.onAbort);\n return recipient.deferred.promise;\n }\n async run() {\n this.status = 'running';\n this.timeline.started = Date.now();\n try {\n this.controller.signal.throwIfAborted();\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal);\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result);\n });\n this.status = 'complete';\n }\n catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err);\n });\n this.status = 'errored';\n }\n finally {\n this.timeline.finished = Date.now();\n this.cleanup();\n }\n }\n cleanup() {\n this.recipients.forEach(recipient => {\n recipient.cleanup();\n recipient.signal?.removeEventListener('abort', this.onAbort);\n });\n }\n}\n//# sourceMappingURL=job.js.map","import { AbortError, CodeError, TypedEventEmitter } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport { raceEvent } from 'race-event';\nimport { Job } from './job.js';\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue extends TypedEventEmitter {\n concurrency;\n queue;\n pending;\n sort;\n constructor(init = {}) {\n super();\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY;\n this.pending = 0;\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n };\n }\n });\n }\n this.sort = init.sort;\n this.queue = [];\n }\n tryToStartAnother() {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty');\n });\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle');\n });\n }\n return false;\n }\n if (this.pending < this.concurrency) {\n let job;\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j;\n break;\n }\n }\n if (job == null) {\n return false;\n }\n this.safeDispatchEvent('active');\n this.pending++;\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n this.pending--;\n this.tryToStartAnother();\n this.safeDispatchEvent('next');\n });\n return true;\n }\n return false;\n }\n enqueue(job) {\n this.queue.push(job);\n if (this.sort != null) {\n this.queue.sort(this.sort);\n }\n }\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options) {\n options?.signal?.throwIfAborted();\n const job = new Job(fn, options);\n this.enqueue(job);\n this.safeDispatchEvent('add');\n this.tryToStartAnother();\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result });\n this.safeDispatchEvent('success', { detail: { job, result } });\n return result;\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n }\n this.safeDispatchEvent('error', { detail: err });\n this.safeDispatchEvent('failure', { detail: { job, error: err } });\n throw err;\n });\n }\n /**\n * Clear the queue\n */\n clear() {\n this.queue.splice(0, this.queue.length);\n }\n /**\n * Abort all jobs in the queue and clear it\n */\n abort() {\n this.queue.forEach(job => {\n job.abort(new AbortError());\n });\n this.clear();\n }\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty(options) {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return;\n }\n await raceEvent(this, 'empty', options?.signal);\n }\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan(limit, options) {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return;\n }\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n });\n }\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle(options) {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return;\n }\n await raceEvent(this, 'idle', options?.signal);\n }\n /**\n * Size of the queue including running items\n */\n get size() {\n return this.queue.length;\n }\n /**\n * The number of queued items waiting to run.\n */\n get queued() {\n return this.queue.length - this.pending;\n }\n /**\n * The number of items currently running.\n */\n get running() {\n return this.pending;\n }\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async *toGenerator(options) {\n options?.signal?.throwIfAborted();\n const stream = pushable({\n objectMode: true\n });\n const cleanup = (err) => {\n if (err != null) {\n this.abort();\n }\n else {\n this.clear();\n }\n stream.end(err);\n };\n const onQueueJobComplete = (evt) => {\n if (evt.detail != null) {\n stream.push(evt.detail);\n }\n };\n const onQueueError = (evt) => {\n cleanup(evt.detail);\n };\n const onQueueIdle = () => {\n cleanup();\n };\n // clear the queue and throw if the query is aborted\n const onSignalAbort = () => {\n cleanup(new CodeError('Queue aborted', 'ERR_QUEUE_ABORTED'));\n };\n // add listeners\n this.addEventListener('completed', onQueueJobComplete);\n this.addEventListener('error', onQueueError);\n this.addEventListener('idle', onQueueIdle);\n options?.signal?.addEventListener('abort', onSignalAbort);\n try {\n yield* stream;\n }\n finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete);\n this.removeEventListener('error', onQueueError);\n this.removeEventListener('idle', onQueueIdle);\n options?.signal?.removeEventListener('abort', onSignalAbort);\n // empty the queue for when the user has broken out of a loop early\n cleanup();\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { Queue } from './queue/index.js';\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue extends Queue {\n has(peerId) {\n return this.find(peerId) != null;\n }\n find(peerId) {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId);\n });\n }\n}\n//# sourceMappingURL=peer-queue.js.map","export * from './constants.defaults.js';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#minConnections\n */\nexport const MIN_CONNECTIONS = 5;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections\n */\nexport const MAX_CONNECTIONS = 100;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials\n */\nexport const MAX_PARALLEL_DIALS = 50;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialPeerRetryThreshold\n */\nexport const AUTO_DIAL_PEER_RETRY_THRESHOLD = 1000 * 60 * 7;\n//# sourceMappingURL=constants.browser.js.map","/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#dialTimeout\n */\nexport const DIAL_TIMEOUT = 5e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundUpgradeTimeout\n */\nexport const INBOUND_UPGRADE_TIMEOUT = 2e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxPeerAddrsToDial\n */\nexport const MAX_PEER_ADDRS_TO_DIAL = 25;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialInterval\n */\nexport const AUTO_DIAL_INTERVAL = 5000;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialConcurrency\n */\nexport const AUTO_DIAL_CONCURRENCY = 25;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialPriority\n */\nexport const AUTO_DIAL_PRIORITY = 0;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#autoDialMaxQueueLength\n */\nexport const AUTO_DIAL_MAX_QUEUE_LENGTH = 100;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/libp2p.index.unknown.ConnectionManagerInit.html#autoDialDiscoveredPeersDebounce\n */\nexport const AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE = 10;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold\n */\nexport const INBOUND_CONNECTION_THRESHOLD = 5;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxIncomingPendingConnections\n */\nexport const MAX_INCOMING_PENDING_CONNECTIONS = 10;\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempted failed with the relevant\n * peer stored as a string.\n *\n * Used to insure we do not endlessly try to auto dial peers we have recently\n * failed to dial.\n */\nexport const LAST_DIAL_FAILURE_KEY = 'last-dial-failure';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength\n */\nexport const MAX_DIAL_QUEUE_LENGTH = 500;\n//# sourceMappingURL=constants.defaults.js.map","import { PeerMap, PeerSet } from '@libp2p/peer-collections';\nimport { PeerQueue } from '@libp2p/utils/peer-queue';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_INTERVAL, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, LAST_DIAL_FAILURE_KEY, MIN_CONNECTIONS } from './constants.js';\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialInterval: AUTO_DIAL_INTERVAL,\n autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\nexport class AutoDial {\n connectionManager;\n peerStore;\n queue;\n minConnections;\n autoDialPriority;\n autoDialIntervalMs;\n autoDialMaxQueueLength;\n autoDialPeerRetryThresholdMs;\n autoDialDiscoveredPeersDebounce;\n autoDialInterval;\n started;\n running;\n log;\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on whether we know their keys and protocols.\n */\n constructor(components, init) {\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.minConnections = init.minConnections ?? defaultOptions.minConnections;\n this.autoDialPriority = init.autoDialPriority ?? defaultOptions.autoDialPriority;\n this.autoDialIntervalMs = init.autoDialInterval ?? defaultOptions.autoDialInterval;\n this.autoDialMaxQueueLength = init.maxQueueLength ?? defaultOptions.maxQueueLength;\n this.autoDialPeerRetryThresholdMs = init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold;\n this.autoDialDiscoveredPeersDebounce = init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce;\n this.log = components.logger.forComponent('libp2p:connection-manager:auto-dial');\n this.started = false;\n this.running = false;\n this.queue = new PeerQueue({\n concurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n metricName: 'libp2p_autodial_queue',\n metrics: components.metrics\n });\n this.queue.addEventListener('error', (evt) => {\n this.log.error('error during auto-dial', evt.detail);\n });\n // check the min connection limit whenever a peer disconnects\n components.events.addEventListener('connection:close', () => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n });\n // sometimes peers are discovered in quick succession so add a small\n // debounce to ensure all eligible peers are autodialed\n let debounce;\n // when new peers are discovered, dial them if we don't have\n // enough connections\n components.events.addEventListener('peer:discovery', () => {\n clearTimeout(debounce);\n debounce = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n }, this.autoDialDiscoveredPeersDebounce);\n });\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n afterStart() {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }\n stop() {\n // clear the queue\n this.queue.clear();\n clearTimeout(this.autoDialInterval);\n this.started = false;\n this.running = false;\n }\n async autoDial() {\n if (!this.started || this.running) {\n return;\n }\n const connections = this.connectionManager.getConnectionsMap();\n const numConnections = connections.size;\n // already have enough connections\n if (numConnections >= this.minConnections) {\n if (this.minConnections > 0) {\n this.log.trace('have enough connections %d/%d', numConnections, this.minConnections);\n }\n // no need to schedule next autodial as it will be run when on\n // connection:close event\n return;\n }\n if (this.queue.size > this.autoDialMaxQueueLength) {\n this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections);\n this.sheduleNextAutodial();\n return;\n }\n this.running = true;\n this.log('not enough connections %d/%d - will dial peers to increase the number of connections', numConnections, this.minConnections);\n const dialQueue = new PeerSet(\n // @ts-expect-error boolean filter removes falsy peer IDs\n this.connectionManager.getDialQueue()\n .map(queue => queue.peerId)\n .filter(Boolean));\n // sort peers on whether we know protocols or public keys for them\n const peers = await this.peerStore.all({\n filters: [\n // remove some peers\n (peer) => {\n // remove peers without addresses\n if (peer.addresses.length === 0) {\n this.log.trace('not autodialing %p because they have no addresses', peer.id);\n return false;\n }\n // remove peers we are already connected to\n if (connections.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already connected', peer.id);\n return false;\n }\n // remove peers we are already dialling\n if (dialQueue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being dialed', peer.id);\n return false;\n }\n // remove peers already in the autodial queue\n if (this.queue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being autodialed', peer.id);\n return false;\n }\n return true;\n }\n ]\n });\n // shuffle the peers - this is so peers with the same tag values will be\n // dialled in a different order each time\n const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1);\n // sort shuffled peers by tag value\n const peerValues = new PeerMap();\n for (const peer of shuffledPeers) {\n if (peerValues.has(peer.id)) {\n continue;\n }\n // sum all tag values\n peerValues.set(peer.id, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n // sort by value, highest to lowest\n const sortedPeers = shuffledPeers.sort((a, b) => {\n const peerAValue = peerValues.get(a.id) ?? 0;\n const peerBValue = peerValues.get(b.id) ?? 0;\n if (peerAValue > peerBValue) {\n return -1;\n }\n if (peerAValue < peerBValue) {\n return 1;\n }\n return 0;\n });\n const peersThatHaveNotFailed = sortedPeers.filter(peer => {\n const lastDialFailure = peer.metadata.get(LAST_DIAL_FAILURE_KEY);\n if (lastDialFailure == null) {\n return true;\n }\n const lastDialFailureTimestamp = parseInt(uint8ArrayToString(lastDialFailure));\n if (isNaN(lastDialFailureTimestamp)) {\n return true;\n }\n // only dial if the time since the last failure is above the retry threshold\n return Date.now() - lastDialFailureTimestamp > this.autoDialPeerRetryThresholdMs;\n });\n this.log('selected %d/%d peers to dial', peersThatHaveNotFailed.length, peers.length);\n for (const peer of peersThatHaveNotFailed) {\n this.queue.add(async () => {\n const numConnections = this.connectionManager.getConnectionsMap().size;\n // Check to see if we still need to auto dial\n if (numConnections >= this.minConnections) {\n this.log('got enough connections now %d/%d', numConnections, this.minConnections);\n this.queue.clear();\n return;\n }\n this.log('connecting to a peerStore stored peer %p', peer.id);\n await this.connectionManager.openConnection(peer.id, {\n priority: this.autoDialPriority\n });\n }, {\n peerId: peer.id\n }).catch(err => {\n this.log.error('could not connect to peerStore stored peer', err);\n });\n }\n this.running = false;\n this.sheduleNextAutodial();\n }\n sheduleNextAutodial() {\n if (!this.started) {\n return;\n }\n this.autoDialInterval = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }, this.autoDialIntervalMs);\n }\n}\n//# sourceMappingURL=auto-dial.js.map","/**\n * Close the passed stream, falling back to aborting the stream if closing\n * cleanly fails.\n */\nexport async function safelyCloseStream(stream, options) {\n try {\n await stream?.close(options);\n }\n catch (err) {\n stream?.abort(err);\n }\n}\n/**\n * These are speculative protocols that are run automatically on connection open\n * so are usually not the reason the connection was opened.\n *\n * Consequently when requested it should be safe to close connections that only\n * have these protocol streams open.\n */\nconst DEFAULT_CLOSABLE_PROTOCOLS = [\n // identify\n '/ipfs/id/1.0.0',\n // identify-push\n '/ipfs/id/push/1.0.0',\n // autonat\n '/libp2p/autonat/1.0.0',\n // dcutr\n '/libp2p/dcutr'\n];\n/**\n * Close the passed connection if it has no streams, or only closable protocol\n * streams, falling back to aborting the connection if closing it cleanly fails.\n */\nexport async function safelyCloseConnectionIfUnused(connection, options) {\n const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? [];\n const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS;\n // if the connection has protocols not in the closable protocols list, do not\n // close the connection\n if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {\n return;\n }\n try {\n await connection?.close(options);\n }\n catch (err) {\n connection?.abort(err);\n }\n}\n//# sourceMappingURL=close.js.map","import { PeerMap } from '@libp2p/peer-collections';\nimport { safelyCloseConnectionIfUnused } from '@libp2p/utils/close';\nimport { MAX_CONNECTIONS } from './constants.js';\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n allow: []\n};\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nexport class ConnectionPruner {\n maxConnections;\n connectionManager;\n peerStore;\n allow;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n this.allow = init.allow ?? defaultOptions.allow;\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner');\n // check the max connection limit whenever a peer connects\n components.events.addEventListener('connection:open', () => {\n this.maybePruneConnections()\n .catch(err => {\n this.log.error(err);\n });\n });\n }\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async maybePruneConnections() {\n const connections = this.connectionManager.getConnections();\n const numConnections = connections.length;\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections);\n if (numConnections <= this.maxConnections) {\n return;\n }\n const peerValues = new PeerMap();\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer;\n if (peerValues.has(remotePeer)) {\n continue;\n }\n peerValues.set(remotePeer, 0);\n try {\n const peer = await this.peerStore.get(remotePeer);\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n this.log.error('error loading peer tags', err);\n }\n }\n }\n const sortedConnections = this.sortConnections(connections, peerValues);\n // close some connections\n const toPrune = Math.max(numConnections - this.maxConnections, 0);\n const toClose = [];\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer);\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString());\n });\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection);\n }\n if (toClose.length === toPrune) {\n break;\n }\n }\n // close connections\n await Promise.all(toClose.map(async (connection) => {\n await safelyCloseConnectionIfUnused(connection, {\n signal: AbortSignal.timeout(1000)\n });\n }));\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose });\n }\n sortConnections(connections, peerValues) {\n return connections\n // sort by connection age, newest to oldest\n .sort((a, b) => {\n const connectionALifespan = a.timeline.open;\n const connectionBLifespan = b.timeline.open;\n if (connectionALifespan < connectionBLifespan) {\n return 1;\n }\n if (connectionALifespan > connectionBLifespan) {\n return -1;\n }\n return 0;\n })\n // sort by direction, incoming first then outgoing\n .sort((a, b) => {\n if (a.direction === 'outbound' && b.direction === 'inbound') {\n return 1;\n }\n if (a.direction === 'inbound' && b.direction === 'outbound') {\n return -1;\n }\n return 0;\n })\n // sort by number of streams, lowest to highest\n .sort((a, b) => {\n if (a.streams.length > b.streams.length) {\n return 1;\n }\n if (a.streams.length < b.streams.length) {\n return -1;\n }\n return 0;\n })\n // sort by tag value, lowest to highest\n .sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0;\n const peerBValue = peerValues.get(b.remotePeer) ?? 0;\n if (peerAValue > peerBValue) {\n return 1;\n }\n if (peerAValue < peerBValue) {\n return -1;\n }\n return 0;\n });\n }\n}\n//# sourceMappingURL=connection-pruner.js.map","import { Queue } from './queue/index.js';\nexport class PriorityQueue extends Queue {\n constructor(init = {}) {\n super({\n ...init,\n sort: (a, b) => {\n if (a.options.priority > b.options.priority) {\n return -1;\n }\n if (a.options.priority < b.options.priority) {\n return 1;\n }\n return 0;\n }\n });\n }\n}\n//# sourceMappingURL=priority-queue.js.map","/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal(signals) {\n const controller = new globalThis.AbortController();\n function onAbort() {\n controller.abort();\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort();\n break;\n }\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort);\n }\n }\n function clear() {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n const signal = controller.signal;\n signal.clear = clear;\n return signal;\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable max-depth */\nimport { CodeError, AggregateCodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { PriorityQueue } from '@libp2p/utils/priority-queue';\nimport { resolvers, multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { Circuit } from '@multiformats/multiaddr-matcher';\nimport { anySignal } from 'any-signal';\nimport { CustomProgressEvent } from 'progress-events';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { codes } from '../errors.js';\nimport { getPeerAddress } from '../get-peer.js';\nimport { DIAL_TIMEOUT, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, LAST_DIAL_FAILURE_KEY, MAX_DIAL_QUEUE_LENGTH } from './constants.js';\nimport { resolveMultiaddrs } from './utils.js';\nimport { DEFAULT_DIAL_PRIORITY } from './index.js';\nconst defaultOptions = {\n addressSorter: defaultAddressSort,\n maxParallelDials: MAX_PARALLEL_DIALS,\n maxDialQueueLength: MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n};\nexport class DialQueue {\n queue;\n components;\n addressSorter;\n maxPeerAddrsToDial;\n maxDialQueueLength;\n dialTimeout;\n shutDownController;\n connections;\n log;\n constructor(components, init = {}) {\n this.addressSorter = init.addressSorter ?? defaultOptions.addressSorter;\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial;\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength;\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout;\n this.connections = init.connections ?? new PeerMap();\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue');\n this.components = components;\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value);\n }\n // controls dial concurrency\n this.queue = new PriorityQueue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n });\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n this.log.error('error in dial queue', event.detail);\n });\n }\n start() {\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n }\n /**\n * Clears any pending dials\n */\n stop() {\n this.shutDownController.abort();\n this.queue.abort();\n }\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial(peerIdOrMultiaddr, options = {}) {\n const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr);\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false;\n }\n if (conn.remotePeer.equals(peerId)) {\n return true;\n }\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr);\n });\n });\n if (existingConnection != null) {\n this.log('already connected to %a', existingConnection.remoteAddr);\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true;\n }\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs;\n if (addresses == null) {\n return false;\n }\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true;\n }\n }\n return false;\n });\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId);\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString());\n }\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-in-dial-queue'));\n return existingDial.join(options);\n }\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL');\n }\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()));\n options.onProgress?.(new CustomProgressEvent('dial-queue:add-to-dial-queue'));\n return this.queue.add(async (options) => {\n options?.onProgress?.(new CustomProgressEvent('dial-queue:start-dial'));\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal);\n let addrsToDial;\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n });\n options?.onProgress?.(new CustomProgressEvent('dial-queue:calculated-addresses', addrsToDial));\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr);\n });\n }\n catch (err) {\n signal.clear();\n throw err;\n }\n try {\n let dialed = 0;\n const errors = [];\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId);\n throw new CodeError('Peer had more than maxPeerAddrsToDial', codes.ERR_TOO_MANY_ADDRESSES);\n }\n dialed++;\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n });\n this.log('dial to %a succeeded', address.multiaddr);\n return conn;\n }\n catch (err) {\n this.log.error('dial failed to %a', address.multiaddr, err);\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.patch(peerId, {\n metadata: {\n [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n }\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new CodeError(err.message, ERR_TIMEOUT);\n }\n errors.push(err);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateCodeError(errors, 'All multiaddr dials failed', codes.ERR_TRANSPORT_DIAL_FAILED);\n }\n finally {\n // clean up abort signals/controllers\n signal.clear();\n }\n }, {\n peerId,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal,\n onProgress: options.onProgress\n });\n }\n createDialAbortController(userSignal) {\n // let any signal abort the dial\n const signal = anySignal([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ]);\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, signal);\n return signal;\n }\n // eslint-disable-next-line complexity\n async calculateMultiaddrs(peerId, multiaddrs = new Set(), options = {}) {\n const addrs = [...multiaddrs].map(ma => ({\n multiaddr: multiaddr(ma),\n isCertified: false\n }));\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF);\n }\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED);\n }\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId);\n try {\n const peer = await this.components.peerStore.get(peerId);\n addrs.push(...peer.addresses);\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n }\n catch (err) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId);\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId);\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })));\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_ROUTERS_AVAILABLE) {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err);\n }\n }\n }\n }\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(addrs.map(async (addr) => {\n const result = await resolveMultiaddrs(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n });\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr;\n }\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }));\n })))\n .flat();\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`;\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop();\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr;\n }\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n };\n }\n return addr;\n });\n }\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.dialTransportForMultiaddr(addr.multiaddr) == null) {\n return false;\n }\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId();\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId);\n }\n return true;\n });\n // deduplicate addresses\n const dedupedAddrs = new Map();\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString();\n const existing = dedupedAddrs.get(maStr);\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false;\n continue;\n }\n dedupedAddrs.set(maStr, addr);\n }\n const dedupedMultiaddrs = [...dedupedAddrs.values()];\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES);\n }\n const gatedAdrs = [];\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue;\n }\n gatedAdrs.push(addr);\n }\n const sortedGatedAddrs = gatedAdrs.sort(this.addressSorter);\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new CodeError('The connection gater denied all addresses in the dial request', codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()));\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()));\n return sortedGatedAddrs;\n }\n async isDialable(multiaddr, options = {}) {\n if (!Array.isArray(multiaddr)) {\n multiaddr = [multiaddr];\n }\n try {\n const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options);\n if (options.runOnTransientConnection === false) {\n // return true if any resolved multiaddrs are not relay addresses\n return addresses.find(addr => {\n return !Circuit.matches(addr.multiaddr);\n }) != null;\n }\n return true;\n }\n catch (err) {\n this.log.trace('error calculating if multiaddr(s) were dialable', err);\n }\n return false;\n }\n}\n//# sourceMappingURL=dial-queue.js.map","import { resolvers } from '@multiformats/multiaddr';\n/**\n * Recursively resolve DNSADDR multiaddrs\n */\nexport async function resolveMultiaddrs(ma, options) {\n // check multiaddr resolvers\n let resolvable = false;\n for (const key of resolvers.keys()) {\n resolvable = ma.protoNames().includes(key);\n if (resolvable) {\n break;\n }\n }\n // return multiaddr if it is not resolvable\n if (!resolvable) {\n return [ma];\n }\n const output = await ma.resolve(options);\n options.log('resolved %s to', ma, output.map(ma => ma.toString()));\n return output;\n}\n//# sourceMappingURL=utils.js.map","import { CodeError, KEEP_ALIVE } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { defaultAddressSort } from '@libp2p/utils/address-sort';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { CustomProgressEvent } from 'progress-events';\nimport { codes } from '../errors.js';\nimport { getPeerAddress } from '../get-peer.js';\nimport { AutoDial } from './auto-dial.js';\nimport { ConnectionPruner } from './connection-pruner.js';\nimport { AUTO_DIAL_CONCURRENCY, AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE, AUTO_DIAL_MAX_QUEUE_LENGTH, AUTO_DIAL_PEER_RETRY_THRESHOLD, AUTO_DIAL_PRIORITY, DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, MIN_CONNECTIONS } from './constants.js';\nimport { DialQueue } from './dial-queue.js';\nexport const DEFAULT_DIAL_PRIORITY = 50;\nconst defaultOptions = {\n minConnections: MIN_CONNECTIONS,\n maxConnections: MAX_CONNECTIONS,\n inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS,\n autoDialConcurrency: AUTO_DIAL_CONCURRENCY,\n autoDialPriority: AUTO_DIAL_PRIORITY,\n autoDialMaxQueueLength: AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialPeerRetryThreshold: AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager {\n started;\n connections;\n allow;\n deny;\n maxIncomingPendingConnections;\n incomingPendingConnections;\n maxConnections;\n dialQueue;\n autoDial;\n connectionPruner;\n inboundConnectionRateLimiter;\n peerStore;\n metrics;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n const minConnections = init.minConnections ?? defaultOptions.minConnections;\n if (this.maxConnections < minConnections) {\n throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS);\n }\n /**\n * Map of connections per peer\n */\n this.connections = new PeerMap();\n this.started = false;\n this.peerStore = components.peerStore;\n this.metrics = components.metrics;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager');\n this.onConnect = this.onConnect.bind(this);\n this.onDisconnect = this.onDisconnect.bind(this);\n this.events.addEventListener('connection:open', this.onConnect);\n this.events.addEventListener('connection:close', this.onDisconnect);\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma));\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma));\n this.incomingPendingConnections = 0;\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections;\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n });\n // controls what happens when we don't have enough connections\n this.autoDial = new AutoDial({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n minConnections,\n autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,\n autoDialPeerRetryThreshold: init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold,\n autoDialDiscoveredPeersDebounce: init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce,\n maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength\n });\n // controls what happens when we have too many connections\n this.connectionPruner = new ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n });\n this.dialQueue = new DialQueue(components, {\n addressSorter: init.addressSorter ?? defaultAddressSort,\n maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: dnsaddrResolver\n },\n connections: this.connections\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-manager';\n isStarted() {\n return this.started;\n }\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start() {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n };\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.direction === 'inbound') {\n metric.inbound++;\n }\n else {\n metric.outbound++;\n }\n }\n }\n return metric;\n }\n });\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n metric[key] = (metric[key] ?? 0) + 1;\n }\n }\n }\n return metric;\n }\n });\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams = {};\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n streams[key] = (streams[key] ?? 0) + 1;\n }\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? [];\n allStreams[protocol].push(count);\n }\n }\n }\n const metric = {};\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b);\n const index = Math.floor(counts.length * 0.9);\n metric[protocol] = counts[index];\n }\n return metric;\n }\n });\n this.dialQueue.start();\n this.autoDial.start();\n this.started = true;\n this.log('started');\n }\n async afterStart() {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(KEEP_ALIVE);\n }]\n });\n await Promise.all(keepAlivePeers.map(async (peer) => {\n await this.openConnection(peer.id)\n .catch(err => {\n this.log.error(err);\n });\n }));\n })\n .catch(err => {\n this.log.error(err);\n });\n this.autoDial.afterStart();\n }\n /**\n * Stops the Connection Manager\n */\n async stop() {\n this.dialQueue.stop();\n this.autoDial.stop();\n // Close all connections we're tracking\n const tasks = [];\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n })());\n }\n }\n this.log('closing %d connections', tasks.length);\n await Promise.all(tasks);\n this.connections.clear();\n this.log('stopped');\n }\n onConnect(evt) {\n void this._onConnect(evt).catch(err => {\n this.log.error(err);\n });\n }\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close();\n return;\n }\n const peerId = connection.remotePeer;\n const storedConns = this.connections.get(peerId);\n let isNewPeer = false;\n if (storedConns != null) {\n storedConns.push(connection);\n }\n else {\n isNewPeer = true;\n this.connections.set(peerId, [connection]);\n }\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n });\n }\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer });\n }\n }\n /**\n * Removes the connection from tracking\n */\n onDisconnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return;\n }\n const peerId = connection.remotePeer;\n let storedConn = this.connections.get(peerId);\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id);\n this.connections.set(peerId, storedConn);\n }\n else if (storedConn != null) {\n this.connections.delete(peerId);\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer });\n }\n }\n getConnections(peerId) {\n if (peerId != null) {\n return this.connections.get(peerId) ?? [];\n }\n let conns = [];\n for (const c of this.connections.values()) {\n conns = conns.concat(c);\n }\n return conns;\n }\n getConnectionsMap() {\n return this.connections;\n }\n async openConnection(peerIdOrMultiaddr, options = {}) {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED);\n }\n options.signal?.throwIfAborted();\n const { peerId } = getPeerAddress(peerIdOrMultiaddr);\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId);\n const existingConnection = this.getConnections(peerId)\n .find(conn => !conn.transient);\n if (existingConnection != null) {\n this.log('had an existing non-transient connection to %p', peerId);\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n }\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n });\n let peerConnections = this.connections.get(connection.remotePeer);\n if (peerConnections == null) {\n peerConnections = [];\n this.connections.set(connection.remotePeer, peerConnections);\n }\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false;\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true;\n }\n }\n if (!trackedConnection) {\n peerConnections.push(connection);\n }\n return connection;\n }\n async closeConnections(peerId, options = {}) {\n const connections = this.connections.get(peerId) ?? [];\n await Promise.all(connections.map(async (connection) => {\n try {\n await connection.close(options);\n }\n catch (err) {\n connection.abort(err);\n }\n }));\n }\n async acceptIncomingConnection(maConn) {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr);\n return false;\n }\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (allowConnection) {\n this.incomingPendingConnections++;\n return true;\n }\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr);\n return false;\n }\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address;\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1);\n }\n catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host);\n return false;\n }\n }\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++;\n return true;\n }\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr);\n return false;\n }\n afterUpgradeInbound() {\n this.incomingPendingConnections--;\n }\n getDialQueue() {\n const statusMap = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n };\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => multiaddr(ma))\n };\n });\n }\n async isDialable(multiaddr, options = {}) {\n return this.dialQueue.isDialable(multiaddr, options);\n }\n}\n//# sourceMappingURL=index.js.map","export const KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map","/**\n * Implements exponential moving average. Ported from `moving-average`.\n *\n * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * @see https://www.npmjs.com/package/moving-average\n */\nexport class MovingAverage {\n movingAverage;\n variance;\n deviation;\n forecast;\n timespan;\n previousTime;\n constructor(timespan) {\n this.timespan = timespan;\n this.movingAverage = 0;\n this.variance = 0;\n this.deviation = 0;\n this.forecast = 0;\n }\n alpha(t, pt) {\n return 1 - (Math.exp(-(t - pt) / this.timespan));\n }\n push(value, time = Date.now()) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime);\n const diff = value - this.movingAverage;\n const incr = a * diff;\n this.movingAverage = a * value + (1 - a) * this.movingAverage;\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr);\n this.deviation = Math.sqrt(this.variance);\n // calculate forecast\n this.forecast = this.movingAverage + a * diff;\n }\n else {\n this.movingAverage = value;\n }\n this.previousTime = time;\n }\n}\n//# sourceMappingURL=moving-average.js.map","import { setMaxListeners } from '@libp2p/interface';\nimport { anySignal } from 'any-signal';\nimport { MovingAverage } from './moving-average.js';\nexport const DEFAULT_TIMEOUT_MULTIPLIER = 1.2;\nexport const DEFAULT_FAILURE_MULTIPLIER = 2;\nexport const DEFAULT_MIN_TIMEOUT = 2000;\nexport class AdaptiveTimeout {\n success;\n failure;\n next;\n metric;\n timeoutMultiplier;\n failureMultiplier;\n minTimeout;\n constructor(init = {}) {\n this.success = new MovingAverage(init.interval ?? 5000);\n this.failure = new MovingAverage(init.interval ?? 5000);\n this.next = new MovingAverage(init.interval ?? 5000);\n this.failureMultiplier = init.failureMultiplier ?? DEFAULT_FAILURE_MULTIPLIER;\n this.timeoutMultiplier = init.timeoutMultiplier ?? DEFAULT_TIMEOUT_MULTIPLIER;\n this.minTimeout = init.minTimeout ?? DEFAULT_MIN_TIMEOUT;\n if (init.metricName != null) {\n this.metric = init.metrics?.registerMetricGroup(init.metricName);\n }\n }\n getTimeoutSignal(options = {}) {\n // calculate timeout for individual peers based on moving average of\n // previous successful requests\n const timeout = Math.max(Math.round(this.next.movingAverage * (options.timeoutFactor ?? this.timeoutMultiplier)), this.minTimeout);\n const sendTimeout = AbortSignal.timeout(timeout);\n const timeoutSignal = anySignal([options.signal, sendTimeout]);\n setMaxListeners(Infinity, timeoutSignal, sendTimeout);\n timeoutSignal.start = Date.now();\n timeoutSignal.timeout = timeout;\n return timeoutSignal;\n }\n cleanUp(signal) {\n const time = Date.now() - signal.start;\n if (signal.aborted) {\n this.failure.push(time);\n this.next.push(time * this.failureMultiplier);\n this.metric?.update({\n failureMovingAverage: this.failure.movingAverage,\n failureDeviation: this.failure.deviation,\n failureForecast: this.failure.forecast,\n failureVariance: this.failure.variance,\n failure: time\n });\n }\n else {\n this.success.push(time);\n this.next.push(time);\n this.metric?.update({\n successMovingAverage: this.success.movingAverage,\n successDeviation: this.success.deviation,\n successForecast: this.success.forecast,\n successVariance: this.success.variance,\n success: time\n });\n }\n }\n}\n//# sourceMappingURL=adaptive-timeout.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { serviceCapabilities } from '@libp2p/interface';\nimport { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout';\nimport { byteStream } from 'it-byte-stream';\nconst DEFAULT_PING_INTERVAL_MS = 10000;\nconst PROTOCOL_VERSION = '1.0.0';\nconst PROTOCOL_NAME = 'ping';\nconst PROTOCOL_PREFIX = 'ipfs';\nconst PING_LENGTH = 32;\nexport class ConnectionMonitor {\n protocol;\n components;\n log;\n heartbeatInterval;\n pingIntervalMs;\n abortController;\n timeout;\n constructor(components, init = {}) {\n this.components = components;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.log = components.logger.forComponent('libp2p:connection-monitor');\n this.pingIntervalMs = init.pingInterval ?? DEFAULT_PING_INTERVAL_MS;\n this.timeout = new AdaptiveTimeout({\n ...(init.pingTimeout ?? {}),\n metrics: components.metrics,\n metricName: 'libp2p_connection_monitor_ping_time_milliseconds'\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-monitor';\n [serviceCapabilities] = [\n '@libp2p/connection-monitor'\n ];\n start() {\n this.abortController = new AbortController();\n this.heartbeatInterval = setInterval(() => {\n this.components.connectionManager.getConnections().forEach(conn => {\n Promise.resolve().then(async () => {\n let start = Date.now();\n try {\n const signal = this.timeout.getTimeoutSignal({\n signal: this.abortController?.signal\n });\n const stream = await conn.newStream(this.protocol, {\n signal,\n runOnTransientConnection: true\n });\n const bs = byteStream(stream);\n start = Date.now();\n await Promise.all([\n bs.write(randomBytes(PING_LENGTH), {\n signal\n }),\n bs.read(PING_LENGTH, {\n signal\n })\n ]);\n conn.rtt = Date.now() - start;\n await bs.unwrap().close({\n signal\n });\n }\n catch (err) {\n if (err.code !== 'ERR_UNSUPPORTED_PROTOCOL') {\n throw err;\n }\n // protocol was unsupported, but that's ok as it means the remote\n // peer was still alive. We ran multistream-select which means two\n // round trips (e.g. 1x for the mss header, then another for the\n // protocol) so divide the time it took by two\n conn.rtt = (Date.now() - start) / 2;\n }\n })\n .catch(err => {\n this.log.error('error during heartbeat, aborting connection', err);\n conn.abort(err);\n });\n });\n }, this.pingIntervalMs);\n }\n stop() {\n this.abortController?.abort();\n if (this.heartbeatInterval != null) {\n clearInterval(this.heartbeatInterval);\n }\n }\n}\n//# sourceMappingURL=connection-monitor.js.map","import { CodeError } from '@libp2p/interface';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport merge from 'it-merge';\nimport { codes, messages } from './errors.js';\nexport class CompoundContentRouting {\n routers;\n started;\n components;\n constructor(components, init) {\n this.routers = init.routers ?? [];\n this.started = false;\n this.components = components;\n }\n [Symbol.toStringTag] = '@libp2p/content-routing';\n isStarted() {\n return this.started;\n }\n async start() {\n this.started = true;\n }\n async stop() {\n this.started = false;\n }\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async *findProviders(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = new PeerSet();\n for await (const peer of merge(...self.routers.map(router => router.findProviders(key, options)))) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options);\n }));\n }\n /**\n * Store the given key/value pair in the available content routings\n */\n async put(key, value, options) {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options);\n }));\n }\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get(key, options) {\n if (!this.isStarted()) {\n throw new CodeError(messages.NOT_STARTED_YET, codes.ERR_NODE_NOT_STARTED);\n }\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options);\n }));\n }\n}\n//# sourceMappingURL=content-routing.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nexport const MAX_FINGERPRINT_SIZE = 64;\nexport class Fingerprint {\n fp;\n h;\n seed;\n constructor(buf, hash, seed, fingerprintSize = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size');\n }\n const fnv = hash.hashV(buf, seed);\n const fp = uint8ArrayAlloc(fingerprintSize);\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i];\n }\n if (fp.length === 0) {\n fp[0] = 7;\n }\n this.fp = fp;\n this.h = hash;\n this.seed = seed;\n }\n hash() {\n return this.h.hash(this.fp, this.seed);\n }\n equals(other) {\n if (!(other?.fp instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.fp, other.fp);\n }\n}\n//# sourceMappingURL=fingerprint.js.map","export function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n}\n//# sourceMappingURL=utils.js.map","import { Fingerprint } from './fingerprint.js';\nimport { getRandomInt } from './utils.js';\nexport class Bucket {\n contents;\n constructor(size) {\n this.contents = new Array(size).fill(null);\n }\n has(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n return this.contents.some((fp) => {\n return fingerprint.equals(fp);\n });\n }\n add(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint;\n return true;\n }\n }\n return true;\n }\n swap(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const i = getRandomInt(0, this.contents.length - 1);\n const current = this.contents[i];\n this.contents[i] = fingerprint;\n return current;\n }\n remove(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp);\n });\n if (found > -1) {\n this.contents[found] = null;\n return true;\n }\n else {\n return false;\n }\n }\n}\n//# sourceMappingURL=bucket.js.map","// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n","import fnv1aHash from '@sindresorhus/fnv1a';\nimport mur from 'murmurhash3js-revisited';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport const murmur3 = {\n hash: (input, seed) => {\n return mur.x86.hash32(input, seed);\n },\n hashV: (input, seed) => {\n return numberToBuffer(murmur3.hash(input, seed));\n }\n};\nexport const fnv1a = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }));\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed));\n }\n};\nexport function numberToBuffer(num) {\n let hex = num.toString(16);\n if (hex.length % 2 === 1) {\n hex = `0${hex}`;\n }\n return uint8ArrayFromString(hex, 'base16');\n}\n//# sourceMappingURL=hashes.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { Bucket } from './bucket.js';\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nconst maxCuckooCount = 500;\nexport class CuckooFilter {\n bucketSize;\n filterSize;\n fingerprintSize;\n buckets;\n count;\n hash;\n seed;\n constructor(init) {\n this.filterSize = init.filterSize;\n this.bucketSize = init.bucketSize ?? 4;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.count = 0;\n this.buckets = [];\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize);\n }\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize);\n }\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++;\n return true;\n }\n const rand = [j, k];\n let i = rand[getRandomInt(0, rand.length - 1)];\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint);\n if (swapped == null) {\n continue;\n }\n i = (i ^ swapped.hash()) % this.filterSize;\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n if (this.buckets[i].add(swapped)) {\n this.count++;\n return true;\n }\n else {\n continue;\n }\n }\n return false;\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.has(fingerprint) ?? false;\n if (inJ) {\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n return this.buckets[k]?.has(fingerprint) ?? false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false;\n if (inJ) {\n this.count--;\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n const inK = this.buckets[k]?.remove(fingerprint) ?? false;\n if (inK) {\n this.count--;\n }\n return inK;\n }\n get reliable() {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90;\n }\n}\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n};\nfunction calculateBucketSize(errorRate = 0.001) {\n if (errorRate > 0.002) {\n return 2;\n }\n if (errorRate > 0.00001) {\n return 4;\n }\n return 8;\n}\nexport function optimize(maxItems, errorRate = 0.001) {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate);\n const load = MAX_LOAD[bucketSize];\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load);\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE);\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n };\n}\nexport function createCuckooFilter(maxItems, errorRate = 0.005) {\n const opts = optimize(maxItems, errorRate);\n return new CuckooFilter(opts);\n}\n//# sourceMappingURL=cuckoo-filter.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { CuckooFilter, optimize } from './cuckoo-filter.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nexport class ScalableCuckooFilter {\n filterSize;\n bucketSize;\n fingerprintSize;\n scale;\n filterSeries;\n hash;\n seed;\n constructor(init) {\n this.bucketSize = init.bucketSize ?? 4;\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.scale = init.scale ?? 2;\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ];\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n if (this.has(item)) {\n return true;\n }\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable;\n });\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length);\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n });\n this.filterSeries.push(current);\n }\n return current.add(item);\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true;\n }\n }\n return false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true;\n }\n }\n return false;\n }\n get count() {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count;\n }, 0);\n }\n}\nexport function createScalableCuckooFilter(maxItems, errorRate = 0.001, options) {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n });\n}\n//# sourceMappingURL=scalable-cuckoo-filter.js.map","/**\n * @packageDocumentation\n *\n * Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input\n *\n * @example\n *\n * ```javascript\n * import parallel from 'it-parallel'\n * import all from 'it-all'\n * import delay from 'delay'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const input = [\n * async () => {\n * console.info('start 1')\n * await delay(500)\n *\n * console.info('end 1')\n * return 1\n * },\n * async () => {\n * console.info('start 2')\n * await delay(200)\n *\n * console.info('end 2')\n * return 2\n * },\n * async () => {\n * console.info('start 3')\n * await delay(100)\n *\n * console.info('end 3')\n * return 3\n * }\n * ]\n *\n * const result = await all(parallel(input, {\n * concurrency: 2\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [2, 3, 1]\n * ```\n *\n * If order is important, pass `ordered: true` as an option:\n *\n * ```javascript\n * const result = await all(parallel(input, {\n * concurrency: 2,\n * ordered: true\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [1, 2, 3]\n * ```\n */\nimport defer from 'p-defer';\nconst CustomEvent = globalThis.CustomEvent ?? Event;\n/**\n * Takes an (async) iterator that emits promise-returning functions,\n * invokes them in parallel and emits the results as they become available but\n * in the same order as the input\n */\nexport default async function* parallel(source, options = {}) {\n let concurrency = options.concurrency ?? Infinity;\n if (concurrency < 1) {\n concurrency = Infinity;\n }\n const ordered = options.ordered == null ? false : options.ordered;\n const emitter = new EventTarget();\n const ops = [];\n let slotAvailable = defer();\n let resultAvailable = defer();\n let sourceFinished = false;\n let sourceErr;\n let opErred = false;\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve();\n });\n void Promise.resolve().then(async () => {\n try {\n for await (const task of source) {\n if (ops.length === concurrency) {\n slotAvailable = defer();\n await slotAvailable.promise;\n }\n if (opErred) {\n break;\n }\n const op = {\n done: false\n };\n ops.push(op);\n task()\n .then(result => {\n op.done = true;\n op.ok = true;\n op.value = result;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }, err => {\n op.done = true;\n op.err = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n });\n }\n sourceFinished = true;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n catch (err) {\n sourceErr = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n });\n function valuesAvailable() {\n if (ordered) {\n return ops[0]?.done;\n }\n return Boolean(ops.find(op => op.done));\n }\n function* yieldOrderedValues() {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0];\n ops.shift();\n if (op.ok) {\n yield op.value;\n }\n else {\n // allow the source to exit\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n function* yieldUnOrderedValues() {\n // more values can become available while we wait for `yield`\n // to return control to this function\n while (valuesAvailable()) {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].done) {\n const op = ops[i];\n ops.splice(i, 1);\n i--;\n if (op.ok) {\n yield op.value;\n }\n else {\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n }\n }\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer();\n await resultAvailable.promise;\n }\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr;\n }\n if (ordered) {\n yield* yieldOrderedValues();\n }\n else {\n yield* yieldUnOrderedValues();\n }\n if (sourceFinished && ops.length === 0) {\n // not waiting for any results and no more tasks so we are done\n break;\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { CodeError } from '@libp2p/interface';\nimport { createScalableCuckooFilter } from '@libp2p/utils/filters';\nimport merge from 'it-merge';\nimport parallel from 'it-parallel';\nimport { codes, messages } from './errors.js';\nexport class DefaultPeerRouting {\n log;\n peerId;\n peerStore;\n routers;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing');\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.routers = init.routers ?? [];\n }\n [Symbol.toStringTag] = '@libp2p/peer-routing';\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer(id, options) {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n if (id.toString() === this.peerId.toString()) {\n throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF);\n }\n const self = this;\n const source = merge(...this.routers.map(router => (async function* () {\n try {\n yield await router.findPeer(id, options);\n }\n catch (err) {\n self.log.error(err);\n }\n })()));\n for await (const peer of source) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n return peer;\n }\n throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND);\n }\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async *getClosestPeers(key, options = {}) {\n if (this.routers.length === 0) {\n throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = createScalableCuckooFilter(1024);\n for await (const peer of parallel(async function* () {\n const source = merge(...self.routers.map(router => router.getClosestPeers(key, options)));\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n });\n }\n catch (err) {\n self.log.error('could not find peer multiaddrs', err);\n return;\n }\n }\n return peer;\n };\n }\n }())) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id.toBytes())) {\n continue;\n }\n seen.add(peer.id.toBytes());\n yield peer;\n }\n }\n}\n//# sourceMappingURL=peer-routing.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { TypedEventEmitter, setMaxListeners } from '@libp2p/interface';\nimport { anySignal } from 'any-signal';\nimport pDefer, {} from 'p-defer';\nimport { raceEvent } from 'race-event';\nimport { raceSignal } from 'race-signal';\nexport class RandomWalk extends TypedEventEmitter {\n peerRouting;\n log;\n walking;\n walkers;\n shutdownController;\n walkController;\n needNext;\n constructor(components) {\n super();\n this.log = components.logger.forComponent('libp2p:random-walk');\n this.peerRouting = components.peerRouting;\n this.walkers = 0;\n this.walking = false;\n // stops any in-progress walks when the node is shut down\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n [Symbol.toStringTag] = '@libp2p/random-walk';\n start() {\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n stop() {\n this.shutdownController.abort();\n }\n async *walk(options) {\n if (!this.walking) {\n // start the query that causes walk:peer events to be emitted\n this.startWalk();\n }\n this.walkers++;\n const signal = anySignal([this.shutdownController.signal, options?.signal]);\n setMaxListeners(Infinity, signal);\n try {\n while (true) {\n // if another consumer has paused the query, start it again\n this.needNext?.resolve();\n this.needNext = pDefer();\n // wait for a walk:peer or walk:error event\n const event = await raceEvent(this, 'walk:peer', signal, {\n errorEvent: 'walk:error'\n });\n yield event.detail;\n }\n }\n finally {\n signal.clear();\n this.walkers--;\n // stop the walk if no more consumers are interested\n if (this.walkers === 0) {\n this.walkController?.abort();\n this.walkController = undefined;\n }\n }\n }\n startWalk() {\n this.walking = true;\n // the signal for this controller will be aborted if no more random peers\n // are required\n this.walkController = new AbortController();\n setMaxListeners(Infinity, this.walkController.signal);\n const signal = anySignal([this.walkController.signal, this.shutdownController.signal]);\n setMaxListeners(Infinity, signal);\n const start = Date.now();\n let found = 0;\n Promise.resolve().then(async () => {\n this.log('start walk');\n // find peers until no more consumers are interested\n while (this.walkers > 0) {\n try {\n const data = randomBytes(32);\n let s = Date.now();\n for await (const peer of this.peerRouting.getClosestPeers(data, { signal })) {\n if (signal.aborted) {\n this.log('aborting walk');\n }\n signal.throwIfAborted();\n this.log('found peer %p after %dms for %d walkers', peer.id, Date.now() - s, this.walkers);\n found++;\n this.safeDispatchEvent('walk:peer', {\n detail: peer\n });\n // if we only have one consumer, pause the query until they request\n // another random peer or they signal they are no longer interested\n if (this.walkers === 1 && this.needNext != null) {\n this.log('wait for need next');\n await raceSignal(this.needNext.promise, signal);\n }\n s = Date.now();\n }\n this.log('walk iteration for %b and %d walkers finished, found %d peers', data, this.walkers, found);\n }\n catch (err) {\n this.log.error('randomwalk errored', err);\n this.safeDispatchEvent('walk:error', {\n detail: err\n });\n }\n }\n this.log('no walkers left, ended walk');\n })\n .catch(err => {\n this.log.error('randomwalk errored', err);\n })\n .finally(() => {\n this.log('finished walk, found %d peers after %dms', found, Date.now() - start);\n this.walking = false;\n });\n }\n}\n//# sourceMappingURL=random-walk.js.map","import { CodeError } from '@libp2p/interface';\nimport merge from 'merge-options';\nimport { codes } from './errors.js';\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32;\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64;\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar {\n log;\n topologies;\n handlers;\n components;\n constructor(components) {\n this.log = components.logger.forComponent('libp2p:registrar');\n this.topologies = new Map();\n this.handlers = new Map();\n this.components = components;\n this._onDisconnect = this._onDisconnect.bind(this);\n this._onPeerUpdate = this._onPeerUpdate.bind(this);\n this._onPeerIdentify = this._onPeerIdentify.bind(this);\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect);\n this.components.events.addEventListener('peer:update', this._onPeerUpdate);\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify);\n }\n [Symbol.toStringTag] = '@libp2p/registrar';\n getProtocols() {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort();\n }\n getHandler(protocol) {\n const handler = this.handlers.get(protocol);\n if (handler == null) {\n throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL);\n }\n return handler;\n }\n getTopologies(protocol) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n return [];\n }\n return [\n ...topologies.values()\n ];\n }\n /**\n * Registers the `handler` for each protocol\n */\n async handle(protocol, handler, opts) {\n if (this.handlers.has(protocol)) {\n throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);\n }\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts);\n this.handlers.set(protocol, {\n handler,\n options\n });\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n });\n }\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle(protocols) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols];\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol);\n });\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n });\n }\n /**\n * Register handlers for a set of multicodecs given\n */\n async register(protocol, topology) {\n if (topology == null) {\n throw new CodeError('invalid topology', codes.ERR_INVALID_PARAMETERS);\n }\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`;\n let topologies = this.topologies.get(protocol);\n if (topologies == null) {\n topologies = new Map();\n this.topologies.set(protocol, topologies);\n }\n topologies.set(id, topology);\n return id;\n }\n /**\n * Unregister topology\n */\n unregister(id) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id);\n if (topologies.size === 0) {\n this.topologies.delete(protocol);\n }\n }\n }\n }\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect(evt) {\n const remotePeer = evt.detail;\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(remotePeer) === false) {\n continue;\n }\n topology.filter?.remove(remotePeer);\n topology.onDisconnect?.(remotePeer);\n }\n }\n })\n .catch(err => {\n if (err.code === codes.ERR_NOT_FOUND) {\n // peer has not completed identify so they are not in the peer store\n return;\n }\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err);\n });\n }\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate(evt) {\n const { peer, previous } = evt.detail;\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol));\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(peer.id) === false) {\n continue;\n }\n topology.filter?.remove(peer.id);\n topology.onDisconnect?.(peer.id);\n }\n }\n }\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify(evt) {\n const protocols = evt.detail.protocols;\n const connection = evt.detail.connection;\n const peerId = evt.detail.peerId;\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (connection.transient && topology.notifyOnTransient !== true) {\n continue;\n }\n if (topology.filter?.has(peerId) === true) {\n continue;\n }\n topology.filter?.add(peerId);\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n}\n//# sourceMappingURL=registrar.js.map","class TrackedMap extends Map {\n metric;\n constructor(init) {\n super();\n const { name, metrics } = init;\n this.metric = metrics.registerMetric(name);\n this.updateComponentMetric();\n }\n set(key, value) {\n super.set(key, value);\n this.updateComponentMetric();\n return this;\n }\n delete(key) {\n const deleted = super.delete(key);\n this.updateComponentMetric();\n return deleted;\n }\n clear() {\n super.clear();\n this.updateComponentMetric();\n }\n updateComponentMetric() {\n this.metric.update(this.size);\n }\n}\nexport function trackedMap(config) {\n const { name, metrics } = config;\n let map;\n if (metrics != null) {\n map = new TrackedMap({ name, metrics });\n }\n else {\n map = new Map();\n }\n return map;\n}\n//# sourceMappingURL=tracked-map.js.map","import { CodeError, FaultTolerance } from '@libp2p/interface';\nimport { trackedMap } from '@libp2p/utils/tracked-map';\nimport { CustomProgressEvent } from 'progress-events';\nimport { codes } from './errors.js';\nexport class DefaultTransportManager {\n log;\n components;\n transports;\n listeners;\n faultTolerance;\n started;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:transports');\n this.components = components;\n this.started = false;\n this.transports = new Map();\n this.listeners = trackedMap({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n });\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL;\n }\n [Symbol.toStringTag] = '@libp2p/transport-manager';\n /**\n * Adds a `Transport` to the manager\n */\n add(transport) {\n const tag = transport[Symbol.toStringTag];\n if (tag == null) {\n throw new CodeError('Transport must have a valid tag', codes.ERR_INVALID_KEY);\n }\n if (this.transports.has(tag)) {\n throw new CodeError(`There is already a transport with the tag ${tag}`, codes.ERR_DUPLICATE_TRANSPORT);\n }\n this.log('adding transport %s', tag);\n this.transports.set(tag, transport);\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, []);\n }\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs();\n await this.listen(addrs);\n }\n /**\n * Stops all listeners\n */\n async stop() {\n const tasks = [];\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n }\n await Promise.all(tasks);\n this.log('all listeners closed');\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, []);\n }\n this.started = false;\n }\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial(ma, options) {\n const transport = this.dialTransportForMultiaddr(ma);\n if (transport == null) {\n throw new CodeError(`No transport available for address ${String(ma)}`, codes.ERR_TRANSPORT_UNAVAILABLE);\n }\n options?.onProgress?.(new CustomProgressEvent('transport-manager:selected-transport', transport[Symbol.toStringTag]));\n try {\n // @ts-expect-error the transport has a typed onProgress option but we\n // can't predict what transport implementation we selected so all we can\n // do is pass the onProgress handler in and hope for the best\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n });\n }\n catch (err) {\n if (err.code == null) {\n err.code = codes.ERR_TRANSPORT_DIAL_FAILED;\n }\n throw err;\n }\n }\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs() {\n let addrs = [];\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()];\n }\n }\n return addrs;\n }\n /**\n * Returns all the transports instances\n */\n getTransports() {\n return Array.of(...this.transports.values());\n }\n /**\n * Returns all the listener instances\n */\n getListeners() {\n return Array.of(...this.listeners.values()).flat();\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n dialTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.dialFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n listenTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.listenFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen(addrs) {\n if (!this.isStarted()) {\n throw new CodeError('Not started', codes.ERR_NODE_NOT_STARTED);\n }\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only');\n return;\n }\n const couldNotListen = [];\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.listenFilter(addrs);\n const tasks = [];\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr);\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n });\n let listeners = this.listeners.get(key) ?? [];\n if (listeners == null) {\n listeners = [];\n this.listeners.set(key, listeners);\n }\n listeners.push(listener);\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n });\n });\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener);\n // remove the listener\n listeners.splice(index, 1);\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n });\n });\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr));\n }\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key);\n continue;\n }\n const results = await Promise.allSettled(tasks);\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled');\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw new CodeError(`Transport (${key}) could not listen on any available address`, codes.ERR_NO_VALID_ADDRESSES);\n }\n }\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`;\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw new CodeError(message, codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log(`libp2p in dial mode only: ${message}`);\n }\n }\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove(key) {\n const listeners = this.listeners.get(key) ?? [];\n this.log.trace('removing transport %s', key);\n // Close any running listeners\n const tasks = [];\n this.log.trace('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n await Promise.all(tasks);\n this.transports.delete(key);\n this.listeners.delete(key);\n }\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll() {\n const tasks = [];\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key));\n }\n await Promise.all(tasks);\n }\n}\n//# sourceMappingURL=transport-manager.js.map","export const PROTOCOL_ID = '/multistream/1.0.0';\n// Conforming to go-libp2p\n// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297\nexport const MAX_PROTOCOL_LENGTH = 1024;\n//# sourceMappingURL=constants.js.map","import { CodeError } from '@libp2p/interface';\nimport {} from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst NewLine = uint8ArrayFromString('\\n');\n/**\n * `write` encodes and writes a single buffer\n */\nexport async function write(writer, buffer, options) {\n await writer.write(buffer, options);\n}\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport async function writeAll(writer, buffers, options) {\n await writer.writeV(buffers, options);\n}\n/**\n * Read a length-prefixed buffer from the passed stream, stripping the final newline character\n */\nexport async function read(reader, options) {\n const buf = await reader.read(options);\n if (buf.byteLength === 0 || buf.get(buf.byteLength - 1) !== NewLine[0]) {\n options.log.error('Invalid mss message - missing newline', buf);\n throw new CodeError('missing newline', 'ERR_INVALID_MULTISTREAM_SELECT_MESSAGE');\n }\n return buf.sublist(0, -1); // Remove newline\n}\n/**\n * Read a length-prefixed string from the passed stream, stripping the final newline character\n */\nexport async function readString(reader, options) {\n const buf = await read(reader, options);\n return uint8ArrayToString(buf.subarray());\n}\n//# sourceMappingURL=multistream.js.map","import { encode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH, PROTOCOL_ID } from './constants.js';\nimport * as multistream from './multistream.js';\n/**\n * Handle multistream protocol selections for the given list of protocols.\n *\n * Note that after a protocol is handled `listener` can no longer be used.\n *\n * @param stream - A duplex iterable stream to listen on\n * @param protocols - A list of protocols (or single protocol) that this listener is able to speak.\n * @param options - an options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex({\n * async onStream (muxedStream) {\n * // mss.handle(handledProtocols)\n * // Returns selected stream and protocol\n * const { stream, protocol } = await mss.handle(muxedStream, [\n * '/ipfs-dht/1.0.0',\n * '/ipfs-bitswap/1.0.0'\n * ])\n *\n * // Typically here we'd call the handler function that was registered in\n * // libp2p for the given protocol:\n * // e.g. handlers[protocol].handler(stream)\n * //\n * // If protocol was /ipfs-dht/1.0.0 it might do something like this:\n * // try {\n * // await pipe(\n * // dhtStream,\n * // source => (async function * () {\n * // for await (const chunk of source)\n * // // Incoming DHT data -> process and yield to respond\n * // })(),\n * // dhtStream\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * }\n * })\n * ```\n */\nexport async function handle(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n options.log.trace('handle: available protocols %s', protocols);\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH,\n maxLengthLength: 2 // 2 bytes is enough to length-prefix MAX_PROTOCOL_LENGTH\n });\n while (true) {\n options.log.trace('handle: reading incoming string');\n const protocol = await multistream.readString(lp, options);\n options.log.trace('handle: read \"%s\"', protocol);\n if (protocol === PROTOCOL_ID) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${PROTOCOL_ID}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n continue;\n }\n if (protocols.includes(protocol)) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', protocol, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', protocol, protocol);\n return { stream: lp.unwrap(), protocol };\n }\n if (protocol === 'ls') {\n // \\n\\n\\n\n const protos = new Uint8ArrayList(...protocols.map(p => encode.single(uint8ArrayFromString(`${p}\\n`))), uint8ArrayFromString('\\n'));\n options.log.trace('handle: respond with \"%s\" for %s', protocols, protocol);\n await multistream.write(lp, protos, options);\n options.log.trace('handle: responded with \"%s\" for %s', protocols, protocol);\n continue;\n }\n options.log('handle: respond with \"na\" for \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString('na\\n'), options);\n options.log('handle: responded with \"na\" for \"%s\"', protocol);\n }\n}\n//# sourceMappingURL=handle.js.map","import { CodeError } from '@libp2p/interface';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH } from './constants.js';\nimport * as multistream from './multistream.js';\nimport { PROTOCOL_ID } from './index.js';\n/**\n * Negotiate a protocol to use from a list of protocols.\n *\n * @param stream - A duplex iterable stream to dial on\n * @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.\n * @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex()\n * const muxedStream = muxer.newStream()\n *\n * // mss.select(protocol(s))\n * // Select from one of the passed protocols (in priority order)\n * // Returns selected stream and protocol\n * const { stream: dhtStream, protocol } = await mss.select(muxedStream, [\n * // This might just be different versions of DHT, but could be different impls\n * '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.\n * '/ipfs-dht/1.0.0'\n * ])\n *\n * // Typically this stream will be passed back to the caller of libp2p.dialProtocol\n * //\n * // ...it might then do something like this:\n * // try {\n * // await pipe(\n * // [uint8ArrayFromString('Some DHT data')]\n * // dhtStream,\n * // async source => {\n * // for await (const chunk of source)\n * // // DHT response data\n * // }\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * ```\n */\nexport async function select(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols];\n if (protocols.length === 1 && options.negotiateFully === false) {\n return optimisticSelect(stream, protocols[0], options);\n }\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n const protocol = protocols.shift();\n if (protocol == null) {\n throw new Error('At least one protocol must be specified');\n }\n options.log.trace('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol);\n const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\\n`);\n const p2 = uint8ArrayFromString(`${protocol}\\n`);\n await multistream.writeAll(lp, [p1, p2], options);\n options.log.trace('select: reading multistream-select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n options.log.trace('select: reading protocol response');\n response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n }\n // We're done\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n options.log.trace('select: write \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('select: reading protocol response');\n const response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\" for \"%s\"', response, protocol);\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n }\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL');\n}\n/**\n * Optimistically negotiates a protocol.\n *\n * It *does not* block writes waiting for the other end to respond. Instead, it\n * simply assumes the negotiation went successfully and starts writing data.\n *\n * Use when it is known that the receiver supports the desired protocol.\n */\nfunction optimisticSelect(stream, protocol, options) {\n const originalSink = stream.sink.bind(stream);\n const originalSource = stream.source;\n let negotiated = false;\n let negotiating = false;\n const doneNegotiating = pDefer();\n let sentProtocol = false;\n let sendingProtocol = false;\n const doneSendingProtocol = pDefer();\n let readProtocol = false;\n let readingProtocol = false;\n const doneReadingProtocol = pDefer();\n const lp = lpStream({\n sink: originalSink,\n source: originalSource\n }, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n stream.sink = async (source) => {\n const { sink } = lp.unwrap();\n await sink(async function* () {\n let sentData = false;\n for await (const buf of source) {\n // started reading before the source yielded, wait for protocol send\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n }\n // writing before reading, send the protocol and the first chunk of data\n if (!sentProtocol) {\n sendingProtocol = true;\n options.log.trace('optimistic: write [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n const protocolString = `${protocol}\\n`;\n // send protocols in first chunk of data written to transport\n yield new Uint8ArrayList(Uint8Array.from([19]), // length of PROTOCOL_ID plus newline\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`), varint.encode(protocolString.length), uint8ArrayFromString(protocolString), buf).subarray();\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n // read the negotiation response but don't block more sending\n negotiate()\n .catch(err => {\n options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err);\n });\n }\n else {\n yield buf;\n }\n sentData = true;\n }\n // special case - the source passed to the sink has ended but we didn't\n // negotiated the protocol yet so do it now\n if (!sentData) {\n await negotiate();\n }\n }());\n };\n async function negotiate() {\n if (negotiating) {\n options.log.trace('optimistic: already negotiating %s stream', protocol);\n await doneNegotiating.promise;\n return;\n }\n negotiating = true;\n try {\n // we haven't sent the protocol yet, send it now\n if (!sentProtocol) {\n options.log.trace('optimistic: doing send protocol for %s stream', protocol);\n await doSendProtocol();\n }\n // if we haven't read the protocol response yet, do it now\n if (!readProtocol) {\n options.log.trace('optimistic: doing read protocol for %s stream', protocol);\n await doReadProtocol();\n }\n }\n finally {\n negotiating = false;\n negotiated = true;\n doneNegotiating.resolve();\n }\n }\n async function doSendProtocol() {\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n return;\n }\n sendingProtocol = true;\n try {\n options.log.trace('optimistic: write [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n await lp.writeV([\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n uint8ArrayFromString(`${protocol}\\n`)\n ]);\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n }\n finally {\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n }\n }\n async function doReadProtocol() {\n if (readingProtocol) {\n await doneReadingProtocol.promise;\n return;\n }\n readingProtocol = true;\n try {\n options.log.trace('optimistic: reading multistream select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('optimistic: read multistream select header \"%s\"', response);\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(lp, options);\n }\n options.log.trace('optimistic: read protocol \"%s\", expecting \"%s\"', response, protocol);\n if (response !== protocol) {\n throw new CodeError('protocol selection failed', 'ERR_UNSUPPORTED_PROTOCOL');\n }\n }\n finally {\n readProtocol = true;\n readingProtocol = false;\n doneReadingProtocol.resolve();\n }\n }\n stream.source = (async function* () {\n // make sure we've done protocol negotiation before we read stream data\n await negotiate();\n options.log.trace('optimistic: reading data from \"%s\" stream', protocol);\n yield* lp.unwrap().source;\n })();\n if (stream.closeRead != null) {\n const originalCloseRead = stream.closeRead.bind(stream);\n stream.closeRead = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the readable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close read', err);\n });\n }\n // protocol has been negotiated, ok to close the readable end\n await originalCloseRead(opts);\n };\n }\n if (stream.closeWrite != null) {\n const originalCloseWrite = stream.closeWrite.bind(stream);\n stream.closeWrite = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the writable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close write', err);\n });\n }\n // protocol has been negotiated, ok to close the writable end\n await originalCloseWrite(opts);\n };\n }\n if (stream.close != null) {\n const originalClose = stream.close.bind(stream);\n stream.close = async (opts) => {\n // if we are in the process of negotiation, let it finish before closing\n // because we may have unsent early data\n const tasks = [];\n if (sendingProtocol) {\n tasks.push(doneSendingProtocol.promise);\n }\n if (readingProtocol) {\n tasks.push(doneReadingProtocol.promise);\n }\n if (tasks.length > 0) {\n // let the in-flight protocol negotiation finish gracefully\n await raceSignal(Promise.all(tasks), opts?.signal);\n }\n else {\n // no protocol negotiation attempt has occurred so don't start one\n negotiated = true;\n negotiating = false;\n doneNegotiating.resolve();\n }\n // protocol has been negotiated, ok to close the writable end\n await originalClose(opts);\n };\n }\n return {\n stream,\n protocol\n };\n}\n//# sourceMappingURL=select.js.map","export const connectionSymbol = Symbol.for('@libp2p/connection');\nexport function isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map","import { connectionSymbol, CodeError, setMaxListeners } from '@libp2p/interface';\nconst CLOSE_TIMEOUT = 500;\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl {\n /**\n * Connection identifier.\n */\n id;\n /**\n * Observed multiaddr of the remote peer\n */\n remoteAddr;\n /**\n * Remote peer id\n */\n remotePeer;\n direction;\n timeline;\n multiplexer;\n encryption;\n status;\n transient;\n log;\n /**\n * User provided tags\n *\n */\n tags;\n /**\n * Reference to the new stream function of the multiplexer\n */\n _newStream;\n /**\n * Reference to the close function of the raw connection\n */\n _close;\n _abort;\n /**\n * Reference to the getStreams function of the muxer\n */\n _getStreams;\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor(init) {\n const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init;\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`;\n this.remoteAddr = remoteAddr;\n this.remotePeer = remotePeer;\n this.direction = init.direction;\n this.status = 'open';\n this.timeline = init.timeline;\n this.multiplexer = init.multiplexer;\n this.encryption = init.encryption;\n this.transient = init.transient ?? false;\n this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`);\n if (this.remoteAddr.getPeerId() == null) {\n this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`);\n }\n this._newStream = newStream;\n this._close = close;\n this._abort = abort;\n this._getStreams = getStreams;\n this.tags = [];\n }\n [Symbol.toStringTag] = 'Connection';\n [connectionSymbol] = true;\n /**\n * Get all the streams of the muxer\n */\n get streams() {\n return this._getStreams();\n }\n /**\n * Create a new stream from this connection\n */\n async newStream(protocols, options) {\n if (this.status === 'closing') {\n throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED');\n }\n if (this.status === 'closed') {\n throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED');\n }\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n if (this.transient && options?.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n const stream = await this._newStream(protocols, options);\n stream.direction = 'outbound';\n return stream;\n }\n /**\n * Close the connection\n */\n async close(options = {}) {\n if (this.status === 'closed' || this.status === 'closing') {\n return;\n }\n this.log('closing connection to %a', this.remoteAddr);\n this.status = 'closing';\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n this.log.trace('closing all streams');\n // close all streams gracefully - this can throw if we're not multiplexed\n await Promise.all(this.streams.map(async (s) => s.close(options)));\n this.log.trace('closing underlying transport');\n // close raw connection\n await this._close(options);\n this.log.trace('updating timeline with close time');\n this.status = 'closed';\n this.timeline.close = Date.now();\n }\n catch (err) {\n this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err);\n this.abort(err);\n }\n }\n abort(err) {\n this.log.error('aborting connection to %a due to error', this.remoteAddr, err);\n this.status = 'closing';\n this.streams.forEach(s => { s.abort(err); });\n this.log.error('all streams aborted', this.streams.length);\n // Abort raw connection\n this._abort(err);\n this.timeline.close = Date.now();\n this.status = 'closed';\n }\n}\nexport function createConnection(init) {\n return new ConnectionImpl(init);\n}\n//# sourceMappingURL=index.js.map","import { CodeError, ERR_TIMEOUT, setMaxListeners } from '@libp2p/interface';\nimport * as mss from '@libp2p/multistream-select';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { CustomProgressEvent } from 'progress-events';\nimport { createConnection } from './connection/index.js';\nimport { INBOUND_UPGRADE_TIMEOUT } from './connection-manager/constants.js';\nimport { codes } from './errors.js';\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js';\nconst DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000;\nfunction findIncomingStreamLimit(protocol, registrar) {\n try {\n const { options } = registrar.getHandler(protocol);\n return options.maxInboundStreams;\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return DEFAULT_MAX_INBOUND_STREAMS;\n}\nfunction findOutgoingStreamLimit(protocol, registrar, options = {}) {\n try {\n const { options } = registrar.getHandler(protocol);\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams;\n }\n }\n catch (err) {\n if (err.code !== codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS;\n}\nfunction countStreams(protocol, direction, connection) {\n let streamCount = 0;\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++;\n }\n });\n return streamCount;\n}\nexport class DefaultUpgrader {\n components;\n connectionEncryption;\n muxers;\n inboundUpgradeTimeout;\n events;\n constructor(components, init) {\n this.components = components;\n this.connectionEncryption = new Map();\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter);\n });\n this.muxers = new Map();\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer);\n });\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? INBOUND_UPGRADE_TIMEOUT;\n this.events = components.events;\n }\n [Symbol.toStringTag] = '@libp2p/upgrader';\n async shouldBlockConnection(remotePeer, maConn, connectionType) {\n const connectionGater = this.components.connectionGater[connectionType];\n if (connectionGater !== undefined) {\n if (await connectionGater(remotePeer, maConn)) {\n throw new CodeError(`The multiaddr connection is blocked by gater.${connectionType}`, codes.ERR_CONNECTION_INTERCEPTED);\n }\n }\n }\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound(maConn, opts) {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn);\n if (!accept) {\n throw new CodeError('connection denied', codes.ERR_CONNECTION_DENIED);\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let muxerFactory;\n let cryptoProtocol;\n const signal = AbortSignal.timeout(this.inboundUpgradeTimeout);\n const onAbort = () => {\n maConn.abort(new CodeError('inbound upgrade timeout', ERR_TIMEOUT));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n setMaxListeners(Infinity, signal);\n try {\n if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {\n throw new CodeError('The multiaddr connection is blocked by gater.acceptConnection', codes.ERR_CONNECTION_INTERCEPTED);\n }\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the inbound connection upgrade');\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n maConn.log('protecting the inbound connection');\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n opts?.onProgress?.(new CustomProgressEvent('upgrader:encrypt-inbound-connection'));\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection');\n }\n else {\n const idStr = maConn.remoteAddr.getPeerId();\n if (idStr == null) {\n throw new CodeError('inbound connection that skipped encryption must have a peer id', codes.ERR_INVALID_MULTIADDR);\n }\n const remotePeerId = peerIdFromString(idStr);\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n opts?.onProgress?.(new CustomProgressEvent('upgrader:multiplex-inbound-connection'));\n // Multiplex the connection\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade inbound connection', err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection');\n maConn.log('successfully upgraded inbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n finally {\n signal.removeEventListener('abort', onAbort);\n this.components.connectionManager.afterUpgradeInbound();\n }\n }\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound(maConn, opts) {\n const idStr = maConn.remoteAddr.getPeerId();\n let remotePeerId;\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr);\n await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection');\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let cryptoProtocol;\n let muxerFactory;\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the outbound connection upgrade');\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection');\n }\n else {\n if (remotePeerId == null) {\n throw new CodeError('Encryption was skipped but no peer id was passed', codes.ERR_INVALID_PEER);\n }\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade outbound connection', err);\n await maConn.close(err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection');\n maConn.log('successfully upgraded outbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection(opts) {\n const { cryptoProtocol, direction, maConn, upgradedConn, remotePeer, muxerFactory, transient } = opts;\n let muxer;\n let newStream;\n let connection; // eslint-disable-line prefer-const\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return;\n }\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols();\n const { stream, protocol } = await mss.handle(muxedStream, protocols, {\n log: muxedStream.log,\n yieldBytes: false\n });\n if (connection == null) {\n return;\n }\n connection.log('incoming stream opened on %s', protocol);\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar);\n const streamCount = countStreams(protocol, 'inbound', connection);\n if (streamCount === incomingLimit) {\n const err = new CodeError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`, codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n this._onStream({ connection, stream: muxedStream, protocol });\n })\n .catch(async (err) => {\n connection.log.error('error handling incoming stream id %s', muxedStream.id, err.message, err.code, err.stack);\n if (muxedStream.timeline.close == null) {\n await muxedStream.close();\n }\n });\n }\n });\n newStream = async (protocols, options = {}) => {\n if (muxer == null) {\n throw new CodeError('Stream is not multiplexed', codes.ERR_MUXER_UNAVAILABLE);\n }\n connection.log('starting new stream for protocols %s', protocols);\n const muxedStream = await muxer.newStream();\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols);\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols);\n const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n muxedStream.log.trace('selecting protocol from protocols %s', protocols);\n const { stream, protocol } = await mss.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n });\n muxedStream.log('selected protocol %s', protocol);\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);\n const streamCount = countStreams(protocol, 'outbound', connection);\n if (streamCount >= outgoingLimit) {\n const err = new CodeError(`Too many outbound protocol streams for protocol \"${protocol}\" - ${streamCount}/${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n return muxedStream;\n }\n catch (err) {\n connection.log.error('could not create new stream for protocols %s', protocols, err);\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err);\n }\n if (err.code != null) {\n throw err;\n }\n throw new CodeError(String(err), codes.ERR_UNSUPPORTED_PROTOCOL);\n }\n };\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer', err);\n });\n }\n const _timeline = maConn.timeline;\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close();\n }\n }\n catch (err) {\n connection.log.error('error closing connection after timeline close', err);\n }\n finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n });\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event', err);\n });\n }\n return Reflect.set(...args);\n }\n });\n maConn.timeline.upgraded = Date.now();\n const errConnectionNotMultiplexed = () => {\n throw new CodeError('connection is not multiplexed', codes.ERR_CONNECTION_NOT_MULTIPLEXED);\n };\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n transient,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => { if (muxer != null) {\n return muxer.streams;\n }\n else {\n return [];\n } },\n close: async (options) => {\n // Ensure remaining streams are closed gracefully\n if (muxer != null) {\n connection.log.trace('close muxer');\n await muxer.close(options);\n }\n connection.log.trace('close maconn');\n // close the underlying transport\n await maConn.close(options);\n connection.log.trace('closed maconn');\n },\n abort: (err) => {\n maConn.abort(err);\n // Ensure remaining streams are aborted\n if (muxer != null) {\n muxer.abort(err);\n }\n }\n });\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n });\n return connection;\n }\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream(opts) {\n const { connection, stream, protocol } = opts;\n const { handler, options } = this.components.registrar.getHandler(protocol);\n if (connection.transient && options.runOnTransientConnection !== true) {\n throw new CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n handler({ connection, stream });\n }\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound(connection) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('handling inbound crypto protocol selection', protocols);\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting inbound connection using', protocol);\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting inbound connection failed', err);\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound(connection, remotePeerId) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('selecting outbound crypto protocol', protocols);\n try {\n connection.log.trace('selecting encrypter from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting outbound connection to %p using %s', remotePeerId, encrypter);\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting outbound connection to %p failed', remotePeerId, err);\n throw new CodeError(err.message, codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('outbound selecting muxer %s', protocols);\n try {\n connection.log.trace('selecting stream muxer from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n connection.log('selected %s as muxer protocol', protocol);\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing outbound connection', err);\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('inbound handling muxers %s', protocols);\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n log: connection.log\n });\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing inbound connection', err);\n throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n}\n//# sourceMappingURL=upgrader.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from '@libp2p/crypto/keys';\nimport { contentRoutingSymbol, CodeError, TypedEventEmitter, CustomEvent, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { createEd25519PeerId } from '@libp2p/peer-id-factory';\nimport { PersistentPeerStore } from '@libp2p/peer-store';\nimport { isMultiaddr } from '@multiformats/multiaddr';\nimport { MemoryDatastore } from 'datastore-core/memory';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { DefaultAddressManager } from './address-manager/index.js';\nimport { checkServiceDependencies, defaultComponents } from './components.js';\nimport { connectionGater } from './config/connection-gater.js';\nimport { validateConfig } from './config.js';\nimport { DefaultConnectionManager } from './connection-manager/index.js';\nimport { ConnectionMonitor } from './connection-monitor.js';\nimport { CompoundContentRouting } from './content-routing.js';\nimport { codes } from './errors.js';\nimport { DefaultPeerRouting } from './peer-routing.js';\nimport { RandomWalk } from './random-walk.js';\nimport { DefaultRegistrar } from './registrar.js';\nimport { DefaultTransportManager } from './transport-manager.js';\nimport { DefaultUpgrader } from './upgrader.js';\nimport * as pkg from './version.js';\nexport class Libp2pNode extends TypedEventEmitter {\n peerId;\n peerStore;\n contentRouting;\n peerRouting;\n metrics;\n services;\n logger;\n status;\n components;\n log;\n constructor(init) {\n super();\n this.status = 'stopped';\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new TypedEventEmitter();\n const originalDispatch = events.dispatchEvent.bind(events);\n events.dispatchEvent = (evt) => {\n const internalResult = originalDispatch(evt);\n const externalResult = this.dispatchEvent(new CustomEvent(evt.type, { detail: evt.detail }));\n return internalResult || externalResult;\n };\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, events);\n this.peerId = init.peerId;\n this.logger = init.logger ?? defaultLogger();\n this.log = this.logger.forComponent('libp2p');\n // @ts-expect-error {} may not be of type T\n this.services = {};\n // @ts-expect-error defaultComponents is missing component types added later\n const components = this.components = defaultComponents({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: pkg.name,\n version: pkg.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: connectionGater(init.connectionGater),\n dns: init.dns\n });\n this.peerStore = this.configureComponent('peerStore', new PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }));\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components));\n }\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n };\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo });\n }\n });\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components));\n }\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n muxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout\n });\n // Setup the transport manager\n this.configureComponent('transportManager', new DefaultTransportManager(this.components, init.transportManager));\n // Create the Connection Manager\n this.configureComponent('connectionManager', new DefaultConnectionManager(this.components, init.connectionManager));\n if (init.connectionMonitor?.enabled !== false) {\n // Create the Connection Monitor if not disabled\n this.configureComponent('connectionMonitor', new ConnectionMonitor(this.components, init.connectionMonitor));\n }\n // Create the Registrar\n this.configureComponent('registrar', new DefaultRegistrar(this.components));\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new DefaultAddressManager(this.components, init.addresses));\n // Peer routers\n const peerRouters = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)));\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new DefaultPeerRouting(this.components, {\n routers: peerRouters\n }));\n // Content routers\n const contentRouters = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)));\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new CompoundContentRouting(this.components, {\n routers: contentRouters\n }));\n // Random walk\n this.configureComponent('randomWalk', new RandomWalk(this.components));\n (init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components));\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n });\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)));\n });\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name];\n const service = createService(this.components);\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name);\n continue;\n }\n this.services[name] = service;\n this.configureComponent(name, service);\n if (service[contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name);\n contentRouters.push(service[contentRoutingSymbol]);\n }\n if (service[peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name);\n peerRouters.push(service[peerRoutingSymbol]);\n }\n if (service[peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name);\n service[peerDiscoverySymbol].addEventListener?.('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n }\n }\n }\n // Ensure all services have their required dependencies\n checkServiceDependencies(components);\n }\n configureComponent(name, component) {\n if (component == null) {\n this.log.error('component %s was null or undefined', name);\n }\n // @ts-expect-error cannot assign props\n this.components[name] = component;\n return component;\n }\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start() {\n if (this.status !== 'stopped') {\n return;\n }\n this.status = 'starting';\n this.log('libp2p is starting');\n try {\n await this.components.beforeStart?.();\n await this.components.start();\n await this.components.afterStart?.();\n this.status = 'started';\n this.safeDispatchEvent('start', { detail: this });\n this.log('libp2p has started');\n }\n catch (err) {\n this.log.error('An error occurred starting libp2p', err);\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started';\n await this.stop();\n throw err;\n }\n }\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop() {\n if (this.status !== 'started') {\n return;\n }\n this.log('libp2p is stopping');\n this.status = 'stopping';\n await this.components.beforeStop?.();\n await this.components.stop();\n await this.components.afterStop?.();\n this.status = 'stopped';\n this.safeDispatchEvent('stop', { detail: this });\n this.log('libp2p has stopped');\n }\n getConnections(peerId) {\n return this.components.connectionManager.getConnections(peerId);\n }\n getDialQueue() {\n return this.components.connectionManager.getDialQueue();\n }\n getPeers() {\n const peerSet = new PeerSet();\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer);\n }\n return Array.from(peerSet);\n }\n async dial(peer, options = {}) {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n });\n }\n async dialProtocol(peer, protocols, options = {}) {\n if (protocols == null) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n if (protocols.length === 0) {\n throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n const connection = await this.dial(peer, options);\n return connection.newStream(protocols, options);\n }\n getMultiaddrs() {\n return this.components.addressManager.getAddresses();\n }\n getProtocols() {\n return this.components.registrar.getProtocols();\n }\n async hangUp(peer, options = {}) {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '');\n }\n await this.components.connectionManager.closeConnections(peer, options);\n }\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey(peer, options = {}) {\n this.log('getPublicKey %p', peer);\n if (peer.publicKey != null) {\n return peer.publicKey;\n }\n try {\n const peerInfo = await this.peerStore.get(peer);\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey;\n }\n }\n catch (err) {\n if (err.code !== codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.multihash.digest\n ]);\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options);\n // ensure the returned key is valid\n unmarshalPublicKey(bytes);\n await this.peerStore.patch(peer, {\n publicKey: bytes\n });\n return bytes;\n }\n async handle(protocols, handler, options) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.handle(protocol, handler, options);\n }));\n }\n async unhandle(protocols) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.unhandle(protocol);\n }));\n }\n async register(protocol, topology) {\n return this.components.registrar.register(protocol, topology);\n }\n unregister(id) {\n this.components.registrar.unregister(id);\n }\n async isDialable(multiaddr, options = {}) {\n return this.components.connectionManager.isDialable(multiaddr, options);\n }\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer(evt) {\n const { detail: peer } = evt;\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error(new Error(codes.ERR_DISCOVERED_SELF));\n return;\n }\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err); });\n }\n}\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nexport async function createLibp2pNode(options = {}) {\n const peerId = options.peerId ??= await createEd25519PeerId();\n if (peerId.privateKey == null) {\n throw new CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY');\n }\n options.privateKey ??= await unmarshalPrivateKey(peerId.privateKey);\n return new Libp2pNode(await validateConfig(options));\n}\n//# sourceMappingURL=libp2p.js.map","export const version = '1.9.4';\nexport const name = 'libp2p';\n//# sourceMappingURL=version.js.map","/**\n * The ENR tree for the different fleets.\n * SANDBOX and TEST fleets are for The Waku Network.\n */\nexport const enrTree = {\n SANDBOX: \"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im\",\n TEST: \"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im\"\n};\nexport const DEFAULT_BOOTSTRAP_TAG_NAME = \"bootstrap\";\nexport const DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nexport const DEFAULT_BOOTSTRAP_TAG_TTL = 100_000_000;\nexport const DEFAULT_NODE_REQUIREMENTS = {\n store: 1,\n filter: 2,\n lightPush: 2\n};\n//# sourceMappingURL=constants.js.map","/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nimport * as nodeCrypto from 'crypto';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _8n = BigInt(8);\nconst CURVE = Object.freeze({\n a: _0n,\n b: BigInt(7),\n P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: _1n,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n});\nconst divNearest = (a, b) => (a + b / _2n) / b;\nconst endo = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar(k) {\n const { n } = CURVE;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000');\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n};\nconst fieldLen = 32;\nconst groupLen = 32;\nconst hashLen = 32;\nconst compressedLen = fieldLen + 1;\nconst uncompressedLen = 2 * fieldLen + 1;\nexport { CURVE };\nfunction weierstrass(x) {\n const { a, b } = CURVE;\n const x2 = mod(x * x);\n const x3 = mod(x2 * x);\n return mod(x3 + a * x + b);\n}\nconst USE_ENDOMORPHISM = CURVE.a === _0n;\nclass ShaError extends Error {\n constructor(message) {\n super(message);\n }\n}\nfunction assertJacPoint(other) {\n if (!(other instanceof JacobianPoint))\n throw new TypeError('JacobianPoint expected');\n}\nclass JacobianPoint {\n constructor(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('JacobianPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return JacobianPoint.ZERO;\n return new JacobianPoint(p.x, p.y, _1n);\n }\n static toAffineBatch(points) {\n const toInv = invertBatch(points.map((p) => p.z));\n return points.map((p, i) => p.toAffine(toInv[i]));\n }\n static normalizeZ(points) {\n return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);\n }\n equals(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n return U1 === U2 && S1 === S2;\n }\n negate() {\n return new JacobianPoint(this.x, mod(-this.y), this.z);\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(B * B);\n const x1b = X1 + B;\n const D = mod(_2n * (mod(x1b * x1b) - A - C));\n const E = mod(_3n * A);\n const F = mod(E * E);\n const X3 = mod(F - _2n * D);\n const Y3 = mod(E * (D - X3) - _8n * C);\n const Z3 = mod(_2n * Y1 * Z1);\n return new JacobianPoint(X3, Y3, Z3);\n }\n add(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n if (X2 === _0n || Y2 === _0n)\n return this;\n if (X1 === _0n || Y1 === _0n)\n return other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n const H = mod(U2 - U1);\n const r = mod(S2 - S1);\n if (H === _0n) {\n if (r === _0n) {\n return this.double();\n }\n else {\n return JacobianPoint.ZERO;\n }\n }\n const HH = mod(H * H);\n const HHH = mod(H * HH);\n const V = mod(U1 * HH);\n const X3 = mod(r * r - HHH - _2n * V);\n const Y3 = mod(r * (V - X3) - S1 * HHH);\n const Z3 = mod(Z1 * Z2 * H);\n return new JacobianPoint(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiplyUnsafe(scalar) {\n const P0 = JacobianPoint.ZERO;\n if (typeof scalar === 'bigint' && scalar === _0n)\n return P0;\n let n = normalizeScalar(scalar);\n if (n === _1n)\n return this;\n if (!USE_ENDOMORPHISM) {\n let p = P0;\n let d = this;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = P0;\n let k2p = P0;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n return k1p.add(k2p);\n }\n precomputeWindow(W) {\n const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;\n const points = [];\n let p = this;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n for (let i = 1; i < 2 ** (W - 1); i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n wNAF(n, affinePoint) {\n if (!affinePoint && this.equals(JacobianPoint.BASE))\n affinePoint = Point.BASE;\n const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;\n if (256 % W) {\n throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');\n }\n let precomputes = affinePoint && pointPrecomputes.get(affinePoint);\n if (!precomputes) {\n precomputes = this.precomputeWindow(W);\n if (affinePoint && W !== 1) {\n precomputes = JacobianPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = JacobianPoint.ZERO;\n let f = JacobianPoint.BASE;\n const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);\n const windowSize = 2 ** (W - 1);\n const mask = BigInt(2 ** W - 1);\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n let wbits = Number(n & mask);\n n >>= shiftBy;\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1;\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n return { p, f };\n }\n multiply(scalar, affinePoint) {\n let n = normalizeScalar(scalar);\n let point;\n let fake;\n if (USE_ENDOMORPHISM) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);\n let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);\n k1p = constTimeNegate(k1neg, k1p);\n k2p = constTimeNegate(k2neg, k2p);\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n, affinePoint);\n point = p;\n fake = f;\n }\n return JacobianPoint.normalizeZ([point, fake])[0];\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(JacobianPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const iz1 = invZ;\n const iz2 = mod(iz1 * iz1);\n const iz3 = mod(iz2 * iz1);\n const ax = mod(x * iz2);\n const ay = mod(y * iz3);\n const zz = mod(z * iz1);\n if (is0)\n return Point.ZERO;\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return new Point(ax, ay);\n }\n}\nJacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);\nJacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nconst pointPrecomputes = new WeakMap();\nexport class Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n hasEvenY() {\n return this.y % _2n === _0n;\n }\n static fromCompressedHex(bytes) {\n const isShort = bytes.length === 32;\n const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrass(x);\n let y = sqrtMod(y2);\n const isYOdd = (y & _1n) === _1n;\n if (isShort) {\n if (isYOdd)\n y = mod(-y);\n }\n else {\n const isFirstByteOdd = (bytes[0] & 1) === 1;\n if (isFirstByteOdd !== isYOdd)\n y = mod(-y);\n }\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromUncompressedHex(bytes) {\n const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));\n const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n const len = bytes.length;\n const header = bytes[0];\n if (len === fieldLen)\n return this.fromCompressedHex(bytes);\n if (len === compressedLen && (header === 0x02 || header === 0x03)) {\n return this.fromCompressedHex(bytes);\n }\n if (len === uncompressedLen && header === 0x04)\n return this.fromUncompressedHex(bytes);\n throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normalizePrivateKey(privateKey));\n }\n static fromSignature(msgHash, signature, recovery) {\n const { r, s } = normalizeSignature(signature);\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('Cannot recover: invalid recovery bit');\n const h = truncateHash(ensureBytes(msgHash));\n const { n } = CURVE;\n const radj = recovery === 2 || recovery === 3 ? r + n : r;\n const rinv = invert(radj, n);\n const u1 = mod(-h * rinv, n);\n const u2 = mod(s * rinv, n);\n const prefix = recovery & 1 ? '03' : '02';\n const R = Point.fromHex(prefix + numTo32bStr(radj));\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);\n if (!Q)\n throw new Error('Cannot recover signature: point at infinify');\n Q.assertValidity();\n return Q;\n }\n toRawBytes(isCompressed = false) {\n return hexToBytes(this.toHex(isCompressed));\n }\n toHex(isCompressed = false) {\n const x = numTo32bStr(this.x);\n if (isCompressed) {\n const prefix = this.hasEvenY() ? '02' : '03';\n return `${prefix}${x}`;\n }\n else {\n return `04${x}${numTo32bStr(this.y)}`;\n }\n }\n toHexX() {\n return this.toHex(true).slice(2);\n }\n toRawX() {\n return this.toRawBytes(true).slice(1);\n }\n assertValidity() {\n const msg = 'Point is not on elliptic curve';\n const { x, y } = this;\n if (!isValidFieldElement(x) || !isValidFieldElement(y))\n throw new Error(msg);\n const left = mod(y * y);\n const right = weierstrass(x);\n if (mod(left - right) !== _0n)\n throw new Error(msg);\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(this.x, mod(-this.y));\n }\n double() {\n return JacobianPoint.fromAffine(this).double().toAffine();\n }\n add(other) {\n return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const P = JacobianPoint.fromAffine(this);\n const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);\n const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);\n const sum = aP.add(bQ);\n return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _0n);\nfunction sliceDER(s) {\n return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;\n}\nfunction parseDERInt(data) {\n if (data.length < 2 || data[0] !== 0x02) {\n throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);\n }\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) {\n throw new Error(`Invalid signature integer: wrong length`);\n }\n if (res[0] === 0x00 && res[1] <= 0x7f) {\n throw new Error('Invalid signature integer: trailing length');\n }\n return { data: bytesToNumber(res), left: data.subarray(len + 2) };\n}\nfunction parseDERSignature(data) {\n if (data.length < 2 || data[0] != 0x30) {\n throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);\n }\n if (data[1] !== data.length - 2) {\n throw new Error('Invalid signature: incorrect length');\n }\n const { data: r, left: sBytes } = parseDERInt(data.subarray(2));\n const { data: s, left: rBytesLeft } = parseDERInt(sBytes);\n if (rBytesLeft.length) {\n throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);\n }\n return { r, s };\n}\nexport class Signature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromCompact(hex) {\n const arr = hex instanceof Uint8Array;\n const name = 'Signature.fromCompact';\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`${name}: Expected string or Uint8Array`);\n const str = arr ? bytesToHex(hex) : hex;\n if (str.length !== 128)\n throw new Error(`${name}: Expected 64-byte hex`);\n return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));\n }\n static fromDER(hex) {\n const arr = hex instanceof Uint8Array;\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);\n const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));\n return new Signature(r, s);\n }\n static fromHex(hex) {\n return this.fromDER(hex);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isWithinCurveOrder(r))\n throw new Error('Invalid Signature: r must be 0 < r < n');\n if (!isWithinCurveOrder(s))\n throw new Error('Invalid Signature: s must be 0 < s < n');\n }\n hasHighS() {\n const HALF = CURVE.n >> _1n;\n return this.s > HALF;\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;\n }\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n const sHex = sliceDER(numberToHexUnpadded(this.s));\n const rHex = sliceDER(numberToHexUnpadded(this.r));\n const sHexL = sHex.length / 2;\n const rHexL = rHex.length / 2;\n const sLen = numberToHexUnpadded(sHexL);\n const rLen = numberToHexUnpadded(rHexL);\n const length = numberToHexUnpadded(rHexL + sHexL + 4);\n return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;\n }\n toRawBytes() {\n return this.toDERRawBytes();\n }\n toHex() {\n return this.toDERHex();\n }\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n}\nfunction concatBytes(...arrays) {\n if (!arrays.every((b) => b instanceof Uint8Array))\n throw new Error('Uint8Array list expected');\n if (arrays.length === 1)\n return arrays[0];\n const length = arrays.reduce((a, arr) => a + arr.length, 0);\n const result = new Uint8Array(length);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n result.set(arr, pad);\n pad += arr.length;\n }\n return result;\n}\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\nfunction bytesToHex(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return hex;\n}\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nfunction numTo32bStr(num) {\n if (typeof num !== 'bigint')\n throw new Error('Expected bigint');\n if (!(_0n <= num && num < POW_2_256))\n throw new Error('Expected number 0 <= n < 2^256');\n return num.toString(16).padStart(64, '0');\n}\nfunction numTo32b(num) {\n const b = hexToBytes(numTo32bStr(num));\n if (b.length !== 32)\n throw new Error('Error: expected 32 bytes');\n return b;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToNumber: expected string, got ' + typeof hex);\n }\n return BigInt(`0x${hex}`);\n}\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToBytes: expected string, got ' + typeof hex);\n }\n if (hex.length % 2)\n throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\nfunction bytesToNumber(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction ensureBytes(hex) {\n return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n}\nfunction normalizeScalar(num) {\n if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)\n return BigInt(num);\n if (typeof num === 'bigint' && isWithinCurveOrder(num))\n return num;\n throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');\n}\nfunction mod(a, b = CURVE.P) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\nfunction pow2(x, power) {\n const { P } = CURVE;\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= P;\n }\n return res;\n}\nfunction sqrtMod(x) {\n const { P } = CURVE;\n const _6n = BigInt(6);\n const _11n = BigInt(11);\n const _22n = BigInt(22);\n const _23n = BigInt(23);\n const _44n = BigInt(44);\n const _88n = BigInt(88);\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n) * b3) % P;\n const b9 = (pow2(b6, _3n) * b3) % P;\n const b11 = (pow2(b9, _2n) * b2) % P;\n const b22 = (pow2(b11, _11n) * b11) % P;\n const b44 = (pow2(b22, _22n) * b22) % P;\n const b88 = (pow2(b44, _44n) * b44) % P;\n const b176 = (pow2(b88, _88n) * b88) % P;\n const b220 = (pow2(b176, _44n) * b44) % P;\n const b223 = (pow2(b220, _3n) * b3) % P;\n const t1 = (pow2(b223, _23n) * b22) % P;\n const t2 = (pow2(t1, _6n) * b2) % P;\n const rt = pow2(t2, _2n);\n const xc = (rt * rt) % P;\n if (xc !== x)\n throw new Error('Cannot find square root');\n return rt;\n}\nfunction invert(number, modulo = CURVE.P) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n let a = mod(number, modulo);\n let b = modulo;\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction invertBatch(nums, p = CURVE.P) {\n const scratch = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = acc;\n return mod(acc * num, p);\n }, _1n);\n const inverted = invert(lastMultiplied, p);\n nums.reduceRight((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = mod(acc * scratch[i], p);\n return mod(acc * num, p);\n }, inverted);\n return scratch;\n}\nfunction bits2int_2(bytes) {\n const delta = bytes.length * 8 - groupLen * 8;\n const num = bytesToNumber(bytes);\n return delta > 0 ? num >> BigInt(delta) : num;\n}\nfunction truncateHash(hash, truncateOnly = false) {\n const h = bits2int_2(hash);\n if (truncateOnly)\n return h;\n const { n } = CURVE;\n return h >= n ? h - n : h;\n}\nlet _sha256Sync;\nlet _hmacSha256Sync;\nclass HmacDrbg {\n constructor(hashLen, qByteLen) {\n this.hashLen = hashLen;\n this.qByteLen = qByteLen;\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n this.v = new Uint8Array(hashLen).fill(1);\n this.k = new Uint8Array(hashLen).fill(0);\n this.counter = 0;\n }\n hmac(...values) {\n return utils.hmacSha256(this.k, ...values);\n }\n hmacSync(...values) {\n return _hmacSha256Sync(this.k, ...values);\n }\n checkSync() {\n if (typeof _hmacSha256Sync !== 'function')\n throw new ShaError('hmacSha256Sync needs to be set');\n }\n incr() {\n if (this.counter >= 1000)\n throw new Error('Tried 1,000 k values for sign(), all were invalid');\n this.counter += 1;\n }\n async reseed(seed = new Uint8Array()) {\n this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed);\n this.v = await this.hmac(this.v);\n if (seed.length === 0)\n return;\n this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed);\n this.v = await this.hmac(this.v);\n }\n reseedSync(seed = new Uint8Array()) {\n this.checkSync();\n this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);\n this.v = this.hmacSync(this.v);\n if (seed.length === 0)\n return;\n this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed);\n this.v = this.hmacSync(this.v);\n }\n async generate() {\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = await this.hmac(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n generateSync() {\n this.checkSync();\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = this.hmacSync(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n}\nfunction isWithinCurveOrder(num) {\n return _0n < num && num < CURVE.n;\n}\nfunction isValidFieldElement(num) {\n return _0n < num && num < CURVE.P;\n}\nfunction kmdToSig(kBytes, m, d, lowS = true) {\n const { n } = CURVE;\n const k = truncateHash(kBytes, true);\n if (!isWithinCurveOrder(k))\n return;\n const kinv = invert(k, n);\n const q = Point.BASE.multiply(k);\n const r = mod(q.x, n);\n if (r === _0n)\n return;\n const s = mod(kinv * mod(m + d * r, n), n);\n if (s === _0n)\n return;\n let sig = new Signature(r, s);\n let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);\n if (lowS && sig.hasHighS()) {\n sig = sig.normalizeS();\n recovery ^= 1;\n }\n return { sig, recovery };\n}\nfunction normalizePrivateKey(key) {\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {\n num = BigInt(key);\n }\n else if (typeof key === 'string') {\n if (key.length !== 2 * groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = hexToNumber(key);\n }\n else if (key instanceof Uint8Array) {\n if (key.length !== groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = bytesToNumber(key);\n }\n else {\n throw new TypeError('Expected valid private key');\n }\n if (!isWithinCurveOrder(num))\n throw new Error('Expected private key: 0 < key < n');\n return num;\n}\nfunction normalizePublicKey(publicKey) {\n if (publicKey instanceof Point) {\n publicKey.assertValidity();\n return publicKey;\n }\n else {\n return Point.fromHex(publicKey);\n }\n}\nfunction normalizeSignature(signature) {\n if (signature instanceof Signature) {\n signature.assertValidity();\n return signature;\n }\n try {\n return Signature.fromDER(signature);\n }\n catch (error) {\n return Signature.fromCompact(signature);\n }\n}\nexport function getPublicKey(privateKey, isCompressed = false) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n}\nexport function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {\n return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);\n}\nfunction isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === compressedLen * 2 || len === uncompressedLen * 2;\n if (item instanceof Point)\n return true;\n return false;\n}\nexport function getSharedSecret(privateA, publicB, isCompressed = false) {\n if (isProbPub(privateA))\n throw new TypeError('getSharedSecret: first arg must be private key');\n if (!isProbPub(publicB))\n throw new TypeError('getSharedSecret: second arg must be public key');\n const b = normalizePublicKey(publicB);\n b.assertValidity();\n return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);\n}\nfunction bits2int(bytes) {\n const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;\n return bytesToNumber(slice);\n}\nfunction bits2octets(bytes) {\n const z1 = bits2int(bytes);\n const z2 = mod(z1, CURVE.n);\n return int2octets(z2 < _0n ? z1 : z2);\n}\nfunction int2octets(num) {\n return numTo32b(num);\n}\nfunction initSigArgs(msgHash, privateKey, extraEntropy) {\n if (msgHash == null)\n throw new Error(`sign: expected valid message hash, not \"${msgHash}\"`);\n const h1 = ensureBytes(msgHash);\n const d = normalizePrivateKey(privateKey);\n const seedArgs = [int2octets(d), bits2octets(h1)];\n if (extraEntropy != null) {\n if (extraEntropy === true)\n extraEntropy = utils.randomBytes(fieldLen);\n const e = ensureBytes(extraEntropy);\n if (e.length !== fieldLen)\n throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);\n seedArgs.push(e);\n }\n const seed = concatBytes(...seedArgs);\n const m = bits2int(h1);\n return { seed, m, d };\n}\nfunction finalizeSig(recSig, opts) {\n const { sig, recovery } = recSig;\n const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);\n const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();\n return recovered ? [hashed, recovery] : hashed;\n}\nasync function sign(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n await drbg.reseed(seed);\n let sig;\n while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))\n await drbg.reseed();\n return finalizeSig(sig, opts);\n}\nfunction signSync(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n drbg.reseedSync(seed);\n let sig;\n while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical)))\n drbg.reseedSync();\n return finalizeSig(sig, opts);\n}\nexport { sign, signSync };\nconst vopts = { strict: true };\nexport function verify(signature, msgHash, publicKey, opts = vopts) {\n let sig;\n try {\n sig = normalizeSignature(signature);\n msgHash = ensureBytes(msgHash);\n }\n catch (error) {\n return false;\n }\n const { r, s } = sig;\n if (opts.strict && sig.hasHighS())\n return false;\n const h = truncateHash(msgHash);\n let P;\n try {\n P = normalizePublicKey(publicKey);\n }\n catch (error) {\n return false;\n }\n const { n } = CURVE;\n const sinv = invert(s, n);\n const u1 = mod(h * sinv, n);\n const u2 = mod(r * sinv, n);\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2);\n if (!R)\n return false;\n const v = mod(R.x, n);\n return v === r;\n}\nfunction schnorrChallengeFinalize(ch) {\n return mod(bytesToNumber(ch), CURVE.n);\n}\nclass SchnorrSignature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n if (bytes.length !== 64)\n throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);\n const r = bytesToNumber(bytes.subarray(0, 32));\n const s = bytesToNumber(bytes.subarray(32, 64));\n return new SchnorrSignature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isValidFieldElement(r) || !isWithinCurveOrder(s))\n throw new Error('Invalid signature');\n }\n toHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n toRawBytes() {\n return hexToBytes(this.toHex());\n }\n}\nfunction schnorrGetPublicKey(privateKey) {\n return Point.fromPrivateKey(privateKey).toRawX();\n}\nclass InternalSchnorrSignature {\n constructor(message, privateKey, auxRand = utils.randomBytes()) {\n if (message == null)\n throw new TypeError(`sign: Expected valid message, not \"${message}\"`);\n this.m = ensureBytes(message);\n const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey));\n this.px = x;\n this.d = scalar;\n this.rand = ensureBytes(auxRand);\n if (this.rand.length !== 32)\n throw new TypeError('sign: Expected 32 bytes of aux randomness');\n }\n getScalar(priv) {\n const point = Point.fromPrivateKey(priv);\n const scalar = point.hasEvenY() ? priv : CURVE.n - priv;\n return { point, scalar, x: point.toRawX() };\n }\n initNonce(d, t0h) {\n return numTo32b(d ^ bytesToNumber(t0h));\n }\n finalizeNonce(k0h) {\n const k0 = mod(bytesToNumber(k0h), CURVE.n);\n if (k0 === _0n)\n throw new Error('sign: Creation of signature failed. k is zero');\n const { point: R, x: rx, scalar: k } = this.getScalar(k0);\n return { R, rx, k };\n }\n finalizeSig(R, k, e, d) {\n return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();\n }\n error() {\n throw new Error('sign: Invalid signature produced');\n }\n async calc() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHash;\n const t = this.initNonce(d, await tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!(await schnorrVerify(sig, m, px)))\n this.error();\n return sig;\n }\n calcSync() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHashSync;\n const t = this.initNonce(d, tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!schnorrVerifySync(sig, m, px))\n this.error();\n return sig;\n }\n}\nasync function schnorrSign(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calc();\n}\nfunction schnorrSignSync(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync();\n}\nfunction initSchnorrVerify(signature, message, publicKey) {\n const raw = signature instanceof SchnorrSignature;\n const sig = raw ? signature : SchnorrSignature.fromHex(signature);\n if (raw)\n sig.assertValidity();\n return {\n ...sig,\n m: ensureBytes(message),\n P: normalizePublicKey(publicKey),\n };\n}\nfunction finalizeSchnorrVerify(r, P, s, e) {\n const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));\n if (!R || !R.hasEvenY() || R.x !== r)\n return false;\n return true;\n}\nasync function schnorrVerify(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n return false;\n }\n}\nfunction schnorrVerifySync(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n if (error instanceof ShaError)\n throw error;\n return false;\n }\n}\nexport const schnorr = {\n Signature: SchnorrSignature,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n signSync: schnorrSignSync,\n verifySync: schnorrVerifySync,\n};\nPoint.BASE._setWindowSize(8);\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n aux: 'BIP0340/aux',\n nonce: 'BIP0340/nonce',\n};\nconst TAGGED_HASH_PREFIXES = {};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n isValidPrivateKey(privateKey) {\n try {\n normalizePrivateKey(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n _bigintTo32Bytes: numTo32b,\n _normalizePrivateKey: normalizePrivateKey,\n hashToPrivateKey: (hash) => {\n hash = ensureBytes(hash);\n const minLen = groupLen + 8;\n if (hash.length < minLen || hash.length > 1024) {\n throw new Error(`Expected valid bytes of private key as per FIPS 186`);\n }\n const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;\n return numTo32b(num);\n },\n randomBytes: (bytesLength = 32) => {\n if (crypto.web) {\n return crypto.web.getRandomValues(new Uint8Array(bytesLength));\n }\n else if (crypto.node) {\n const { randomBytes } = crypto.node;\n return Uint8Array.from(randomBytes(bytesLength));\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point === Point.BASE ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_3n);\n return cached;\n },\n sha256: async (...messages) => {\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages));\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHash } = crypto.node;\n const hash = createHash('sha256');\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha256 function\");\n }\n },\n hmacSha256: async (key, ...messages) => {\n if (crypto.web) {\n const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n const message = concatBytes(...messages);\n const buffer = await crypto.web.subtle.sign('HMAC', ckey, message);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHmac } = crypto.node;\n const hash = createHmac('sha256', key);\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have hmac-sha256 function\");\n }\n },\n sha256Sync: undefined,\n hmacSha256Sync: undefined,\n taggedHash: async (tag, ...messages) => {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return utils.sha256(tagP, ...messages);\n },\n taggedHashSync: (tag, ...messages) => {\n if (typeof _sha256Sync !== 'function')\n throw new ShaError('sha256Sync is undefined, you need to set it');\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return _sha256Sync(tagP, ...messages);\n },\n _JacobianPoint: JacobianPoint,\n};\nObject.defineProperties(utils, {\n sha256Sync: {\n configurable: false,\n get() {\n return _sha256Sync;\n },\n set(val) {\n if (!_sha256Sync)\n _sha256Sync = val;\n },\n },\n hmacSha256Sync: {\n configurable: false,\n get() {\n return _hmacSha256Sync;\n },\n set(val) {\n if (!_hmacSha256Sync)\n _hmacSha256Sync = val;\n },\n },\n});\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"@waku/utils/bytes\";\nimport sha3 from \"js-sha3\";\n/**\n * ECDSA Sign a message with the given private key.\n *\n * @param message The message to sign, usually a hash.\n * @param privateKey The ECDSA private key to use to sign the message.\n *\n * @returns The signature and the recovery id concatenated.\n */\nexport async function sign(message, privateKey) {\n const [signature, recoveryId] = await secp.sign(message, privateKey, {\n recovered: true,\n der: false\n });\n return concat([signature, new Uint8Array([recoveryId])], signature.length + 1);\n}\nexport function keccak256(input) {\n return new Uint8Array(sha3.keccak256.arrayBuffer(input));\n}\nexport function compressPublicKey(publicKey) {\n if (publicKey.length === 64) {\n publicKey = concat([new Uint8Array([4]), publicKey], 65);\n }\n const point = secp.Point.fromHex(publicKey);\n return point.toRawBytes(true);\n}\n/**\n * Verify an ECDSA signature.\n */\nexport function verifySignature(signature, message, publicKey) {\n try {\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n return secp.verify(_signature, message, publicKey);\n }\n catch {\n return false;\n }\n}\n//# sourceMappingURL=crypto.js.map","// Maximum encoded size of an ENR\nexport const MAX_RECORD_SIZE = 300;\nexport const ERR_INVALID_ID = \"Invalid record id\";\nexport const ERR_NO_SIGNATURE = \"No valid signature found\";\n// The maximum length of byte size of a multiaddr to encode in the `multiaddr` field\n// The size is a big endian 16-bit unsigned integer\nexport const MULTIADDR_LENGTH_SIZE = 2;\n//# sourceMappingURL=constants.js.map","import { multiaddrFromFields } from \"./multiaddr_from_fields.js\";\nexport function locationMultiaddrFromEnrFields(enr, protocol) {\n switch (protocol) {\n case \"udp\":\n return (locationMultiaddrFromEnrFields(enr, \"udp4\") ||\n locationMultiaddrFromEnrFields(enr, \"udp6\"));\n case \"tcp\":\n return (locationMultiaddrFromEnrFields(enr, \"tcp4\") ||\n locationMultiaddrFromEnrFields(enr, \"tcp6\"));\n }\n const isIpv6 = protocol.endsWith(\"6\");\n const ipVal = enr.get(isIpv6 ? \"ip6\" : \"ip\");\n if (!ipVal)\n return;\n const protoName = protocol.slice(0, 3);\n let protoVal;\n switch (protoName) {\n case \"udp\":\n protoVal = isIpv6 ? enr.get(\"udp6\") : enr.get(\"udp\");\n break;\n case \"tcp\":\n protoVal = isIpv6 ? enr.get(\"tcp6\") : enr.get(\"tcp\");\n break;\n default:\n return;\n }\n if (!protoVal)\n return;\n return multiaddrFromFields(isIpv6 ? \"ip6\" : \"ip4\", protoName, ipVal, protoVal);\n}\n//# sourceMappingURL=get_multiaddr.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { convertToString } from \"@multiformats/multiaddr/convert\";\nexport function multiaddrFromFields(ipFamily, protocol, ipBytes, protocolBytes) {\n let ma = multiaddr(\"/\" + ipFamily + \"/\" + convertToString(ipFamily, ipBytes));\n ma = ma.encapsulate(multiaddr(\"/\" + protocol + \"/\" + convertToString(protocol, protocolBytes)));\n return ma;\n}\n//# sourceMappingURL=multiaddr_from_fields.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { MULTIADDR_LENGTH_SIZE } from \"./constants.js\";\nexport function decodeMultiaddrs(bytes) {\n const multiaddrs = [];\n let index = 0;\n while (index < bytes.length) {\n const sizeDataView = new DataView(bytes.buffer, index, MULTIADDR_LENGTH_SIZE);\n const size = sizeDataView.getUint16(0);\n index += MULTIADDR_LENGTH_SIZE;\n const multiaddrBytes = bytes.slice(index, index + size);\n index += size;\n multiaddrs.push(multiaddr(multiaddrBytes));\n }\n return multiaddrs;\n}\nexport function encodeMultiaddrs(multiaddrs) {\n const totalLength = multiaddrs.reduce((acc, ma) => acc + MULTIADDR_LENGTH_SIZE + ma.bytes.length, 0);\n const bytes = new Uint8Array(totalLength);\n const dataView = new DataView(bytes.buffer);\n let index = 0;\n multiaddrs.forEach((multiaddr) => {\n if (multiaddr.getPeerId())\n throw new Error(\"`multiaddr` field MUST not contain peer id\");\n // Prepend the size of the next entry\n dataView.setUint16(index, multiaddr.bytes.length);\n index += MULTIADDR_LENGTH_SIZE;\n bytes.set(multiaddr.bytes, index);\n index += multiaddr.bytes.length;\n });\n return bytes;\n}\n//# sourceMappingURL=multiaddrs_codec.js.map","export function encodeWaku2(protocols) {\n let byte = 0;\n if (protocols.lightPush)\n byte += 1;\n byte = byte << 1;\n if (protocols.filter)\n byte += 1;\n byte = byte << 1;\n if (protocols.store)\n byte += 1;\n byte = byte << 1;\n if (protocols.relay)\n byte += 1;\n return byte;\n}\nexport function decodeWaku2(byte) {\n const waku2 = {\n relay: false,\n store: false,\n filter: false,\n lightPush: false\n };\n if (byte % 2)\n waku2.relay = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.store = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.filter = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.lightPush = true;\n return waku2;\n}\n//# sourceMappingURL=waku2_codec.js.map","import { convertToBytes, convertToString } from \"@multiformats/multiaddr/convert\";\nimport { decodeRelayShard } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { decodeMultiaddrs, encodeMultiaddrs } from \"./multiaddrs_codec.js\";\nimport { decodeWaku2, encodeWaku2 } from \"./waku2_codec.js\";\nexport class RawEnr extends Map {\n seq;\n signature;\n constructor(kvs = {}, seq = BigInt(1), signature) {\n super(Object.entries(kvs));\n this.seq = seq;\n this.signature = signature;\n }\n set(k, v) {\n this.signature = undefined;\n this.seq++;\n return super.set(k, v);\n }\n get id() {\n const id = this.get(\"id\");\n if (!id)\n throw new Error(\"id not found.\");\n return bytesToUtf8(id);\n }\n get publicKey() {\n switch (this.id) {\n case \"v4\":\n return this.get(\"secp256k1\");\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n get rs() {\n const rs = this.get(\"rs\");\n if (!rs)\n return undefined;\n return decodeRelayShard(rs);\n }\n get rsv() {\n const rsv = this.get(\"rsv\");\n if (!rsv)\n return undefined;\n return decodeRelayShard(rsv);\n }\n get ip() {\n return getStringValue(this, \"ip\", \"ip4\");\n }\n set ip(ip) {\n setStringValue(this, \"ip\", \"ip4\", ip);\n }\n get tcp() {\n return getNumberAsStringValue(this, \"tcp\", \"tcp\");\n }\n set tcp(port) {\n setNumberAsStringValue(this, \"tcp\", \"tcp\", port);\n }\n get udp() {\n return getNumberAsStringValue(this, \"udp\", \"udp\");\n }\n set udp(port) {\n setNumberAsStringValue(this, \"udp\", \"udp\", port);\n }\n get ip6() {\n return getStringValue(this, \"ip6\", \"ip6\");\n }\n set ip6(ip) {\n setStringValue(this, \"ip6\", \"ip6\", ip);\n }\n get tcp6() {\n return getNumberAsStringValue(this, \"tcp6\", \"tcp\");\n }\n set tcp6(port) {\n setNumberAsStringValue(this, \"tcp6\", \"tcp\", port);\n }\n get udp6() {\n return getNumberAsStringValue(this, \"udp6\", \"udp\");\n }\n set udp6(port) {\n setNumberAsStringValue(this, \"udp6\", \"udp\", port);\n }\n /**\n * Get the `multiaddrs` field from ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.getLocationMultiaddr } should be preferred.\n *\n * The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.\n */\n get multiaddrs() {\n const raw = this.get(\"multiaddrs\");\n if (raw)\n return decodeMultiaddrs(raw);\n return;\n }\n /**\n * Set the `multiaddrs` field on the ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.setLocationMultiaddr } should be preferred.\n * The multiaddresses stored in this field must be location multiaddresses,\n * ie, without a peer id.\n */\n set multiaddrs(multiaddrs) {\n deleteUndefined(this, \"multiaddrs\", multiaddrs, encodeMultiaddrs);\n }\n /**\n * Get the `waku2` field from ENR.\n */\n get waku2() {\n const raw = this.get(\"waku2\");\n if (raw)\n return decodeWaku2(raw[0]);\n return;\n }\n /**\n * Set the `waku2` field on the ENR.\n */\n set waku2(waku2) {\n deleteUndefined(this, \"waku2\", waku2, (w) => new Uint8Array([encodeWaku2(w)]));\n }\n}\nfunction getStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return convertToString(proto, raw);\n}\nfunction getNumberAsStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return Number(convertToString(proto, raw));\n}\nfunction setStringValue(map, key, proto, value) {\n deleteUndefined(map, key, value, convertToBytes.bind({}, proto));\n}\nfunction setNumberAsStringValue(map, key, proto, value) {\n setStringValue(map, key, proto, value?.toString(10));\n}\nfunction deleteUndefined(map, key, value, transform) {\n if (value !== undefined) {\n map.set(key, transform(value));\n }\n else {\n map.delete(key);\n }\n}\n//# sourceMappingURL=raw_enr.js.map","import * as secp from \"@noble/secp256k1\";\nimport { bytesToHex } from \"@waku/utils/bytes\";\nimport { keccak256 } from \"./crypto.js\";\nexport async function sign(privKey, msg) {\n return secp.sign(keccak256(msg), privKey, {\n der: false\n });\n}\nexport function nodeId(pubKey) {\n const publicKey = secp.Point.fromHex(pubKey);\n const uncompressedPubkey = publicKey.toRawBytes(false);\n return bytesToHex(keccak256(uncompressedPubkey.slice(1)));\n}\n//# sourceMappingURL=v4.js.map","import { Logger } from \"@waku/utils\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { keccak256, verifySignature } from \"./crypto.js\";\nimport { locationMultiaddrFromEnrFields } from \"./get_multiaddr.js\";\nimport { createPeerIdFromPublicKey } from \"./peer_id.js\";\nimport { RawEnr } from \"./raw_enr.js\";\nimport * as v4 from \"./v4.js\";\nconst log = new Logger(\"enr\");\nexport var TransportProtocol;\n(function (TransportProtocol) {\n TransportProtocol[\"TCP\"] = \"tcp\";\n TransportProtocol[\"UDP\"] = \"udp\";\n})(TransportProtocol || (TransportProtocol = {}));\nexport var TransportProtocolPerIpVersion;\n(function (TransportProtocolPerIpVersion) {\n TransportProtocolPerIpVersion[\"TCP4\"] = \"tcp4\";\n TransportProtocolPerIpVersion[\"UDP4\"] = \"udp4\";\n TransportProtocolPerIpVersion[\"TCP6\"] = \"tcp6\";\n TransportProtocolPerIpVersion[\"UDP6\"] = \"udp6\";\n})(TransportProtocolPerIpVersion || (TransportProtocolPerIpVersion = {}));\nexport class ENR extends RawEnr {\n static RECORD_PREFIX = \"enr:\";\n peerId;\n static async create(kvs = {}, seq = BigInt(1), signature) {\n const enr = new ENR(kvs, seq, signature);\n try {\n const publicKey = enr.publicKey;\n if (publicKey) {\n enr.peerId = await createPeerIdFromPublicKey(publicKey);\n }\n }\n catch (e) {\n log.error(\"Could not calculate peer id for ENR\", e);\n }\n return enr;\n }\n get nodeId() {\n switch (this.id) {\n case \"v4\":\n return this.publicKey ? v4.nodeId(this.publicKey) : undefined;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n getLocationMultiaddr = locationMultiaddrFromEnrFields.bind({}, this);\n get shardInfo() {\n if (this.rs && this.rsv) {\n log.warn(\"ENR contains both `rs` and `rsv` fields.\");\n }\n return this.rs || this.rsv;\n }\n setLocationMultiaddr(multiaddr) {\n const protoNames = multiaddr.protoNames();\n if (protoNames.length !== 2 &&\n protoNames[1] !== \"udp\" &&\n protoNames[1] !== \"tcp\") {\n throw new Error(\"Invalid multiaddr\");\n }\n const tuples = multiaddr.tuples();\n if (!tuples[0][1] || !tuples[1][1]) {\n throw new Error(\"Invalid multiaddr\");\n }\n // IPv4\n if (tuples[0][0] === 4) {\n this.set(\"ip\", tuples[0][1]);\n this.set(protoNames[1], tuples[1][1]);\n }\n else {\n this.set(\"ip6\", tuples[0][1]);\n this.set(protoNames[1] + \"6\", tuples[1][1]);\n }\n }\n getAllLocationMultiaddrs() {\n const multiaddrs = [];\n for (const protocol of Object.values(TransportProtocolPerIpVersion)) {\n const ma = this.getLocationMultiaddr(protocol);\n if (ma)\n multiaddrs.push(ma);\n }\n const _multiaddrs = this.multiaddrs ?? [];\n return multiaddrs.concat(_multiaddrs).map((ma) => {\n if (this.peerId) {\n return ma.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n return ma;\n });\n }\n get peerInfo() {\n const id = this.peerId;\n if (!id)\n return;\n return {\n id,\n multiaddrs: this.getAllLocationMultiaddrs()\n };\n }\n /**\n * Returns the full multiaddr from the ENR fields matching the provided\n * `protocol` parameter.\n * To return full multiaddrs from the `multiaddrs` ENR field,\n * use { @link ENR.getFullMultiaddrs }.\n *\n * @param protocol\n */\n getFullMultiaddr(protocol) {\n if (this.peerId) {\n const locationMultiaddr = this.getLocationMultiaddr(protocol);\n if (locationMultiaddr) {\n return locationMultiaddr.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n }\n return;\n }\n /**\n * Returns the full multiaddrs from the `multiaddrs` ENR field.\n */\n getFullMultiaddrs() {\n if (this.peerId && this.multiaddrs) {\n const peerId = this.peerId;\n return this.multiaddrs.map((ma) => {\n return ma.encapsulate(`/p2p/${peerId.toString()}`);\n });\n }\n return [];\n }\n verify(data, signature) {\n if (!this.get(\"id\") || this.id !== \"v4\") {\n throw new Error(ERR_INVALID_ID);\n }\n if (!this.publicKey) {\n throw new Error(\"Failed to verify ENR: No public key\");\n }\n return verifySignature(signature, keccak256(data), this.publicKey);\n }\n async sign(data, privateKey) {\n switch (this.id) {\n case \"v4\":\n this.signature = await v4.sign(privateKey, data);\n break;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n return this.signature;\n }\n}\n//# sourceMappingURL=enr.js.map","import { unmarshalPrivateKey, unmarshalPublicKey } from \"@libp2p/crypto/keys\";\nimport { supportedKeys } from \"@libp2p/crypto/keys\";\nimport { peerIdFromKeys } from \"@libp2p/peer-id\";\nexport function createPeerIdFromPublicKey(publicKey) {\n const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);\n return peerIdFromKeys(_publicKey.bytes, undefined);\n}\nexport function getPublicKeyFromPeerId(peerId) {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n if (!peerId.publicKey) {\n throw new Error(\"Public key not present on peer id\");\n }\n return unmarshalPublicKey(peerId.publicKey).marshal();\n}\n// Only used in tests\nexport async function getPrivateKeyFromPeerId(peerId) {\n if (peerId.type !== \"secp256k1\") {\n throw new Error(\"Unsupported peer id type\");\n }\n if (!peerId.privateKey) {\n throw new Error(\"Private key not present on peer id\");\n }\n const privateKey = await unmarshalPrivateKey(peerId.privateKey);\n return privateKey.marshal();\n}\n//# sourceMappingURL=peer_id.js.map","\"use strict\";\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\nconst LogLevels = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\nimport { version } from \"./_version\";\nlet _globalLogger = null;\nfunction _checkNormalize() {\n try {\n const missing = [];\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n }\n ;\n }\n catch (error) {\n missing.push(form);\n }\n });\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\");\n }\n }\n catch (error) {\n return error.message;\n }\n return null;\n}\nconst _normalizeError = _checkNormalize();\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[\"DEBUG\"] = \"DEBUG\";\n LogLevel[\"INFO\"] = \"INFO\";\n LogLevel[\"WARNING\"] = \"WARNING\";\n LogLevel[\"ERROR\"] = \"ERROR\";\n LogLevel[\"OFF\"] = \"OFF\";\n})(LogLevel || (LogLevel = {}));\nexport var ErrorCode;\n(function (ErrorCode) {\n ///////////////////\n // Generic Errors\n // Unknown Error\n ErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n // Not Implemented\n ErrorCode[\"NOT_IMPLEMENTED\"] = \"NOT_IMPLEMENTED\";\n // Unsupported Operation\n // - operation\n ErrorCode[\"UNSUPPORTED_OPERATION\"] = \"UNSUPPORTED_OPERATION\";\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n ErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n // Some sort of bad response from the server\n ErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n // Timeout\n ErrorCode[\"TIMEOUT\"] = \"TIMEOUT\";\n ///////////////////\n // Operational Errors\n // Buffer Overrun\n ErrorCode[\"BUFFER_OVERRUN\"] = \"BUFFER_OVERRUN\";\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n ErrorCode[\"NUMERIC_FAULT\"] = \"NUMERIC_FAULT\";\n ///////////////////\n // Argument Errors\n // Missing new operator to an object\n // - name: The name of the class\n ErrorCode[\"MISSING_NEW\"] = \"MISSING_NEW\";\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n ErrorCode[\"INVALID_ARGUMENT\"] = \"INVALID_ARGUMENT\";\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"MISSING_ARGUMENT\"] = \"MISSING_ARGUMENT\";\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"UNEXPECTED_ARGUMENT\"] = \"UNEXPECTED_ARGUMENT\";\n ///////////////////\n // Blockchain Errors\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n ErrorCode[\"CALL_EXCEPTION\"] = \"CALL_EXCEPTION\";\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n ErrorCode[\"INSUFFICIENT_FUNDS\"] = \"INSUFFICIENT_FUNDS\";\n // Nonce has already been used\n // - transaction: the transaction attempted\n ErrorCode[\"NONCE_EXPIRED\"] = \"NONCE_EXPIRED\";\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n ErrorCode[\"REPLACEMENT_UNDERPRICED\"] = \"REPLACEMENT_UNDERPRICED\";\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n ErrorCode[\"UNPREDICTABLE_GAS_LIMIT\"] = \"UNPREDICTABLE_GAS_LIMIT\";\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n ErrorCode[\"TRANSACTION_REPLACED\"] = \"TRANSACTION_REPLACED\";\n ///////////////////\n // Interaction Errors\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ErrorCode[\"ACTION_REJECTED\"] = \"ACTION_REJECTED\";\n})(ErrorCode || (ErrorCode = {}));\n;\nconst HEX = \"0123456789abcdef\";\nexport class Logger {\n constructor(version) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n _log(logLevel, args) {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) {\n return;\n }\n console.log.apply(console, args);\n }\n debug(...args) {\n this._log(Logger.levels.DEBUG, args);\n }\n info(...args) {\n this._log(Logger.levels.INFO, args);\n }\n warn(...args) {\n this._log(Logger.levels.WARNING, args);\n }\n makeError(message, code, params) {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, {});\n }\n if (!code) {\n code = Logger.errors.UNKNOWN_ERROR;\n }\n if (!params) {\n params = {};\n }\n const messageDetails = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n }\n else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n }\n catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${code}`);\n messageDetails.push(`version=${this.version}`);\n const reason = message;\n let url = \"\";\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n switch (fault) {\n case \"overflow\":\n case \"underflow\":\n case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\":\n case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n // @TODO: Any??\n const error = new Error(message);\n error.reason = reason;\n error.code = code;\n Object.keys(params).forEach(function (key) {\n error[key] = params[key];\n });\n return error;\n }\n throwError(message, code, params) {\n throw this.makeError(message, code, params);\n }\n throwArgumentError(message, name, value) {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n assert(condition, message, code, params) {\n if (!!condition) {\n return;\n }\n this.throwError(message, code, params);\n }\n assertArgument(condition, message, name, value) {\n if (!!condition) {\n return;\n }\n this.throwArgumentError(message, name, value);\n }\n checkNormalize(message) {\n if (message == null) {\n message = \"platform missing String.prototype.normalize\";\n }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n checkSafeUint53(value, message) {\n if (typeof (value) !== \"number\") {\n return;\n }\n if (message == null) {\n message = \"value not safe\";\n }\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n checkArgumentCount(count, expectedCount, message) {\n if (message) {\n message = \": \" + message;\n }\n else {\n message = \"\";\n }\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n checkNew(target, kind) {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n checkAbstract(target, kind) {\n if (target === kind) {\n this.throwError(\"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: \"new\" });\n }\n else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n static globalLogger() {\n if (!_globalLogger) {\n _globalLogger = new Logger(version);\n }\n return _globalLogger;\n }\n static setCensorship(censorship, permanent) {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n if (_permanentCensorErrors) {\n if (!censorship) {\n return;\n }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n static setLogLevel(logLevel) {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n static from(version) {\n return new Logger(version);\n }\n}\nLogger.errors = ErrorCode;\nLogger.levels = LogLevel;\n//# sourceMappingURL=index.js.map","export const version = \"logger/5.7.0\";\n//# sourceMappingURL=_version.js.map","export const version = \"bytes/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n///////////////////////////////\nfunction isHexable(value) {\n return !!(value.toHexString);\n}\nfunction addSlice(array) {\n if (array.slice) {\n return array;\n }\n array.slice = function () {\n const args = Array.prototype.slice.call(arguments);\n return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));\n };\n return array;\n}\nexport function isBytesLike(value) {\n return ((isHexString(value) && !(value.length % 2)) || isBytes(value));\n}\nfunction isInteger(value) {\n return (typeof (value) === \"number\" && value == value && (value % 1) === 0);\n}\nexport function isBytes(value) {\n if (value == null) {\n return false;\n }\n if (value.constructor === Uint8Array) {\n return true;\n }\n if (typeof (value) === \"string\") {\n return false;\n }\n if (!isInteger(value.length) || value.length < 0) {\n return false;\n }\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (!isInteger(v) || v < 0 || v >= 256) {\n return false;\n }\n }\n return true;\n}\nexport function arrayify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid arrayify value\");\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value = parseInt(String(value / 256));\n }\n if (result.length === 0) {\n result.push(0);\n }\n return addSlice(new Uint8Array(result));\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n value = value.toHexString();\n }\n if (isHexString(value)) {\n let hex = value.substring(2);\n if (hex.length % 2) {\n if (options.hexPad === \"left\") {\n hex = \"0\" + hex;\n }\n else if (options.hexPad === \"right\") {\n hex += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n const result = [];\n for (let i = 0; i < hex.length; i += 2) {\n result.push(parseInt(hex.substring(i, i + 2), 16));\n }\n return addSlice(new Uint8Array(result));\n }\n if (isBytes(value)) {\n return addSlice(new Uint8Array(value));\n }\n return logger.throwArgumentError(\"invalid arrayify value\", \"value\", value);\n}\nexport function concat(items) {\n const objects = items.map(item => arrayify(item));\n const length = objects.reduce((accum, item) => (accum + item.length), 0);\n const result = new Uint8Array(length);\n objects.reduce((offset, object) => {\n result.set(object, offset);\n return offset + object.length;\n }, 0);\n return addSlice(result);\n}\nexport function stripZeros(value) {\n let result = arrayify(value);\n if (result.length === 0) {\n return result;\n }\n // Find the first non-zero entry\n let start = 0;\n while (start < result.length && result[start] === 0) {\n start++;\n }\n // If we started with zeros, strip them\n if (start) {\n result = result.slice(start);\n }\n return result;\n}\nexport function zeroPad(value, length) {\n value = arrayify(value);\n if (value.length > length) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[0]);\n }\n const result = new Uint8Array(length);\n result.set(value, length - value.length);\n return addSlice(result);\n}\nexport function isHexString(value, length) {\n if (typeof (value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false;\n }\n if (length && value.length !== 2 + 2 * length) {\n return false;\n }\n return true;\n}\nconst HexCharacters = \"0123456789abcdef\";\nexport function hexlify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid hexlify value\");\n let hex = \"\";\n while (value) {\n hex = HexCharacters[value & 0xf] + hex;\n value = Math.floor(value / 16);\n }\n if (hex.length) {\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n return \"0x\" + hex;\n }\n return \"0x00\";\n }\n if (typeof (value) === \"bigint\") {\n value = value.toString(16);\n if (value.length % 2) {\n return (\"0x0\" + value);\n }\n return \"0x\" + value;\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n return value.toHexString();\n }\n if (isHexString(value)) {\n if (value.length % 2) {\n if (options.hexPad === \"left\") {\n value = \"0x0\" + value.substring(2);\n }\n else if (options.hexPad === \"right\") {\n value += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n return value.toLowerCase();\n }\n if (isBytes(value)) {\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n let v = value[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n }\n return logger.throwArgumentError(\"invalid hexlify value\", \"value\", value);\n}\n/*\nfunction unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {\n if (typeof(value) === \"string\" && value.length % 2 && value.substring(0, 2) === \"0x\") {\n return \"0x0\" + value.substring(2);\n }\n return value;\n}\n*/\nexport function hexDataLength(data) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n return null;\n }\n return (data.length - 2) / 2;\n}\nexport function hexDataSlice(data, offset, endOffset) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n logger.throwArgumentError(\"invalid hexData\", \"value\", data);\n }\n offset = 2 + 2 * offset;\n if (endOffset != null) {\n return \"0x\" + data.substring(offset, 2 + 2 * endOffset);\n }\n return \"0x\" + data.substring(offset);\n}\nexport function hexConcat(items) {\n let result = \"0x\";\n items.forEach((item) => {\n result += hexlify(item).substring(2);\n });\n return result;\n}\nexport function hexValue(value) {\n const trimmed = hexStripZeros(hexlify(value, { hexPad: \"left\" }));\n if (trimmed === \"0x\") {\n return \"0x0\";\n }\n return trimmed;\n}\nexport function hexStripZeros(value) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n value = value.substring(2);\n let offset = 0;\n while (offset < value.length && value[offset] === \"0\") {\n offset++;\n }\n return \"0x\" + value.substring(offset);\n}\nexport function hexZeroPad(value, length) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n else if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n if (value.length > 2 * length + 2) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[1]);\n }\n while (value.length < 2 * length + 2) {\n value = \"0x0\" + value.substring(2);\n }\n return value;\n}\nexport function splitSignature(signature) {\n const result = {\n r: \"0x\",\n s: \"0x\",\n _vs: \"0x\",\n recoveryParam: 0,\n v: 0,\n yParityAndS: \"0x\",\n compact: \"0x\"\n };\n if (isBytesLike(signature)) {\n let bytes = arrayify(signature);\n // Get the r, s and v\n if (bytes.length === 64) {\n // EIP-2098; pull the v from the top bit of s and clear it\n result.v = 27 + (bytes[32] >> 7);\n bytes[32] &= 0x7f;\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n }\n else if (bytes.length === 65) {\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n result.v = bytes[64];\n }\n else {\n logger.throwArgumentError(\"invalid signature string\", \"signature\", signature);\n }\n // Allow a recid to be used as the v\n if (result.v < 27) {\n if (result.v === 0 || result.v === 1) {\n result.v += 27;\n }\n else {\n logger.throwArgumentError(\"signature invalid v byte\", \"signature\", signature);\n }\n }\n // Compute recoveryParam from v\n result.recoveryParam = 1 - (result.v % 2);\n // Compute _vs from recoveryParam and s\n if (result.recoveryParam) {\n bytes[32] |= 0x80;\n }\n result._vs = hexlify(bytes.slice(32, 64));\n }\n else {\n result.r = signature.r;\n result.s = signature.s;\n result.v = signature.v;\n result.recoveryParam = signature.recoveryParam;\n result._vs = signature._vs;\n // If the _vs is available, use it to populate missing s, v and recoveryParam\n // and verify non-missing s, v and recoveryParam\n if (result._vs != null) {\n const vs = zeroPad(arrayify(result._vs), 32);\n result._vs = hexlify(vs);\n // Set or check the recid\n const recoveryParam = ((vs[0] >= 128) ? 1 : 0);\n if (result.recoveryParam == null) {\n result.recoveryParam = recoveryParam;\n }\n else if (result.recoveryParam !== recoveryParam) {\n logger.throwArgumentError(\"signature recoveryParam mismatch _vs\", \"signature\", signature);\n }\n // Set or check the s\n vs[0] &= 0x7f;\n const s = hexlify(vs);\n if (result.s == null) {\n result.s = s;\n }\n else if (result.s !== s) {\n logger.throwArgumentError(\"signature v mismatch _vs\", \"signature\", signature);\n }\n }\n // Use recid and v to populate each other\n if (result.recoveryParam == null) {\n if (result.v == null) {\n logger.throwArgumentError(\"signature missing v and recoveryParam\", \"signature\", signature);\n }\n else if (result.v === 0 || result.v === 1) {\n result.recoveryParam = result.v;\n }\n else {\n result.recoveryParam = 1 - (result.v % 2);\n }\n }\n else {\n if (result.v == null) {\n result.v = 27 + result.recoveryParam;\n }\n else {\n const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));\n if (result.recoveryParam !== recId) {\n logger.throwArgumentError(\"signature recoveryParam mismatch v\", \"signature\", signature);\n }\n }\n }\n if (result.r == null || !isHexString(result.r)) {\n logger.throwArgumentError(\"signature missing or invalid r\", \"signature\", signature);\n }\n else {\n result.r = hexZeroPad(result.r, 32);\n }\n if (result.s == null || !isHexString(result.s)) {\n logger.throwArgumentError(\"signature missing or invalid s\", \"signature\", signature);\n }\n else {\n result.s = hexZeroPad(result.s, 32);\n }\n const vs = arrayify(result.s);\n if (vs[0] >= 128) {\n logger.throwArgumentError(\"signature s out of range\", \"signature\", signature);\n }\n if (result.recoveryParam) {\n vs[0] |= 0x80;\n }\n const _vs = hexlify(vs);\n if (result._vs) {\n if (!isHexString(result._vs)) {\n logger.throwArgumentError(\"signature invalid _vs\", \"signature\", signature);\n }\n result._vs = hexZeroPad(result._vs, 32);\n }\n // Set or check the _vs\n if (result._vs == null) {\n result._vs = _vs;\n }\n else if (result._vs !== _vs) {\n logger.throwArgumentError(\"signature _vs mismatch v and s\", \"signature\", signature);\n }\n }\n result.yParityAndS = result._vs;\n result.compact = result.r + result.yParityAndS.substring(2);\n return result;\n}\nexport function joinSignature(signature) {\n signature = splitSignature(signature);\n return hexlify(concat([\n signature.r,\n signature.s,\n (signature.recoveryParam ? \"0x1c\" : \"0x1b\")\n ]));\n}\n//# sourceMappingURL=index.js.map","export const version = \"rlp/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\n//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { arrayify, hexlify, isBytesLike } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nfunction arrayifyInteger(value) {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\nfunction unarrayifyInteger(data, offset, length) {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\nfunction _encode(object) {\n if (Array.isArray(object)) {\n let payload = [];\n object.forEach(function (child) {\n payload = payload.concat(_encode(child));\n });\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length);\n return payload;\n }\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n return length.concat(payload);\n }\n if (!isBytesLike(object)) {\n logger.throwArgumentError(\"RLP object must be BytesLike\", \"object\", object);\n }\n const data = Array.prototype.slice.call(arrayify(object));\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n }\n else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n return length.concat(data);\n}\nexport function encode(object) {\n return hexlify(_encode(object));\n}\nfunction _decodeChildren(data, offset, childOffset, length) {\n const result = [];\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n result.push(decoded.result);\n childOffset += decoded.consumed;\n if (childOffset > offset + 1 + length) {\n logger.throwError(\"child data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n }\n return { consumed: (1 + length), result: result };\n}\n// returns { consumed: number, result: Object }\nfunction _decode(data, offset) {\n if (data.length === 0) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data short segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data long segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n }\n else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1, length);\n }\n else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result };\n }\n else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result };\n }\n return { consumed: 1, result: hexlify(data[offset]) };\n}\nexport function decode(data) {\n const bytes = arrayify(data);\n const decoded = _decode(bytes, 0);\n if (decoded.consumed !== bytes.length) {\n logger.throwArgumentError(\"invalid rlp data\", \"data\", data);\n }\n return decoded.result;\n}\n//# sourceMappingURL=index.js.map","import * as RLP from \"@ethersproject/rlp\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToHex, bytesToUtf8, hexToBytes } from \"@waku/utils/bytes\";\nimport { fromString } from \"uint8arrays/from-string\";\nimport { ENR } from \"./enr.js\";\nconst log = new Logger(\"enr:decoder\");\nexport class EnrDecoder {\n static fromString(encoded) {\n if (!encoded.startsWith(ENR.RECORD_PREFIX)) {\n throw new Error(`\"string encoded ENR must start with '${ENR.RECORD_PREFIX}'`);\n }\n return EnrDecoder.fromRLP(fromString(encoded.slice(4), \"base64url\"));\n }\n static fromRLP(encoded) {\n const decoded = RLP.decode(encoded).map(hexToBytes);\n return fromValues(decoded);\n }\n}\nasync function fromValues(values) {\n const { signature, seq, kvs } = checkValues(values);\n const obj = {};\n for (let i = 0; i < kvs.length; i += 2) {\n try {\n obj[bytesToUtf8(kvs[i])] = kvs[i + 1];\n }\n catch (e) {\n log.error(\"Failed to decode ENR key to UTF-8, skipping it\", kvs[i], e);\n }\n }\n const _seq = decodeSeq(seq);\n const enr = await ENR.create(obj, _seq, signature);\n checkSignature(seq, kvs, enr, signature);\n return enr;\n}\nfunction decodeSeq(seq) {\n // If seq is an empty array, translate as value 0\n if (!seq.length)\n return BigInt(0);\n return BigInt(\"0x\" + bytesToHex(seq));\n}\nfunction checkValues(values) {\n if (!Array.isArray(values)) {\n throw new Error(\"Decoded ENR must be an array\");\n }\n if (values.length % 2 !== 0) {\n throw new Error(\"Decoded ENR must have an even number of elements\");\n }\n const [signature, seq, ...kvs] = values;\n if (!signature || Array.isArray(signature)) {\n throw new Error(\"Decoded ENR invalid signature: must be a byte array\");\n }\n if (!seq || Array.isArray(seq)) {\n throw new Error(\"Decoded ENR invalid sequence number: must be a byte array\");\n }\n return { signature, seq, kvs };\n}\nfunction checkSignature(seq, kvs, enr, signature) {\n const rlpEncodedBytes = hexToBytes(RLP.encode([seq, ...kvs]));\n if (!enr.verify(rlpEncodedBytes, signature)) {\n throw new Error(\"Unable to verify ENR signature\");\n }\n}\n//# sourceMappingURL=decoder.js.map","const v4Regex = /^(\\d{1,3}\\.){3,3}\\d{1,3}$/\nconst v4Size = 4\nconst v6Regex = /^(::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i\nconst v6Size = 16\n\nexport const v4 = {\n name: 'v4',\n size: v4Size,\n isFormat: ip => v4Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n buff = buff || new Uint8Array(offset + v4Size)\n const max = ip.length\n let n = 0\n for (let i = 0; i < max;) {\n const c = ip.charCodeAt(i++)\n if (c === 46) { // \".\"\n buff[offset++] = n\n n = 0\n } else {\n n = n * 10 + (c - 48)\n }\n }\n buff[offset] = n\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`\n }\n}\n\nexport const v6 = {\n name: 'v6',\n size: v6Size,\n isFormat: ip => ip.length > 0 && v6Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n let end = offset + v6Size\n let fill = -1\n let hexN = 0\n let decN = 0\n let prevColon = true\n let useDec = false\n buff = buff || new Uint8Array(offset + v6Size)\n // Note: This algorithm needs to check if the offset\n // could exceed the buffer boundaries as it supports\n // non-standard compliant encodings that may go beyond\n // the boundary limits. if (offset < end) checks should\n // not be necessary...\n for (let i = 0; i < ip.length; i++) {\n let c = ip.charCodeAt(i)\n if (c === 58) { // :\n if (prevColon) {\n if (fill !== -1) {\n // Not Standard! (standard doesn't allow multiple ::)\n // We need to treat\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (offset < end) {\n // :: in the middle\n fill = offset\n }\n } else {\n // : ends the previous number\n if (useDec === true) {\n // Non-standard! (ipv4 should be at end only)\n // A ipv4 address should not be found anywhere else but at\n // the end. This codec also support putting characters\n // after the ipv4 address..\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n hexN = 0\n decN = 0\n }\n prevColon = true\n useDec = false\n } else if (c === 46) { // . indicates IPV4 notation\n if (offset < end) buff[offset] = decN\n offset++\n decN = 0\n hexN = 0\n prevColon = false\n useDec = true\n } else {\n prevColon = false\n if (c >= 97) {\n c -= 87 // a-f ... 97~102 -87 => 10~15\n } else if (c >= 65) {\n c -= 55 // A-F ... 65~70 -55 => 10~15\n } else {\n c -= 48 // 0-9 ... starting from charCode 48\n decN = decN * 10 + c\n }\n // We don't know yet if its a dec or hex number\n hexN = (hexN << 4) + c\n }\n }\n if (prevColon === false) {\n // Commiting last number\n if (useDec === true) {\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n } else if (fill === 0) {\n // Not Standard! (standard doesn't allow multiple ::)\n // This means that a : was found at the start AND end which means the\n // end needs to be treated as 0 entry...\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (fill !== -1) {\n // Non-standard! (standard doens't allow multiple ::)\n // Here we find that there has been a :: somewhere in the middle\n // and the end. To treat the end with priority we need to move all\n // written data two bytes to the right.\n offset += 2\n for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) {\n buff[i] = buff[i - 2]\n }\n buff[fill] = 0\n buff[fill + 1] = 0\n fill = offset\n }\n if (fill !== offset && fill !== -1) {\n // Move the written numbers to the end while filling the everything\n // \"fill\" to the bytes with zeros.\n if (offset > end - 2) {\n // Non Standard support, when the cursor exceeds bounds.\n offset = end - 2\n }\n while (end > fill) {\n buff[--end] = offset < end && offset > fill ? buff[--offset] : 0\n }\n } else {\n // Fill the rest with zeros\n while (offset < end) {\n buff[offset++] = 0\n }\n }\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n let result = ''\n for (let i = 0; i < v6Size; i += 2) {\n if (i !== 0) {\n result += ':'\n }\n result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16)\n }\n return result\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n}\n\nexport const name = 'ip'\nexport function sizeOf (ip) {\n if (v4.isFormat(ip)) return v4.size\n if (v6.isFormat(ip)) return v6.size\n throw Error(`Invalid ip address: ${ip}`)\n}\n\nexport function familyOf (string) {\n return sizeOf(string) === v4.size ? 1 : 2\n}\n\nexport function encode (ip, buff, offset) {\n offset = ~~offset\n const size = sizeOf(ip)\n if (typeof buff === 'function') {\n buff = buff(offset + size)\n }\n if (size === v4.size) {\n return v4.encode(ip, buff, offset)\n }\n return v6.encode(ip, buff, offset)\n}\n\nexport function decode (buff, offset, length) {\n offset = ~~offset\n length = length || (buff.length - offset)\n if (length === v4.size) {\n return v4.decode(buff, offset, length)\n }\n if (length === v6.size) {\n return v6.decode(buff, offset, length)\n }\n throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`)\n}\n","export function toString (type) {\n switch (type) {\n case 1: return 'A'\n case 10: return 'NULL'\n case 28: return 'AAAA'\n case 18: return 'AFSDB'\n case 42: return 'APL'\n case 257: return 'CAA'\n case 60: return 'CDNSKEY'\n case 59: return 'CDS'\n case 37: return 'CERT'\n case 5: return 'CNAME'\n case 49: return 'DHCID'\n case 32769: return 'DLV'\n case 39: return 'DNAME'\n case 48: return 'DNSKEY'\n case 43: return 'DS'\n case 55: return 'HIP'\n case 13: return 'HINFO'\n case 45: return 'IPSECKEY'\n case 25: return 'KEY'\n case 36: return 'KX'\n case 29: return 'LOC'\n case 15: return 'MX'\n case 35: return 'NAPTR'\n case 2: return 'NS'\n case 47: return 'NSEC'\n case 50: return 'NSEC3'\n case 51: return 'NSEC3PARAM'\n case 12: return 'PTR'\n case 46: return 'RRSIG'\n case 17: return 'RP'\n case 24: return 'SIG'\n case 6: return 'SOA'\n case 99: return 'SPF'\n case 33: return 'SRV'\n case 44: return 'SSHFP'\n case 32768: return 'TA'\n case 249: return 'TKEY'\n case 52: return 'TLSA'\n case 250: return 'TSIG'\n case 16: return 'TXT'\n case 252: return 'AXFR'\n case 251: return 'IXFR'\n case 41: return 'OPT'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + type\n}\n\nexport function toType (name) {\n switch (name.toUpperCase()) {\n case 'A': return 1\n case 'NULL': return 10\n case 'AAAA': return 28\n case 'AFSDB': return 18\n case 'APL': return 42\n case 'CAA': return 257\n case 'CDNSKEY': return 60\n case 'CDS': return 59\n case 'CERT': return 37\n case 'CNAME': return 5\n case 'DHCID': return 49\n case 'DLV': return 32769\n case 'DNAME': return 39\n case 'DNSKEY': return 48\n case 'DS': return 43\n case 'HIP': return 55\n case 'HINFO': return 13\n case 'IPSECKEY': return 45\n case 'KEY': return 25\n case 'KX': return 36\n case 'LOC': return 29\n case 'MX': return 15\n case 'NAPTR': return 35\n case 'NS': return 2\n case 'NSEC': return 47\n case 'NSEC3': return 50\n case 'NSEC3PARAM': return 51\n case 'PTR': return 12\n case 'RRSIG': return 46\n case 'RP': return 17\n case 'SIG': return 24\n case 'SOA': return 6\n case 'SPF': return 99\n case 'SRV': return 33\n case 'SSHFP': return 44\n case 'TA': return 32768\n case 'TKEY': return 249\n case 'TLSA': return 52\n case 'TSIG': return 250\n case 'TXT': return 16\n case 'AXFR': return 252\n case 'IXFR': return 251\n case 'OPT': return 41\n case 'ANY': return 255\n case '*': return 255\n }\n if (name.toUpperCase().startsWith('UNKNOWN_')) return parseInt(name.slice(8))\n return 0\n}\n","/*\n * Traditional DNS header RCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml\n */\n\nexport function toString (rcode) {\n switch (rcode) {\n case 0: return 'NOERROR'\n case 1: return 'FORMERR'\n case 2: return 'SERVFAIL'\n case 3: return 'NXDOMAIN'\n case 4: return 'NOTIMP'\n case 5: return 'REFUSED'\n case 6: return 'YXDOMAIN'\n case 7: return 'YXRRSET'\n case 8: return 'NXRRSET'\n case 9: return 'NOTAUTH'\n case 10: return 'NOTZONE'\n case 11: return 'RCODE_11'\n case 12: return 'RCODE_12'\n case 13: return 'RCODE_13'\n case 14: return 'RCODE_14'\n case 15: return 'RCODE_15'\n }\n return 'RCODE_' + rcode\n}\n\nexport function toRcode (code) {\n switch (code.toUpperCase()) {\n case 'NOERROR': return 0\n case 'FORMERR': return 1\n case 'SERVFAIL': return 2\n case 'NXDOMAIN': return 3\n case 'NOTIMP': return 4\n case 'REFUSED': return 5\n case 'YXDOMAIN': return 6\n case 'YXRRSET': return 7\n case 'NXRRSET': return 8\n case 'NOTAUTH': return 9\n case 'NOTZONE': return 10\n case 'RCODE_11': return 11\n case 'RCODE_12': return 12\n case 'RCODE_13': return 13\n case 'RCODE_14': return 14\n case 'RCODE_15': return 15\n }\n return 0\n}\n","/*\n * Traditional DNS header OPCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5\n */\n\nexport function toString (opcode) {\n switch (opcode) {\n case 0: return 'QUERY'\n case 1: return 'IQUERY'\n case 2: return 'STATUS'\n case 3: return 'OPCODE_3'\n case 4: return 'NOTIFY'\n case 5: return 'UPDATE'\n case 6: return 'OPCODE_6'\n case 7: return 'OPCODE_7'\n case 8: return 'OPCODE_8'\n case 9: return 'OPCODE_9'\n case 10: return 'OPCODE_10'\n case 11: return 'OPCODE_11'\n case 12: return 'OPCODE_12'\n case 13: return 'OPCODE_13'\n case 14: return 'OPCODE_14'\n case 15: return 'OPCODE_15'\n }\n return 'OPCODE_' + opcode\n}\n\nexport function toOpcode (code) {\n switch (code.toUpperCase()) {\n case 'QUERY': return 0\n case 'IQUERY': return 1\n case 'STATUS': return 2\n case 'OPCODE_3': return 3\n case 'NOTIFY': return 4\n case 'UPDATE': return 5\n case 'OPCODE_6': return 6\n case 'OPCODE_7': return 7\n case 'OPCODE_8': return 8\n case 'OPCODE_9': return 9\n case 'OPCODE_10': return 10\n case 'OPCODE_11': return 11\n case 'OPCODE_12': return 12\n case 'OPCODE_13': return 13\n case 'OPCODE_14': return 14\n case 'OPCODE_15': return 15\n }\n return 0\n}\n","export function toString (klass) {\n switch (klass) {\n case 1: return 'IN'\n case 2: return 'CS'\n case 3: return 'CH'\n case 4: return 'HS'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + klass\n}\n\nexport function toClass (name) {\n switch (name.toUpperCase()) {\n case 'IN': return 1\n case 'CS': return 2\n case 'CH': return 3\n case 'HS': return 4\n case 'ANY': return 255\n }\n return 0\n}\n","export function toString (type) {\n switch (type) {\n // list at\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11\n case 1: return 'LLQ'\n case 2: return 'UL'\n case 3: return 'NSID'\n case 5: return 'DAU'\n case 6: return 'DHU'\n case 7: return 'N3U'\n case 8: return 'CLIENT_SUBNET'\n case 9: return 'EXPIRE'\n case 10: return 'COOKIE'\n case 11: return 'TCP_KEEPALIVE'\n case 12: return 'PADDING'\n case 13: return 'CHAIN'\n case 14: return 'KEY_TAG'\n case 26946: return 'DEVICEID'\n }\n if (type < 0) {\n return null\n }\n return `OPTION_${type}`\n}\n\nexport function toCode (name) {\n if (typeof name === 'number') {\n return name\n }\n if (!name) {\n return -1\n }\n switch (name.toUpperCase()) {\n case 'OPTION_0': return 0\n case 'LLQ': return 1\n case 'UL': return 2\n case 'NSID': return 3\n case 'OPTION_4': return 4\n case 'DAU': return 5\n case 'DHU': return 6\n case 'N3U': return 7\n case 'CLIENT_SUBNET': return 8\n case 'EXPIRE': return 9\n case 'COOKIE': return 10\n case 'TCP_KEEPALIVE': return 11\n case 'PADDING': return 12\n case 'CHAIN': return 13\n case 'KEY_TAG': return 14\n case 'DEVICEID': return 26946\n case 'OPTION_65535': return 65535\n }\n const m = name.match(/_(\\d+)$/)\n if (m) {\n return parseInt(m[1], 10)\n }\n return -1\n}\n","const SURROGATE_A = 0b1101100000000000\nconst SURROGATE_B = 0b1101110000000000\n\nexport const name = 'utf8'\n\nexport function encodingLength (str) {\n let len = 0\n const strLen = str.length\n for (let i = 0; i < strLen; i += 1) {\n const code = str.charCodeAt(i)\n if (code <= 0x7F) {\n len += 1\n } else if (code <= 0x07FF) {\n len += 2\n } else if ((code & 0xF800) !== SURROGATE_A) {\n len += 3\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n len += 3\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n len += 3\n } else {\n i = next\n len += 4\n }\n }\n }\n }\n return len\n}\n\nexport function encode (str, buf, offset) {\n const strLen = str.length\n if (offset === undefined || offset === null) {\n offset = 0\n }\n if (buf === undefined) {\n buf = new Uint8Array(encodingLength(str) + offset)\n }\n let off = offset\n for (let i = 0; i < strLen; i += 1) {\n let code = str.charCodeAt(i)\n if (code <= 0x7F) {\n buf[off++] = code\n } else if (code <= 0x07FF) {\n buf[off++] = 0b11000000 | ((code & 0b11111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b00000111111)\n } else if ((code & 0xF800) !== SURROGATE_A) {\n buf[off++] = 0b11100000 | ((code & 0b1111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b0000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b0000000000111111)\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n // Incorrectly started surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n // Incorrect surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n i = next\n code = 0b000010000000000000000 |\n ((code & 0b1111111111) << 10) |\n (nextCode & 0b1111111111)\n buf[off++] = 0b11110000 | ((code & 0b111000000000000000000) >> 18)\n buf[off++] = 0b10000000 | ((code & 0b000111111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b000000000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b000000000000000111111)\n }\n }\n }\n }\n encode.bytes = off - offset\n return buf\n}\nencode.bytes = 0\n\nexport function decode (buf, start, end) {\n let result = ''\n if (start === undefined || start === null) {\n start = 0\n }\n if (end === undefined || end === null) {\n end = buf.length\n }\n for (let offset = start; offset < end;) {\n const code = buf[offset++]\n let num\n if (code <= 128) {\n num = code\n } else if (code > 191 && code < 224) {\n num = ((code & 0b11111) << 6) | (buf[offset++] & 0b111111)\n } else if (code > 239 && code < 365) {\n num = (\n ((code & 0b111) << 18) |\n ((buf[offset++] & 0b111111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n ) - 0x10000\n const numA = SURROGATE_A | ((num >> 10) & 0b1111111111)\n result += String.fromCharCode(numA)\n num = SURROGATE_B | (num & 0b1111111111)\n } else {\n num = ((code & 0b1111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n }\n result += String.fromCharCode(num)\n }\n decode.bytes = end - start\n return result\n}\ndecode.bytes = 0\n","import * as utf8 from 'utf8-codec'\n\nexport const isU8Arr = input => input instanceof Uint8Array\n\nexport function bytelength (input) {\n return typeof input === 'string' ? utf8.encodingLength(input) : input.byteLength\n}\n\nexport function from (input) {\n if (input instanceof Uint8Array) {\n return input\n }\n if (Array.isArray(input)) {\n return new Uint8Array(input)\n }\n return utf8.encode(input)\n}\n\nexport function write (arr, str, start) {\n if (typeof str !== 'string') {\n throw new Error('unknown input type')\n }\n utf8.encode(str, arr, start)\n return utf8.encode.bytes\n}\n\nexport function toHex (buf, start, end) {\n let result = ''\n for (let offset = start; offset < end;) {\n const num = buf[offset++]\n const str = num.toString(16)\n result += (str.length === 1) ? '0' + str : str\n }\n return result\n}\n\nconst P_24 = Math.pow(2, 24)\nconst P_16 = Math.pow(2, 16)\nconst P_8 = Math.pow(2, 8)\nexport const readUInt32BE = (buf, offset) => buf[offset] * P_24 +\n buf[offset + 1] * P_16 +\n buf[offset + 2] * P_8 +\n buf[offset + 3]\n\nexport const readUInt16BE = (buf, offset) => (buf[offset] << 8) | buf[offset + 1]\nexport const writeUInt32BE = (buf, value, offset) => {\n value = +value\n buf[offset + 3] = value\n value = value >>> 8\n buf[offset + 2] = value\n value = value >>> 8\n buf[offset + 1] = value\n value = value >>> 8\n buf[offset] = value\n return offset + 4\n}\nexport const writeUInt16BE = (buf, value, offset) => {\n buf[offset] = value >> 8\n buf[offset + 1] = value & 0xFF\n return offset + 2\n}\n\nexport function copy (source, target, targetStart, sourceStart, sourceEnd) {\n if (targetStart < 0) {\n sourceStart -= targetStart\n targetStart = 0\n }\n\n if (sourceStart < 0) {\n sourceStart = 0\n }\n\n if (sourceEnd < 0) {\n return new Uint8Array(0)\n }\n\n if (targetStart >= target.length || sourceStart >= sourceEnd) {\n return 0\n }\n\n return _copyActual(source, target, targetStart, sourceStart, sourceEnd)\n}\n\nfunction _copyActual (source, target, targetStart, sourceStart, sourceEnd) {\n if (sourceEnd - sourceStart > target.length - targetStart) {\n sourceEnd = sourceStart + target.length - targetStart\n }\n\n let nb = sourceEnd - sourceStart\n const sourceLen = source.length - sourceStart\n if (nb > sourceLen) {\n nb = sourceLen\n }\n\n if (sourceStart !== 0 || sourceEnd < source.length) {\n source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb)\n }\n\n target.set(source, targetStart)\n\n return nb\n}\n","import * as ip from '@leichtgewicht/ip-codec'\nimport * as types from './types.mjs'\nimport * as rcodes from './rcodes.mjs'\nimport * as opcodes from './opcodes.mjs'\nimport * as classes from './classes.mjs'\nimport * as optioncodes from './optioncodes.mjs'\nimport * as b from './buffer_utils.mjs'\nimport { decode as toUtf8 } from 'utf8-codec'\n\nconst QUERY_FLAG = 0\nconst RESPONSE_FLAG = 1 << 15\nconst FLUSH_MASK = 1 << 15\nconst NOT_FLUSH_MASK = ~FLUSH_MASK\nconst QU_MASK = 1 << 15\nconst NOT_QU_MASK = ~QU_MASK\n\nfunction codec ({ bytes = 0, encode, decode, encodingLength }) {\n encode.bytes = bytes\n decode.bytes = bytes\n return {\n encode,\n decode,\n encodingLength: encodingLength || (() => bytes)\n }\n}\n\nexport const name = codec({\n encode (str, buf, offset) {\n if (!buf) buf = new Uint8Array(name.encodingLength(str))\n if (!offset) offset = 0\n const oldOffset = offset\n\n // strip leading and trailing .\n const n = str.replace(/^\\.|\\.$/gm, '')\n if (n.length) {\n const list = n.split('.')\n\n for (let i = 0; i < list.length; i++) {\n const len = b.write(buf, list[i], offset + 1)\n buf[offset] = len\n offset += len + 1\n }\n }\n\n buf[offset++] = 0\n\n name.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const list = []\n let oldOffset = offset\n let totalLength = 0\n let consumedBytes = 0\n let jumped = false\n\n while (true) {\n if (offset >= buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const len = buf[offset++]\n consumedBytes += jumped ? 0 : 1\n\n if (len === 0) {\n break\n } else if ((len & 0xc0) === 0) {\n if (offset + len > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n totalLength += len + 1\n if (totalLength > 254) {\n throw new Error('Cannot decode name (name too long)')\n }\n list.push(toUtf8(buf, offset, offset + len))\n offset += len\n consumedBytes += jumped ? 0 : len\n } else if ((len & 0xc0) === 0xc0) {\n if (offset + 1 > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const jumpOffset = b.readUInt16BE(buf, offset - 1) - 0xc000\n if (jumpOffset >= oldOffset) {\n // Allow only pointers to prior data. RFC 1035, section 4.1.4 states:\n // \"[...] an entire domain name or a list of labels at the end of a domain name\n // is replaced with a pointer to a prior occurance (sic) of the same name.\"\n throw new Error('Cannot decode name (bad pointer)')\n }\n offset = jumpOffset\n oldOffset = jumpOffset\n consumedBytes += jumped ? 0 : 1\n jumped = true\n } else {\n throw new Error('Cannot decode name (bad label)')\n }\n }\n\n name.decode.bytes = consumedBytes\n return list.length === 0 ? '.' : list.join('.')\n },\n encodingLength (n) {\n if (n === '.' || n === '..') return 1\n return b.bytelength(n.replace(/^\\.|\\.$/gm, '')) + 2\n }\n})\n\nconst string = codec({\n encode (s, buf, offset) {\n if (!buf) buf = new Uint8Array(string.encodingLength(s))\n if (!offset) offset = 0\n\n const len = b.write(buf, s, offset + 1)\n buf[offset] = len\n string.encode.bytes = len + 1\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = buf[offset]\n const s = toUtf8(buf, offset + 1, offset + 1 + len)\n string.decode.bytes = len + 1\n return s\n },\n encodingLength (s) {\n return b.bytelength(s) + 1\n }\n})\n\nconst header = codec({\n bytes: 12,\n encode (h, buf, offset) {\n if (!buf) buf = new Uint8Array(header.encodingLength(h))\n if (!offset) offset = 0\n\n const flags = (h.flags || 0) & 32767\n const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG\n\n b.writeUInt16BE(buf, h.id || 0, offset)\n b.writeUInt16BE(buf, flags | type, offset + 2)\n b.writeUInt16BE(buf, h.questions.length, offset + 4)\n b.writeUInt16BE(buf, h.answers.length, offset + 6)\n b.writeUInt16BE(buf, h.authorities.length, offset + 8)\n b.writeUInt16BE(buf, h.additionals.length, offset + 10)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n if (buf.length < 12) throw new Error('Header must be 12 bytes')\n const flags = b.readUInt16BE(buf, offset + 2)\n\n return {\n id: b.readUInt16BE(buf, offset),\n type: flags & RESPONSE_FLAG ? 'response' : 'query',\n flags: flags & 32767,\n flag_qr: ((flags >> 15) & 0x1) === 1,\n opcode: opcodes.toString((flags >> 11) & 0xf),\n flag_aa: ((flags >> 10) & 0x1) === 1,\n flag_tc: ((flags >> 9) & 0x1) === 1,\n flag_rd: ((flags >> 8) & 0x1) === 1,\n flag_ra: ((flags >> 7) & 0x1) === 1,\n flag_z: ((flags >> 6) & 0x1) === 1,\n flag_ad: ((flags >> 5) & 0x1) === 1,\n flag_cd: ((flags >> 4) & 0x1) === 1,\n rcode: rcodes.toString(flags & 0xf),\n questions: new Array(b.readUInt16BE(buf, offset + 4)),\n answers: new Array(b.readUInt16BE(buf, offset + 6)),\n authorities: new Array(b.readUInt16BE(buf, offset + 8)),\n additionals: new Array(b.readUInt16BE(buf, offset + 10))\n }\n },\n encodingLength () {\n return 12\n }\n})\n\nconst runknown = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(runknown.encodingLength(data))\n if (!offset) offset = 0\n\n const dLen = data.length\n b.writeUInt16BE(buf, dLen, offset)\n b.copy(data, buf, offset + 2, 0, dLen)\n\n runknown.encode.bytes = dLen + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const data = buf.slice(offset + 2, offset + 2 + len)\n runknown.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return data.length + 2\n }\n})\n\nconst rns = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rns.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rns.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const dd = name.decode(buf, offset + 2)\n\n rns.decode.bytes = len + 2\n return dd\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsoa = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsoa.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n name.encode(data.mname, buf, offset)\n offset += name.encode.bytes\n name.encode(data.rname, buf, offset)\n offset += name.encode.bytes\n b.writeUInt32BE(buf, data.serial || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.refresh || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.retry || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.expire || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.minimum || 0, offset)\n offset += 4\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rsoa.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.rname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.serial = b.readUInt32BE(buf, offset)\n offset += 4\n data.refresh = b.readUInt32BE(buf, offset)\n offset += 4\n data.retry = b.readUInt32BE(buf, offset)\n offset += 4\n data.expire = b.readUInt32BE(buf, offset)\n offset += 4\n data.minimum = b.readUInt32BE(buf, offset)\n offset += 4\n\n rsoa.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)\n }\n})\n\nconst rtxt = codec({\n encode (data, buf, offset) {\n if (!Array.isArray(data)) data = [data]\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] === 'string') {\n data[i] = b.from(data[i])\n }\n if (!b.isU8Arr(data[i])) {\n throw new Error('Must be a Buffer')\n }\n }\n\n if (!buf) buf = new Uint8Array(rtxt.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n\n data.forEach(function (d) {\n buf[offset++] = d.length\n b.copy(d, buf, offset, 0, d.length)\n offset += d.length\n })\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rtxt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n let remaining = b.readUInt16BE(buf, offset)\n offset += 2\n\n const data = []\n while (remaining > 0) {\n const len = buf[offset++]\n --remaining\n if (remaining < len) {\n throw new Error('Buffer overflow')\n }\n data.push(buf.slice(offset, offset + len))\n offset += len\n remaining -= len\n }\n\n rtxt.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!Array.isArray(data)) data = [data]\n let length = 2\n data.forEach(function (buf) {\n if (typeof buf === 'string') {\n length += b.bytelength(buf) + 1\n } else {\n length += buf.length + 1\n }\n })\n return length\n }\n})\n\nconst rnull = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rnull.encodingLength(data))\n if (!offset) offset = 0\n\n if (typeof data === 'string') data = b.from(data)\n if (!data) data = new Uint8Array(0)\n\n const oldOffset = offset\n offset += 2\n\n const len = data.length\n b.copy(data, buf, offset, 0, len)\n offset += len\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rnull.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n const len = b.readUInt16BE(buf, offset)\n\n offset += 2\n\n const data = buf.slice(offset, offset + len)\n offset += len\n\n rnull.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!data) return 2\n return (b.isU8Arr(data) ? data.length : b.bytelength(data)) + 2\n }\n})\n\nconst rhinfo = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rhinfo.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n string.encode(data.cpu, buf, offset)\n offset += string.encode.bytes\n string.encode(data.os, buf, offset)\n offset += string.encode.bytes\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rhinfo.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.cpu = string.decode(buf, offset)\n offset += string.decode.bytes\n data.os = string.decode(buf, offset)\n offset += string.decode.bytes\n rhinfo.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2\n }\n})\n\nconst rptr = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rptr.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rptr.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const data = name.decode(buf, offset + 2)\n rptr.decode.bytes = name.decode.bytes + 2\n return data\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsrv = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsrv.encodingLength(data))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, data.priority || 0, offset + 2)\n b.writeUInt16BE(buf, data.weight || 0, offset + 4)\n b.writeUInt16BE(buf, data.port || 0, offset + 6)\n name.encode(data.target, buf, offset + 8)\n\n const len = name.encode.bytes + 6\n b.writeUInt16BE(buf, len, offset)\n\n rsrv.encode.bytes = len + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n\n const data = {}\n data.priority = b.readUInt16BE(buf, offset + 2)\n data.weight = b.readUInt16BE(buf, offset + 4)\n data.port = b.readUInt16BE(buf, offset + 6)\n data.target = name.decode(buf, offset + 8)\n\n rsrv.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return 8 + name.encodingLength(data.target)\n }\n})\n\nconst rcaa = codec({\n encode (data, buf, offset) {\n const len = rcaa.encodingLength(data)\n\n if (!buf) buf = new Uint8Array(rcaa.encodingLength(data))\n if (!offset) offset = 0\n\n if (data.issuerCritical) {\n data.flags = rcaa.ISSUER_CRITICAL\n }\n\n b.writeUInt16BE(buf, len - 2, offset)\n offset += 2\n buf[offset] = data.flags || 0\n offset += 1\n string.encode(data.tag, buf, offset)\n offset += string.encode.bytes\n b.write(buf, data.value, offset)\n offset += b.bytelength(data.value)\n\n rcaa.encode.bytes = len\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n\n const oldOffset = offset\n const data = {}\n data.flags = buf[offset]\n offset += 1\n data.tag = string.decode(buf, offset)\n offset += string.decode.bytes\n data.value = toUtf8(buf, offset, oldOffset + len)\n\n data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)\n\n rcaa.decode.bytes = len + 2\n\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2\n }\n})\n\nrcaa.ISSUER_CRITICAL = 1 << 7\n\nconst rmx = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rmx.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n b.writeUInt16BE(buf, data.preference || 0, offset)\n offset += 2\n name.encode(data.exchange, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rmx.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.preference = b.readUInt16BE(buf, offset)\n offset += 2\n data.exchange = name.decode(buf, offset)\n offset += name.decode.bytes\n\n rmx.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 4 + name.encodingLength(data.exchange)\n }\n})\n\nconst ra = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(ra.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 4, offset)\n offset += 2\n ip.v4.encode(host, buf, offset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v4.decode(buf, offset)\n return host\n },\n bytes: 6\n})\n\nconst raaaa = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(raaaa.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 16, offset)\n offset += 2\n ip.v6.encode(host, buf, offset)\n raaaa.encode.bytes = 18\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v6.decode(buf, offset)\n raaaa.decode.bytes = 18\n return host\n },\n bytes: 18\n})\n\nconst alloc = size => new Uint8Array(size)\n\nconst roption = codec({\n encode (option, buf, offset) {\n if (!buf) buf = new Uint8Array(roption.encodingLength(option))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const code = optioncodes.toCode(option.code)\n b.writeUInt16BE(buf, code, offset)\n offset += 2\n if (option.data) {\n b.writeUInt16BE(buf, option.data.length, offset)\n offset += 2\n b.copy(option.data, buf, offset)\n offset += option.data.length\n } else {\n switch (code) {\n // case 3: NSID. No encode makes sense.\n // case 5,6,7: Not implementable\n case 8: // ECS\n {\n // note: do IP math before calling\n const spl = option.sourcePrefixLength || 0\n const fam = option.family || ip.familyOf(option.ip, alloc)\n const ipBuf = ip.encode(option.ip, alloc)\n const ipLen = Math.ceil(spl / 8)\n b.writeUInt16BE(buf, ipLen + 4, offset)\n offset += 2\n b.writeUInt16BE(buf, fam, offset)\n offset += 2\n buf[offset++] = spl\n buf[offset++] = option.scopePrefixLength || 0\n\n b.copy(ipBuf, buf, offset, 0, ipLen)\n offset += ipLen\n }\n break\n // case 9: EXPIRE (experimental)\n // case 10: COOKIE. No encode makes sense.\n case 11: // KEEP-ALIVE\n if (option.timeout) {\n b.writeUInt16BE(buf, 2, offset)\n offset += 2\n b.writeUInt16BE(buf, option.timeout, offset)\n offset += 2\n } else {\n b.writeUInt16BE(buf, 0, offset)\n offset += 2\n }\n break\n case 12: // PADDING\n {\n const len = option.length || 0\n b.writeUInt16BE(buf, len, offset)\n offset += 2\n buf.fill(0, offset, offset + len)\n offset += len\n }\n break\n // case 13: CHAIN. Experimental.\n case 14: // KEY-TAG\n {\n const tagsLen = option.tags.length * 2\n b.writeUInt16BE(buf, tagsLen, offset)\n offset += 2\n for (const tag of option.tags) {\n b.writeUInt16BE(buf, tag, offset)\n offset += 2\n }\n }\n break\n default:\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n }\n\n roption.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const option = {}\n option.code = b.readUInt16BE(buf, offset)\n option.type = optioncodes.toString(option.code)\n offset += 2\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n option.data = buf.slice(offset, offset + len)\n switch (option.code) {\n // case 3: NSID. No decode makes sense.\n case 8: // ECS\n option.family = b.readUInt16BE(buf, offset)\n offset += 2\n option.sourcePrefixLength = buf[offset++]\n option.scopePrefixLength = buf[offset++]\n {\n const padded = new Uint8Array((option.family === 1) ? 4 : 16)\n b.copy(buf, padded, 0, offset, offset + len - 4)\n option.ip = ip.decode(padded)\n }\n break\n // case 12: Padding. No decode makes sense.\n case 11: // KEEP-ALIVE\n if (len > 0) {\n option.timeout = b.readUInt16BE(buf, offset)\n offset += 2\n }\n break\n case 14:\n option.tags = []\n for (let i = 0; i < len; i += 2) {\n option.tags.push(b.readUInt16BE(buf, offset))\n offset += 2\n }\n // don't worry about default. caller will use data if desired\n }\n\n roption.decode.bytes = len + 4\n return option\n },\n encodingLength (option) {\n if (option.data) {\n return option.data.length + 4\n }\n const code = optioncodes.toCode(option.code)\n switch (code) {\n case 8: // ECS\n {\n const spl = option.sourcePrefixLength || 0\n return Math.ceil(spl / 8) + 8\n }\n case 11: // KEEP-ALIVE\n return (typeof option.timeout === 'number') ? 6 : 4\n case 12: // PADDING\n return option.length + 4\n case 14: // KEY-TAG\n return 4 + (option.tags.length * 2)\n }\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n})\n\nconst ropt = codec({\n encode (options, buf, offset) {\n if (!buf) buf = new Uint8Array(ropt.encodingLength(options))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const rdlen = encodingLengthList(options, roption)\n b.writeUInt16BE(buf, rdlen, offset)\n offset = encodeList(options, roption, buf, offset + 2)\n\n ropt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const options = []\n let rdlen = b.readUInt16BE(buf, offset)\n offset += 2\n let o = 0\n while (rdlen > 0) {\n options[o++] = roption.decode(buf, offset)\n offset += roption.decode.bytes\n rdlen -= roption.decode.bytes\n }\n ropt.decode.bytes = offset - oldOffset\n return options\n },\n encodingLength (options) {\n return 2 + encodingLengthList(options || [], roption)\n }\n})\n\nconst rdnskey = codec({\n encode (key, buf, offset) {\n if (!buf) buf = new Uint8Array(rdnskey.encodingLength(key))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const keydata = key.key\n if (!b.isU8Arr(keydata)) {\n throw new Error('Key must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, key.flags, offset)\n offset += 2\n buf[offset] = rdnskey.PROTOCOL_DNSSEC\n offset += 1\n buf[offset] = key.algorithm\n offset += 1\n b.copy(keydata, buf, offset, 0, keydata.length)\n offset += keydata.length\n\n rdnskey.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rdnskey.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const key = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n key.flags = b.readUInt16BE(buf, offset)\n offset += 2\n if (buf[offset] !== rdnskey.PROTOCOL_DNSSEC) {\n throw new Error('Protocol must be 3')\n }\n offset += 1\n key.algorithm = buf[offset]\n offset += 1\n key.key = buf.slice(offset, oldOffset + length + 2)\n offset += key.key.length\n rdnskey.decode.bytes = offset - oldOffset\n return key\n },\n encodingLength (key) {\n return 6 + b.bytelength(key.key)\n }\n})\n\nrdnskey.PROTOCOL_DNSSEC = 3\nrdnskey.ZONE_KEY = 0x80\nrdnskey.SECURE_ENTRYPOINT = 0x8000\n\nconst rrrsig = codec({\n encode (sig, buf, offset) {\n if (!buf) buf = new Uint8Array(rrrsig.encodingLength(sig))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const signature = sig.signature\n if (!b.isU8Arr(signature)) {\n throw new Error('Signature must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, types.toType(sig.typeCovered), offset)\n offset += 2\n buf[offset] = sig.algorithm\n offset += 1\n buf[offset] = sig.labels\n offset += 1\n b.writeUInt32BE(buf, sig.originalTTL, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.expiration, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.inception, offset)\n offset += 4\n b.writeUInt16BE(buf, sig.keyTag, offset)\n offset += 2\n name.encode(sig.signersName, buf, offset)\n offset += name.encode.bytes\n b.copy(signature, buf, offset, 0, signature.length)\n offset += signature.length\n\n rrrsig.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrrsig.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const sig = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n sig.typeCovered = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n sig.algorithm = buf[offset]\n offset += 1\n sig.labels = buf[offset]\n offset += 1\n sig.originalTTL = b.readUInt32BE(buf, offset)\n offset += 4\n sig.expiration = b.readUInt32BE(buf, offset)\n offset += 4\n sig.inception = b.readUInt32BE(buf, offset)\n offset += 4\n sig.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n sig.signersName = name.decode(buf, offset)\n offset += name.decode.bytes\n sig.signature = buf.slice(offset, oldOffset + length + 2)\n offset += sig.signature.length\n rrrsig.decode.bytes = offset - oldOffset\n return sig\n },\n encodingLength (sig) {\n return 20 +\n name.encodingLength(sig.signersName) +\n b.bytelength(sig.signature)\n }\n})\nconst rrp = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rrp.encodingLength(data))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(data.mbox || '.', buf, offset)\n offset += name.encode.bytes\n name.encode(data.txt || '.', buf, offset)\n offset += name.encode.bytes\n rrp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrp.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mbox = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n data.txt = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n rrp.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 2 + name.encodingLength(data.mbox || '.') + name.encodingLength(data.txt || '.')\n }\n})\n\nconst typebitmap = codec({\n encode (typelist, buf, offset) {\n if (!buf) buf = new Uint8Array(typebitmap.encodingLength(typelist))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typesByWindow = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n if (typesByWindow[typeid >> 8] === undefined) {\n typesByWindow[typeid >> 8] = []\n }\n typesByWindow[typeid >> 8][(typeid >> 3) & 0x1F] |= 1 << (7 - (typeid & 0x7))\n }\n\n for (let i = 0; i < typesByWindow.length; i++) {\n if (typesByWindow[i] !== undefined) {\n const windowBuf = b.from(typesByWindow[i])\n buf[offset] = i\n offset += 1\n buf[offset] = windowBuf.length\n offset += 1\n b.copy(windowBuf, buf, offset, 0, windowBuf.length)\n offset += windowBuf.length\n }\n }\n\n typebitmap.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset, length) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typelist = []\n while (offset - oldOffset < length) {\n const window = buf[offset]\n offset += 1\n const windowLength = buf[offset]\n offset += 1\n for (let i = 0; i < windowLength; i++) {\n const b = buf[offset + i]\n for (let j = 0; j < 8; j++) {\n if (b & (1 << (7 - j))) {\n const typeid = types.toString((window << 8) | (i << 3) | j)\n typelist.push(typeid)\n }\n }\n }\n offset += windowLength\n }\n\n typebitmap.decode.bytes = offset - oldOffset\n return typelist\n },\n encodingLength (typelist) {\n const extents = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 0xFF)\n }\n\n let len = 0\n for (let i = 0; i < extents.length; i++) {\n if (extents[i] !== undefined) {\n len += 2 + Math.ceil((extents[i] + 1) / 8)\n }\n }\n\n return len\n }\n})\n\nconst rnsec = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(record.nextDomain, buf, offset)\n offset += name.encode.bytes\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.nextDomain = name.decode(buf, offset)\n offset += name.decode.bytes\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 2 +\n name.encodingLength(record.nextDomain) +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rnsec3 = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec3.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const salt = record.salt\n if (!b.isU8Arr(salt)) {\n throw new Error('salt must be a Buffer')\n }\n\n const nextDomain = record.nextDomain\n if (!b.isU8Arr(nextDomain)) {\n throw new Error('nextDomain must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.flags\n offset += 1\n b.writeUInt16BE(buf, record.iterations, offset)\n offset += 2\n buf[offset] = salt.length\n offset += 1\n b.copy(salt, buf, offset, 0, salt.length)\n offset += salt.length\n buf[offset] = nextDomain.length\n offset += 1\n b.copy(nextDomain, buf, offset, 0, nextDomain.length)\n offset += nextDomain.length\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec3.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec3.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.algorithm = buf[offset]\n offset += 1\n record.flags = buf[offset]\n offset += 1\n record.iterations = b.readUInt16BE(buf, offset)\n offset += 2\n const saltLength = buf[offset]\n offset += 1\n record.salt = buf.slice(offset, offset + saltLength)\n offset += saltLength\n const hashLength = buf[offset]\n offset += 1\n record.nextDomain = buf.slice(offset, offset + hashLength)\n offset += hashLength\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec3.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 8 +\n record.salt.length +\n record.nextDomain.length +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rds = codec({\n encode (digest, buf, offset) {\n if (!buf) buf = new Uint8Array(rds.encodingLength(digest))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digestdata = digest.digest\n if (!b.isU8Arr(digestdata)) {\n throw new Error('Digest must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, digest.keyTag, offset)\n offset += 2\n buf[offset] = digest.algorithm\n offset += 1\n buf[offset] = digest.digestType\n offset += 1\n b.copy(digestdata, buf, offset, 0, digestdata.length)\n offset += digestdata.length\n\n rds.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rds.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digest = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n digest.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n digest.algorithm = buf[offset]\n offset += 1\n digest.digestType = buf[offset]\n offset += 1\n digest.digest = buf.slice(offset, oldOffset + length + 2)\n offset += digest.digest.length\n rds.decode.bytes = offset - oldOffset\n return digest\n },\n encodingLength (digest) {\n return 6 + b.bytelength(digest.digest)\n }\n})\n\nfunction renc (type) {\n switch (type.toUpperCase()) {\n case 'A': return ra\n case 'PTR': return rptr\n case 'CNAME': return rptr\n case 'DNAME': return rptr\n case 'TXT': return rtxt\n case 'NULL': return rnull\n case 'AAAA': return raaaa\n case 'SRV': return rsrv\n case 'HINFO': return rhinfo\n case 'CAA': return rcaa\n case 'NS': return rns\n case 'SOA': return rsoa\n case 'MX': return rmx\n case 'OPT': return ropt\n case 'DNSKEY': return rdnskey\n case 'RRSIG': return rrrsig\n case 'RP': return rrp\n case 'NSEC': return rnsec\n case 'NSEC3': return rnsec3\n case 'DS': return rds\n }\n return runknown\n}\n\nexport const answer = codec({\n encode (a, buf, offset) {\n if (!buf) buf = new Uint8Array(answer.encodingLength(a))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(a.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(a.type), offset)\n\n if (a.type.toUpperCase() === 'OPT') {\n if (a.name !== '.') {\n throw new Error('OPT name must be root.')\n }\n b.writeUInt16BE(buf, a.udpPayloadSize || 4096, offset + 2)\n buf[offset + 4] = a.extendedRcode || 0\n buf[offset + 5] = a.ednsVersion || 0\n b.writeUInt16BE(buf, a.flags || 0, offset + 6)\n\n offset += 8\n ropt.encode(a.options || [], buf, offset)\n offset += ropt.encode.bytes\n } else {\n let klass = classes.toClass(a.class === undefined ? 'IN' : a.class)\n if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit\n b.writeUInt16BE(buf, klass, offset + 2)\n b.writeUInt32BE(buf, a.ttl || 0, offset + 4)\n\n offset += 8\n const enc = renc(a.type)\n enc.encode(a.data, buf, offset)\n offset += enc.encode.bytes\n }\n\n answer.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const a = {}\n const oldOffset = offset\n\n a.name = name.decode(buf, offset)\n offset += name.decode.bytes\n a.type = types.toString(b.readUInt16BE(buf, offset))\n if (a.type === 'OPT') {\n a.udpPayloadSize = b.readUInt16BE(buf, offset + 2)\n a.extendedRcode = buf[offset + 4]\n a.ednsVersion = buf[offset + 5]\n a.flags = b.readUInt16BE(buf, offset + 6)\n a.flag_do = ((a.flags >> 15) & 0x1) === 1\n a.options = ropt.decode(buf, offset + 8)\n offset += 8 + ropt.decode.bytes\n } else {\n const klass = b.readUInt16BE(buf, offset + 2)\n a.ttl = b.readUInt32BE(buf, offset + 4)\n\n a.class = classes.toString(klass & NOT_FLUSH_MASK)\n a.flush = !!(klass & FLUSH_MASK)\n\n const enc = renc(a.type)\n a.data = enc.decode(buf, offset + 8)\n offset += 8 + enc.decode.bytes\n }\n\n answer.decode.bytes = offset - oldOffset\n return a\n },\n encodingLength (a) {\n const data = (a.data !== null && a.data !== undefined) ? a.data : a.options\n return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data)\n }\n})\n\nexport const question = codec({\n encode (q, buf, offset) {\n if (!buf) buf = new Uint8Array(question.encodingLength(q))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(q.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(q.type), offset)\n offset += 2\n\n b.writeUInt16BE(buf, classes.toClass(q.class === undefined ? 'IN' : q.class), offset)\n offset += 2\n\n question.encode.bytes = offset - oldOffset\n return q\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const q = {}\n\n q.name = name.decode(buf, offset)\n offset += name.decode.bytes\n\n q.type = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n q.class = classes.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n const qu = !!(q.class & QU_MASK)\n if (qu) q.class &= NOT_QU_MASK\n\n question.decode.bytes = offset - oldOffset\n return q\n },\n encodingLength (q) {\n return name.encodingLength(q.name) + 4\n }\n})\n\nexport {\n rsoa as soa,\n rtxt as txt,\n rnull as null,\n runknown as unknown,\n rns as ns,\n rhinfo as hinfo,\n rptr as ptr,\n rptr as cname,\n rptr as dname,\n rsrv as srv,\n rcaa as caa,\n rmx as mx,\n ra as a,\n raaaa as aaaa,\n roption as option,\n ropt as opt,\n rdnskey as dnskey,\n rrrsig as rrsig,\n rrp as rp,\n rnsec as nsec,\n rnsec3 as nsec3,\n rds as ds,\n renc as enc\n}\n\nexport const AUTHORITATIVE_ANSWER = 1 << 10\nexport const TRUNCATED_RESPONSE = 1 << 9\nexport const RECURSION_DESIRED = 1 << 8\nexport const RECURSION_AVAILABLE = 1 << 7\nexport const AUTHENTIC_DATA = 1 << 5\nexport const CHECKING_DISABLED = 1 << 4\nexport const DNSSEC_OK = 1 << 15\n\nexport const packet = {\n encode: function (result, buf, offset) {\n const allocing = !buf\n\n if (allocing) buf = new Uint8Array(encodingLength(result))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n if (!result.questions) result.questions = []\n if (!result.answers) result.answers = []\n if (!result.authorities) result.authorities = []\n if (!result.additionals) result.additionals = []\n\n header.encode(result, buf, offset)\n offset += header.encode.bytes\n\n offset = encodeList(result.questions, question, buf, offset)\n offset = encodeList(result.answers, answer, buf, offset)\n offset = encodeList(result.authorities, answer, buf, offset)\n offset = encodeList(result.additionals, answer, buf, offset)\n\n packet.encode.bytes = offset - oldOffset\n\n // just a quick sanity check\n if (allocing && encode.bytes !== buf.length) {\n return buf.slice(0, encode.bytes)\n }\n\n return buf\n },\n decode: function (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const result = header.decode(buf, offset)\n offset += header.decode.bytes\n\n offset = decodeList(result.questions, question, buf, offset)\n offset = decodeList(result.answers, answer, buf, offset)\n offset = decodeList(result.authorities, answer, buf, offset)\n offset = decodeList(result.additionals, answer, buf, offset)\n\n packet.decode.bytes = offset - oldOffset\n\n return result\n },\n encodingLength: function (result) {\n return header.encodingLength(result) +\n encodingLengthList(result.questions || [], question) +\n encodingLengthList(result.answers || [], answer) +\n encodingLengthList(result.authorities || [], answer) +\n encodingLengthList(result.additionals || [], answer)\n }\n}\npacket.encode.bytes = 0\npacket.decode.bytes = 0\n\nfunction sanitizeSingle (input, type) {\n if (input.questions) {\n throw new Error('Only one .question object expected instead of a .questions array!')\n }\n const sanitized = Object.assign({\n type\n }, input)\n if (sanitized.question) {\n sanitized.questions = [sanitized.question]\n delete sanitized.question\n }\n return sanitized\n}\n\nexport const query = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'query'), buf, offset)\n query.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n query.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'query'))\n }\n}\nquery.encode.bytes = 0\nquery.decode.bytes = 0\n\nexport const response = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'response'), buf, offset)\n response.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n response.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'response'))\n }\n}\nresponse.encode.bytes = 0\nresponse.decode.bytes = 0\n\nexport const encode = packet.encode\nexport const decode = packet.decode\nexport const encodingLength = packet.encodingLength\n\nexport function streamEncode (result) {\n const buf = encode(result)\n const combine = new Uint8Array(2 + buf.byteLength)\n b.writeUInt16BE(combine, buf.byteLength)\n b.copy(buf, combine, 2, 0, buf.length)\n streamEncode.bytes = combine.byteLength\n return combine\n}\nstreamEncode.bytes = 0\n\nexport function streamDecode (sbuf) {\n const len = b.readUInt16BE(sbuf, 0)\n if (sbuf.byteLength < len + 2) {\n // not enough data\n return null\n }\n const result = decode(sbuf.slice(2))\n streamDecode.bytes = decode.bytes\n return result\n}\nstreamDecode.bytes = 0\n\nexport function encodingLengthList (list, enc) {\n let len = 0\n for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i])\n return len\n}\n\nexport function encodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n enc.encode(list[i], buf, offset)\n offset += enc.encode.bytes\n }\n return offset\n}\n\nexport function decodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n list[i] = enc.decode(buf, offset)\n offset += enc.decode.bytes\n }\n return offset\n}\n","export const PREFERS_PADDING = 1\nexport const PREFERS_NO_PADDING = 2\n\nexport function make (name, charset, padding, paddingMode) {\n if (charset.length !== 64) {\n throw new Error(`Charset needs to be 64 characters long! (${charset.length})`)\n }\n const byCharCode = new Uint8Array(256)\n const byNum = new Uint8Array(64)\n for (let i = 0; i < 64; i += 1) {\n const code = charset.charCodeAt(i)\n if (code > 255) {\n throw new Error(`Character #${i} in charset [code=${code}, char=${charset.charAt(i)}] is too high! (max=255)`)\n }\n if (byCharCode[code] !== 0) {\n throw new Error(`Character [code=${code}, char=${charset.charAt(i)}] is more than once in the charset!`)\n }\n byCharCode[code] = i\n byNum[i] = code\n }\n const padCode = padding.charCodeAt(0)\n const codec = {\n name,\n encodingLength (str) {\n const strLen = str.length\n const len = strLen * 0.75 | 0\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n return len - 2\n }\n return len - 1\n }\n return len\n },\n encode (str, buffer, offset) {\n if (buffer === null || buffer === undefined) {\n buffer = new Uint8Array(codec.encodingLength(str))\n }\n if (offset === null || offset === undefined) {\n offset = 0\n }\n\n let strLen = str.length\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n strLen -= 2\n } else {\n strLen -= 1\n }\n }\n\n const padding = strLen % 4\n const safeLen = strLen - padding\n\n let off = offset\n let i = 0\n while (i < safeLen) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 18) |\n (byCharCode[str.charCodeAt(i + 1)] << 12) |\n (byCharCode[str.charCodeAt(i + 2)] << 6) |\n byCharCode[str.charCodeAt(i + 3)]\n buffer[off++] = code >> 16\n buffer[off++] = code >> 8\n buffer[off++] = code\n i += 4\n }\n\n if (padding === 3) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 10) |\n (byCharCode[str.charCodeAt(i + 1)] << 4) |\n (byCharCode[str.charCodeAt(i + 2)] >> 2)\n buffer[off++] = code >> 8\n buffer[off++] = code\n } else if (padding === 2) {\n buffer[off++] = (byCharCode[str.charCodeAt(i)] << 2) |\n (byCharCode[str.charCodeAt(i + 1)] >> 4)\n }\n\n codec.encode.bytes = off - offset\n return buffer\n },\n decode (buffer, start, end) {\n if (start === null || start === undefined) {\n start = 0\n }\n if (end === null || end === undefined) {\n end = buffer.length\n }\n\n const length = end - start\n const pad = length % 3\n const safeEnd = start + length - pad\n const codes = []\n for (let off = start; off < safeEnd; off += 3) {\n const num = (buffer[off] << 16) | ((buffer[off + 1] << 8)) | buffer[off + 2]\n codes.push(\n byNum[num >> 18 & 0x3F],\n byNum[num >> 12 & 0x3F],\n byNum[num >> 6 & 0x3F],\n byNum[num & 0x3F]\n )\n }\n\n if (pad === 2) {\n const num = (buffer[end - 2] << 8) + buffer[end - 1]\n codes.push(\n byNum[num >> 10],\n byNum[(num >> 4) & 0x3F],\n byNum[(num << 2) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode)\n }\n } else if (pad === 1) {\n const num = buffer[end - 1]\n codes.push(\n byNum[num >> 2],\n byNum[(num << 4) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode, padCode)\n }\n }\n\n codec.decode.bytes = length\n return String.fromCharCode.apply(String, codes)\n }\n }\n return codec\n}\n\nexport const base64 = make('base64', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', '=', PREFERS_PADDING)\n// https://datatracker.ietf.org/doc/html/rfc4648#section-5\nexport const base64URL = make('base64-url', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', '=', PREFERS_NO_PADDING)\n","let AbortError = typeof global !== 'undefined' ? global.AbortError : typeof window !== 'undefined' ? window.AbortError : null\nif (!AbortError) {\n AbortError = class AbortError extends Error {\n constructor (message = 'Request aborted.') {\n super(message)\n }\n }\n}\nAbortError.prototype.name = 'AbortError'\nAbortError.prototype.code = 'ABORT_ERR'\n\nconst URL = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL\n\nexport { AbortError, URL }\n\nexport class HTTPStatusError extends Error {\n constructor (uri, code, method) {\n super('status=' + code + ' while requesting ' + uri + ' [' + method + ']')\n this.uri = uri\n this.status = code\n this.method = method\n }\n\n toJSON () {\n return {\n code: this.code,\n uri: this.uri,\n status: this.status,\n method: this.method,\n endpoint: this.endpoint\n }\n }\n}\nHTTPStatusError.prototype.name = 'HTTPStatusError'\nHTTPStatusError.prototype.code = 'HTTP_STATUS'\n\nexport class ResponseError extends Error {\n constructor (message, cause) {\n super(message)\n this.cause = cause\n }\n\n toJSON () {\n return {\n message: this.message,\n endpoint: this.endpoint,\n code: this.code,\n cause: reduceError(this.cause)\n }\n }\n}\nResponseError.prototype.name = 'ResponseError'\nResponseError.prototype.code = 'RESPONSE_ERR'\n\nexport class TimeoutError extends Error {\n constructor (timeout) {\n super('Timeout (t=' + timeout + ').')\n this.timeout = timeout\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nTimeoutError.prototype.name = 'TimeoutError'\nTimeoutError.prototype.code = 'ETIMEOUT'\n\nconst v4Regex = /^((\\d{1,3}\\.){3,3}\\d{1,3})(:(\\d{2,5}))?$/\nconst v6Regex = /^((::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\\d{2,5}))?$/i\n\nexport function reduceError (err) {\n if (typeof err === 'string') {\n return {\n message: err\n }\n }\n try {\n const json = JSON.stringify(err)\n if (json !== '{}') {\n return JSON.parse(json)\n }\n } catch (e) {}\n const error = {\n message: String(err.message || err)\n }\n if (err.code !== undefined) {\n error.code = String(err.code)\n }\n return error\n}\n\nconst baseParts = /^(([a-z0-9]+:)\\/\\/)?([^/[\\s:]+|\\[[^\\]]+\\])?(:([^/\\s]+))?(\\/[^\\s]*)?(.*)$/\nconst httpFlags = /\\[(post|get|((ipv4|ipv6|name)=([^\\]]+)))\\]/ig\nconst updFlags = /\\[(((pk|name)=([^\\]]+)))\\]/ig\n\nexport function parseEndpoint (endpoint) {\n const parts = baseParts.exec(endpoint)\n const protocol = parts[2] || 'https:'\n const host = parts[3]\n const port = parts[5]\n const path = parts[6]\n const rest = parts[7]\n if (protocol === 'https:' || protocol === 'http:') {\n const flags = parseFlags(rest, httpFlags)\n return {\n name: flags.name,\n protocol,\n ipv4: flags.ipv4,\n ipv6: flags.ipv6,\n host,\n port,\n path,\n method: flags.post ? 'POST' : 'GET'\n }\n }\n if (protocol === 'udp:' || protocol === 'udp4:' || protocol === 'udp6:') {\n const flags = parseFlags(rest, updFlags)\n const v6Parts = /^\\[(.*)\\]$/.exec(host)\n if (v6Parts && protocol === 'udp4:') {\n throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${endpoint})`)\n }\n if (!v6Parts && protocol === 'udp6:') {\n throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${endpoint})`)\n }\n if (v6Parts) {\n return new UDP6Endpoint({ protocol: 'udp6:', ipv6: v6Parts[1], port, pk: flags.pk, name: flags.name })\n }\n return new UDP4Endpoint({ protocol: 'udp4:', ipv4: host, port, pk: flags.pk, name: flags.name })\n }\n throw new InvalidProtocolError(protocol, endpoint)\n}\n\nfunction parseFlags (rest, regex) {\n regex.lastIndex = 0\n const result = {}\n while (true) {\n const match = regex.exec(rest)\n if (!match) break\n if (match[2]) {\n result[match[3].toLowerCase()] = match[4]\n } else {\n result[match[1].toLowerCase()] = true\n }\n }\n return result\n}\n\nexport class InvalidProtocolError extends Error {\n constructor (protocol, endpoint) {\n super(`Invalid Endpoint: unsupported protocol \"${protocol}\" for endpoint: ${endpoint}, supported protocols: ${supportedProtocols.join(', ')}`)\n this.protocol = protocol\n this.endpoint = endpoint\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nInvalidProtocolError.prototype.name = 'InvalidProtocolError'\nInvalidProtocolError.prototype.code = 'EPROTOCOL'\n\nexport const supportedProtocols = ['http:', 'https:', 'udp4:', 'udp6:']\n\nexport class BaseEndpoint {\n constructor (opts, isHTTP) {\n this.name = opts.name || null\n this.protocol = opts.protocol\n const port = typeof opts.port === 'string' ? opts.port = parseInt(opts.port, 10) : opts.port\n if (port === undefined || port === null) {\n this.port = isHTTP\n ? (this.protocol === 'https:' ? 443 : 80)\n : (opts.pk ? 443 : 53)\n } else if (typeof port !== 'number' && !isNaN(port)) {\n throw new Error(`Invalid Endpoint: port \"${opts.port}\" needs to be a number: ${JSON.stringify(opts)}`)\n } else {\n this.port = port\n }\n }\n\n toJSON () {\n return this.toString()\n }\n}\n\nexport class UDPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(opts, false)\n this.pk = opts.pk || null\n }\n\n toString () {\n const port = this.port !== (this.pk ? 443 : 53) ? `:${this.port}` : ''\n const pk = this.pk ? ` [pk=${this.pk}]` : ''\n const name = this.name ? ` [name=${this.name}]` : ''\n return `udp://${this.ipv4 || `[${this.ipv6}]`}${port}${pk}${name}`\n }\n}\n\nexport class UDP4Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp4:' }, opts))\n if (!opts.ipv4 || typeof opts.ipv4 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv4 \"${opts.ipv4}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv4 = opts.ipv4\n }\n}\n\nexport class UDP6Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp6:' }, opts))\n if (!opts.ipv6 || typeof opts.ipv6 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv6 \"${opts.ipv6}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv6 = opts.ipv6\n }\n}\n\nfunction safeHost (host) {\n return v6Regex.test(host) && !v4Regex.test(host) ? `[${host}]` : host\n}\n\nexport class HTTPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'https:' }, opts), true)\n if (!opts.host) {\n if (opts.ipv4) {\n opts.host = opts.ipv4\n }\n if (opts.ipv6) {\n opts.host = `[${opts.ipv6}]`\n }\n }\n if (!opts.host || typeof opts.host !== 'string') {\n throw new Error(`Invalid Endpoint: host \"${opts.path}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.host = opts.host\n this.path = opts.path || '/dns-query'\n this.method = /^post$/i.test(opts.method) ? 'POST' : 'GET'\n this.ipv4 = opts.ipv4\n this.ipv6 = opts.ipv6\n if (!this.ipv6) {\n const v6Parts = v6Regex.exec(this.host)\n if (v6Parts) {\n this.ipv6 = v6Parts[1]\n }\n }\n if (!this.ipv4) {\n if (v4Regex.test(this.host)) {\n this.ipv4 = this.host\n }\n }\n const url = `${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`\n try {\n this.url = new URL(url)\n } catch (err) {\n throw new Error(err.message + ` [${url}]`)\n }\n }\n\n toString () {\n const protocol = this.protocol === 'https:' ? '' : 'http://'\n const port = this.port !== (this.protocol === 'https:' ? 443 : 80) ? `:${this.port}` : ''\n const method = this.method !== 'GET' ? ' [post]' : ''\n const path = this.path === '/dns-query' ? '' : this.path\n const name = this.name ? ` [name=${this.name}]` : ''\n const ipv4 = this.ipv4 && this.ipv4 !== this.host ? ` [ipv4=${this.ipv4}]` : ''\n const ipv6 = this.ipv6 && this.ipv6 !== this.host ? ` [ipv6=${this.ipv6}]` : ''\n return `${protocol}${safeHost(this.host)}${port}${path}${method}${ipv4}${ipv6}${name}`\n }\n}\n\nexport function toEndpoint (input) {\n let opts\n if (typeof input === 'string') {\n opts = parseEndpoint(input)\n } else {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error(`Can not convert ${input} to an endpoint`)\n } else if (input instanceof BaseEndpoint) {\n return input\n }\n opts = input\n }\n if (opts.protocol === null || opts.protocol === undefined) {\n opts.protocol = 'https:'\n }\n const protocol = opts.protocol\n if (protocol === 'udp4:') {\n return new UDP4Endpoint(opts)\n }\n if (protocol === 'udp6:') {\n return new UDP6Endpoint(opts)\n }\n if (protocol === 'https:' || protocol === 'http:') {\n return new HTTPEndpoint(opts)\n }\n throw new InvalidProtocolError(protocol, JSON.stringify(opts))\n}\n","/* global XMLHttpRequest, localStorage */\nimport * as utf8Codec from 'utf8-codec'\nimport { base64URL } from '@leichtgewicht/base64-codec'\nimport {\n AbortError,\n HTTPStatusError,\n TimeoutError,\n URL\n} from './common.mjs'\nconst contentType = 'application/dns-message'\n\nfunction noop () { }\n\nexport function queryDns () {\n throw new Error('Only \"doh\" endpoints are supported in the browser')\n}\n\nexport async function loadJSON (url, cache, timeout, abortSignal) {\n const cacheKey = cache ? cache.localStoragePrefix + cache.name : null\n if (cacheKey) {\n try {\n const cached = JSON.parse(localStorage.getItem(cacheKey))\n if (cached && cached.time > cache.maxTime) {\n return cached\n }\n } catch (err) {}\n }\n const { data } = await requestRaw(url, 'GET', null, timeout, abortSignal)\n const result = {\n time: Date.now(),\n data: JSON.parse(utf8Codec.decode(data))\n }\n if (cacheKey) {\n try {\n localStorage.setItem(cacheKey, JSON.stringify(result))\n } catch (err) {\n result.time = null\n }\n }\n return result\n}\n\nfunction requestRaw (url, method, data, timeout, abortSignal) {\n return new Promise((resolve, reject) => {\n const target = new URL(url)\n if (method === 'GET' && data) {\n target.search = '?dns=' + base64URL.decode(data)\n }\n const uri = target.toString()\n const xhr = new XMLHttpRequest()\n xhr.open(method, uri, true)\n xhr.setRequestHeader('Accept', contentType)\n if (method === 'POST') {\n xhr.setRequestHeader('Content-Type', contentType)\n }\n xhr.responseType = 'arraybuffer'\n xhr.timeout = timeout\n xhr.ontimeout = ontimeout\n xhr.onreadystatechange = onreadystatechange\n xhr.onerror = onerror\n xhr.onload = onload\n if (method === 'POST') {\n xhr.send(data)\n } else {\n xhr.send()\n }\n\n if (abortSignal) {\n abortSignal.addEventListener('abort', onabort)\n }\n\n function ontimeout () {\n finish(new TimeoutError(timeout))\n try {\n xhr.abort()\n } catch (e) { }\n }\n\n function onload () {\n if (xhr.status !== 200) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n } else {\n let buf\n if (typeof xhr.response === 'string') {\n buf = utf8Codec.encode(xhr.response)\n } else if (xhr.response instanceof Uint8Array) {\n buf = xhr.response\n } else if (Array.isArray(xhr.response) || xhr.response instanceof ArrayBuffer) {\n buf = new Uint8Array(xhr.response)\n } else {\n throw new Error('Unprocessable response ' + xhr.response)\n }\n finish(null, buf)\n }\n }\n\n function onreadystatechange () {\n if (xhr.readyState > 1 && xhr.status !== 200 && xhr.status !== 0) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n try {\n xhr.abort()\n } catch (e) { }\n }\n }\n\n let finish = function (error, data) {\n finish = noop\n if (abortSignal) {\n abortSignal.removeEventListener('abort', onabort)\n }\n if (error) {\n resolve({\n error,\n response: xhr\n })\n } else {\n resolve({\n data,\n response: xhr\n })\n }\n }\n\n function onerror () {\n finish(xhr.status === 200 ? new Error('Inexplicable XHR Error') : new HTTPStatusError(uri, xhr.status, method))\n }\n\n function onabort () {\n finish(new AbortError())\n try {\n xhr.abort()\n } catch (e) { }\n }\n })\n}\n\nexport function request (url, method, packet, timeout, abortSignal) {\n return requestRaw(url, method, packet, timeout, abortSignal)\n}\n\nexport function processResolvers (resolvers) {\n return resolvers.filter(resolver => resolver.cors || resolver.endpoint.cors)\n}\n","import * as packet from '@leichtgewicht/dns-packet'\nimport { toRcode } from '@leichtgewicht/dns-packet/rcodes.js'\nimport { decode } from 'utf8-codec'\nimport * as lib from './lib.mjs'\nimport { resolvers as backupResolvers } from './resolvers.mjs'\nimport {\n AbortError,\n ResponseError,\n URL,\n toEndpoint\n} from './common.mjs'\n\nexport {\n TimeoutError,\n HTTPStatusError,\n AbortError,\n ResponseError,\n BaseEndpoint,\n HTTPEndpoint,\n UDP4Endpoint,\n UDP6Endpoint,\n parseEndpoint,\n toEndpoint\n} from './common.mjs'\n\nexport const DNS_RCODE_ERROR = {\n 1: 'FormErr',\n 2: 'ServFail',\n 3: 'NXDomain',\n 4: 'NotImp',\n 5: 'Refused',\n 6: 'YXDomain',\n 7: 'YXRRSet',\n 8: 'NXRRSet',\n 9: 'NotAuth',\n 10: 'NotZone',\n 11: 'DSOTYPENI'\n}\n\nexport const DNS_RCODE_MESSAGE = {\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n 1: 'The name server was unable to interpret the query.',\n 2: 'The name server was unable to process this query due to a problem with the name server.',\n 3: 'Non-Existent Domain.',\n 4: 'The name server does not support the requested kind of query.',\n 5: 'The name server refuses to perform the specified operation for policy reasons.',\n 6: 'Name Exists when it should not.',\n 7: 'RR Set Exists when it should not.',\n 8: 'RR Set that should exist does not.',\n 9: 'Server Not Authoritative for zone / Not Authorized.',\n 10: 'Name not contained in zone.',\n 11: 'DSO-TYPE Not Implemented.'\n}\n\nexport class DNSRcodeError extends Error {\n constructor (rcode, question) {\n super(`${(DNS_RCODE_MESSAGE[rcode] || 'Undefined error.')} (rcode=${rcode}${DNS_RCODE_ERROR[rcode] ? `, error=${DNS_RCODE_ERROR[rcode]}` : ''}, question=${JSON.stringify(question)})`)\n this.rcode = rcode\n this.code = `DNS_RCODE_${rcode}`\n this.error = DNS_RCODE_ERROR[rcode]\n this.question = question\n }\n\n toJSON () {\n return {\n code: this.code,\n error: this.error,\n question: this.question,\n endpoint: this.endpoint\n }\n }\n}\n\nexport function validateResponse (data, question) {\n const rcode = toRcode(data.rcode)\n if (rcode !== 0) {\n const err = new DNSRcodeError(rcode, question)\n err.endpoint = data.endpoint\n throw err\n }\n return data\n}\n\nfunction processResolvers (res) {\n const time = (res.time === null || res.time === undefined) ? Date.now() : res.time\n const resolvers = lib.processResolvers(res.data.map(resolver => {\n resolver.endpoint = toEndpoint(Object.assign({ name: resolver.name }, resolver.endpoint))\n return resolver\n }))\n const endpoints = resolvers.map(resolver => resolver.endpoint)\n return {\n data: {\n resolvers,\n resolverByName: resolvers.reduce((byName, resolver) => {\n byName[resolver.name] = resolver\n return byName\n }, {}),\n endpoints,\n endpointByName: endpoints.reduce((byName, endpoint) => {\n byName[endpoint.name] = endpoint\n return byName\n }, {})\n },\n time\n }\n}\n\nexport const backup = processResolvers(backupResolvers)\n\nfunction toMultiQuery (singleQuery) {\n const query = Object.assign({\n type: 'query'\n }, singleQuery)\n delete query.question\n query.questions = []\n if (singleQuery.question) {\n query.questions.push(singleQuery.question)\n }\n return query\n}\n\nfunction queryOne (endpoint, query, timeout, abortSignal) {\n if (abortSignal && abortSignal.aborted) {\n return Promise.reject(new AbortError())\n }\n if (endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:') {\n return lib.queryDns(endpoint, query, timeout, abortSignal)\n }\n return queryDoh(endpoint, query, timeout, abortSignal)\n}\n\nfunction queryDoh (endpoint, query, timeout, abortSignal) {\n return lib.request(\n endpoint.url,\n endpoint.method,\n packet.encode(Object.assign({\n flags: packet.RECURSION_DESIRED\n }, query)),\n timeout,\n abortSignal\n ).then(\n function (res) {\n const data = res.data\n const response = res.response\n let error = res.error\n if (error === undefined) {\n if (data.length === 0) {\n error = new ResponseError('Empty.')\n } else {\n try {\n const decoded = packet.decode(data)\n decoded.response = response\n return decoded\n } catch (err) {\n error = new ResponseError('Invalid packet (cause=' + err.message + ')', err)\n }\n }\n }\n throw Object.assign(error, { response })\n }\n )\n}\n\nconst UPDATE_URL = new URL('https://martinheidegger.github.io/dns-query/resolvers.json')\n\nfunction concatUint8 (arrs) {\n const res = new Uint8Array(\n arrs.reduce((len, arr) => len + arr.length, 0)\n )\n let pos = 0\n for (const arr of arrs) {\n res.set(arr, pos)\n pos += arr.length\n }\n return res\n}\n\nexport function combineTXT (inputs) {\n return decode(concatUint8(inputs))\n}\n\nfunction isNameString (entry) {\n return /^@/.test(entry)\n}\n\nexport class Wellknown {\n constructor (opts) {\n this.opts = Object.assign({\n timeout: 5000,\n update: true,\n updateURL: UPDATE_URL,\n persist: false,\n localStoragePrefix: 'dnsquery_',\n maxAge: 300000 // 5 minutes\n }, opts)\n this._dataP = null\n }\n\n _data (force, outdated) {\n if (!force && this._dataP !== null) {\n return this._dataP.then(res => {\n if (res.time < Date.now() - this.opts.maxAge) {\n return this._data(true, res)\n }\n return res\n })\n }\n this._dataP = (!this.opts.update\n ? Promise.resolve(backup)\n : lib.loadJSON(\n this.opts.updateURL,\n this.opts.persist\n ? {\n name: 'resolvers.json',\n localStoragePrefix: this.opts.localStoragePrefix,\n maxTime: Date.now() - this.opts.maxAge\n }\n : null,\n this.opts.timeout\n )\n .then(res => processResolvers({\n data: res.data.resolvers,\n time: res.time\n }))\n .catch(() => outdated || backup)\n )\n return this._dataP\n }\n\n data () {\n return this._data(false).then(data => data.data)\n }\n\n endpoints (input) {\n if (input === null || input === undefined) {\n return this.data().then(data => data.endpoints)\n }\n if (input === 'doh') {\n input = filterDoh\n }\n if (input === 'dns') {\n input = filterDns\n }\n if (typeof input === 'function') {\n return this.data().then(data => data.endpoints.filter(input))\n }\n if (typeof input === 'string' || typeof input[Symbol.iterator] !== 'function') {\n return Promise.reject(new Error(`Endpoints (${input}) needs to be iterable (array).`))\n }\n input = Array.from(input).filter(Boolean)\n if (input.findIndex(isNameString) === -1) {\n try {\n return Promise.resolve(input.map(toEndpoint))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n return this.data().then(data =>\n input.map(entry => {\n if (isNameString(entry)) {\n const found = data.endpointByName[entry.substring(1)]\n if (!found) {\n throw new Error(`Endpoint ${entry} is not known.`)\n }\n return found\n }\n return toEndpoint(entry)\n })\n )\n }\n}\n\nexport const wellknown = new Wellknown()\n\nfunction isPromise (input) {\n if (input === null) {\n return false\n }\n if (typeof input !== 'object') {\n return false\n }\n return typeof input.then === 'function'\n}\n\nfunction toPromise (input) {\n return isPromise(input) ? input : Promise.resolve(input)\n}\n\nexport function query (q, opts) {\n opts = Object.assign({\n retries: 5,\n timeout: 30000 // 30 seconds\n }, opts)\n if (!q.question) return Promise.reject(new Error('To request data you need to specify a .question!'))\n return toPromise(opts.endpoints)\n .then(endpoints => {\n if (!Array.isArray(endpoints) || endpoints.length === 0) {\n throw new Error('No endpoints defined to lookup dns records.')\n }\n return queryN(endpoints.map(toEndpoint), toMultiQuery(q), opts)\n })\n .then(data => {\n data.question = data.questions[0]\n delete data.questions\n return data\n })\n}\n\nexport function lookupTxt (domain, opts) {\n const q = Object.assign({\n question: {\n type: 'TXT',\n name: domain\n }\n }, opts.query)\n return query(q, opts)\n .then(data => {\n validateResponse(data, q)\n return {\n entries: (data.answers || [])\n .filter(answer => answer.type === 'TXT' && answer.data)\n .map(answer => {\n return ({\n data: combineTXT(answer.data),\n ttl: answer.ttl\n })\n })\n .sort((a, b) => {\n if (a.data > b.data) return 1\n if (a.data < b.data) return -1\n return 0\n }),\n endpoint: data.endpoint\n }\n })\n}\n\nfunction queryN (endpoints, q, opts) {\n const endpoint = endpoints.length === 1\n ? endpoints[0]\n : endpoints[Math.floor(Math.random() * endpoints.length) % endpoints.length]\n return queryOne(endpoint, q, opts.timeout, opts.signal)\n .then(\n data => {\n // Add the endpoint to give a chance to identify which endpoint returned the result\n data.endpoint = endpoint.toString()\n return data\n },\n err => {\n if (err.name === 'AbortError' || opts.retries === 0) {\n err.endpoint = endpoint.toString()\n throw err\n }\n if (opts.retries > 0) {\n opts.retries -= 1\n }\n return queryN(endpoints, q, opts)\n }\n )\n}\n\nfunction filterDoh (endpoint) {\n return endpoint.protocol === 'https:' || endpoint.protocol === 'http:'\n}\n\nfunction filterDns (endpoint) {\n return endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:'\n}\n","export const resolvers = {\n data: [\n {\n name: 'adfree.usableprivacy.net',\n endpoint: {\n protocol: 'https:',\n host: 'adfree.usableprivacy.net'\n },\n description: 'Public updns DoH service with advertising, tracker and malware filters.\\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true\n },\n {\n name: 'adguard-dns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.adguard.com',\n ipv4: '94.140.15.15'\n },\n description: 'Remove ads and protect your computer from malware (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-family-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-family.adguard.com',\n ipv4: '94.140.15.16'\n },\n description: 'Adguard DNS with safesearch and adult content blocking (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-unfiltered-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-unfiltered.adguard.com',\n ipv4: '94.140.14.140'\n },\n description: 'AdGuard public DNS servers without filters (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n }\n },\n {\n name: 'ahadns-doh-chi',\n endpoint: {\n protocol: 'https:',\n host: 'doh.chi.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 41.8483,\n long: -87.6517\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-in',\n endpoint: {\n protocol: 'https:',\n host: 'doh.in.ahadns.net',\n cors: true\n },\n 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',\n country: 'India',\n location: {\n lat: 19.0748,\n long: 72.8856\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-la',\n endpoint: {\n protocol: 'https:',\n host: 'doh.la.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 34.0549,\n long: -118.2578\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.nl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-ny',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ny.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 40.7308,\n long: -73.9975\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-pl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'alidns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.alidns.com',\n ipv4: '223.5.5.5',\n cors: true\n },\n 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/',\n country: 'China',\n location: {\n lat: 34.7725,\n long: 113.7266\n },\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'ams-ads-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl-noads.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n },\n filter: true\n },\n {\n name: 'ams-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n }\n },\n {\n name: 'att',\n endpoint: {\n protocol: 'https:',\n host: 'dohtrial.att.net'\n },\n description: 'AT&T test DoH server.',\n log: true\n },\n {\n name: 'bcn-ads-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses-noads.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n },\n filter: true\n },\n {\n name: 'bcn-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n }\n },\n {\n name: 'brahma-world',\n endpoint: {\n protocol: 'https:',\n host: 'dns.brahma.world'\n },\n 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)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'cisco-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.opendns.com',\n ipv4: '146.112.41.2'\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true,\n log: true\n },\n {\n name: 'cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'dns.cloudflare.com',\n ipv4: '1.0.0.1',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n cors: true\n },\n {\n name: 'cloudflare-family',\n endpoint: {\n protocol: 'https:',\n host: 'family.cloudflare-dns.com',\n ipv4: '1.0.0.3',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'cloudflare-ipv6',\n endpoint: {\n protocol: 'https:',\n host: '1dot1dot1dot1.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare DNS over IPv6 (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'cloudflare-security',\n endpoint: {\n protocol: 'https:',\n host: 'security.cloudflare-dns.com',\n ipv4: '1.0.0.2',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'controld-block-malware',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p1'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p2'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad-social',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p3'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-family-friendly',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/family'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-uncensored',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/uncensored'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'controld-unfiltered',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p0'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'dns.digitale-gesellschaft.ch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.digitale-gesellschaft.ch'\n },\n description: 'Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\\nHosted in Zurich, Switzerland.\\nNon-logging, non-filtering, supports DNSSEC.',\n country: 'Switzerland',\n location: {\n lat: 47.1449,\n long: 8.1551\n }\n },\n {\n name: 'dns.ryan-palmer',\n endpoint: {\n protocol: 'https:',\n host: 'dns1.ryan-palmer.com'\n },\n description: 'Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.',\n country: 'United Kingdom',\n location: {\n lat: 51.5164,\n long: -0.093\n }\n },\n {\n name: 'dns.sb',\n endpoint: {\n protocol: 'https:',\n host: 'doh.sb',\n ipv4: '185.222.222.222',\n cors: true\n },\n description: 'DNSSEC-enabled DoH server by https://xtom.com/\\nhttps://dns.sb/doh/',\n country: 'Unknown',\n location: {\n lat: 47,\n long: 8\n },\n cors: true\n },\n {\n name: 'dns.therifleman.name',\n endpoint: {\n protocol: 'https:',\n host: 'dns.therifleman.name'\n },\n 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',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh-no-safe-search',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh-no-safe-search.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforge.de',\n endpoint: {\n protocol: 'https:',\n host: 'dnsforge.de',\n cors: true\n },\n description: 'Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.',\n country: 'Germany',\n location: {\n lat: 52.2998,\n long: 9.447\n },\n filter: true,\n cors: true\n },\n {\n name: 'dnshome-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.dnshome.de'\n },\n description: 'https://www.dnshome.de/ public resolver in Germany'\n },\n {\n name: 'dnspod-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pub',\n cors: true\n },\n description: 'A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en',\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'dnswarden-asia-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adblock'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-adultfilter-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adultfilter'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-uncensor-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/uncensored'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n }\n },\n {\n name: 'dnswarden-eu-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.eu.dnswarden.com'\n },\n description: 'Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Germany',\n location: {\n lat: 50.1103,\n long: 8.7147\n },\n filter: true\n },\n {\n name: 'dnswarden-us-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.us.dnswarden.com'\n },\n description: 'Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'United States',\n location: {\n lat: 32.7889,\n long: -96.8021\n },\n filter: true\n },\n {\n name: 'doh-ch-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ch.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-adult',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/adult-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-family',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/family-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-security',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/security-filter/',\n cors: true\n },\n description: 'Block access to phishing, malware and malicious domains. It does not block adult content.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'doh.crypto.sx',\n cors: true\n },\n description: 'DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\\nBackend hosted by Scaleway, globally cached via Cloudflare.\\nMaintained by Frank Denis.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-crypto-sx-ipv6',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ipv6.crypto.sx',\n cors: true\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-de-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-de.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-fi-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-fi.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-ibksturm',\n endpoint: {\n protocol: 'https:',\n host: 'ibksturm.synology.me'\n },\n description: 'DoH & DoT Server, No Logging, No Filters, DNSSEC\\nRunning privately by ibksturm in Thurgau, Switzerland'\n },\n {\n name: 'doh-jp-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-jp.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh.ffmuc.net',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ffmuc.net'\n },\n description: 'An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\\nhttps://ffmuc.net/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'doh.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org'\n },\n description: 'Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'google',\n endpoint: {\n protocol: 'https:',\n host: 'dns.google',\n ipv4: '8.8.8.8',\n cors: true\n },\n description: 'Google DNS (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true,\n cors: true\n },\n {\n name: 'hdns',\n endpoint: {\n protocol: 'https:',\n host: 'query.hdns.io',\n cors: true\n },\n description: 'HDNS is a public DNS resolver that supports Handshake domains.\\nhttps://www.hdns.io',\n country: 'United States',\n location: {\n lat: 37.7771,\n long: -122.406\n },\n cors: true\n },\n {\n name: 'he',\n endpoint: {\n protocol: 'https:',\n host: 'ordns.he.net'\n },\n description: 'Hurricane Electric DoH server (anycast)\\nUnknown logging policy.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true\n },\n {\n name: 'id-gmail-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app'\n },\n description: 'Non-Logging DNS-over-HTTPS server located in Singapore.\\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'iij',\n endpoint: {\n protocol: 'https:',\n host: 'public.dns.iij.jp'\n },\n description: 'DoH server operated by Internet Initiative Japan in Tokyo.\\nhttps://www.iij.ad.jp/',\n country: 'Japan',\n location: {\n lat: 35.69,\n long: 139.69\n },\n log: true\n },\n {\n name: 'iqdns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'a.passcloud.xyz'\n },\n 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',\n filter: true\n },\n {\n name: 'jp.tiar.app-doh',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app'\n },\n description: 'Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\\nNo ECS, Support DNSSEC',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n }\n },\n {\n name: 'jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org'\n },\n description: 'DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\\nCached via Cloudflare.'\n },\n {\n name: 'libredns',\n endpoint: {\n protocol: 'https:',\n host: 'doh.libredns.gr'\n },\n description: 'DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\\nhttps://libredns.gr/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'nextdns',\n endpoint: {\n protocol: 'https:',\n host: 'anycsast.dns.nextdns.io'\n },\n 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/',\n country: 'Netherlands',\n location: {\n lat: 52.3891,\n long: 4.6563\n }\n },\n {\n name: 'nextdns-ultralow',\n endpoint: {\n protocol: 'https:',\n host: 'dns.nextdns.io',\n path: '/dnscrypt-proxy'\n },\n 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.'\n },\n {\n name: 'njalla-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.njal.la',\n cors: true\n },\n description: 'Non-logging DoH server in Sweden operated by Njalla.\\nhttps://dns.njal.la/',\n country: 'Sweden',\n location: {\n lat: 59.3247,\n long: 18.056\n },\n cors: true\n },\n {\n name: 'odoh-cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare ODoH server.\\nhttps://cloudflare.com',\n cors: true\n },\n {\n name: 'odoh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.crypto.sx',\n cors: true\n },\n description: 'ODoH target server. Anycast, no logs.\\nBackend hosted by Scaleway. Maintained by Frank Denis.',\n cors: true\n },\n {\n name: 'odoh-id-gmail',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. Based in Singapore, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'odoh-jp.tiar.app',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. no logs.'\n },\n {\n name: 'odoh-jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.'\n },\n {\n name: 'odoh-resolver4.dns.openinternet.io',\n endpoint: {\n protocol: 'https:',\n host: 'resolver4.dns.openinternet.io'\n },\n 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\"\n },\n {\n name: 'odoh-tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'publicarray-au2-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh-2.seby.io',\n cors: true\n },\n description: 'DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\\nMaintained by publicarray - https://dns.seby.io',\n country: 'Australia',\n location: {\n lat: -33.8591,\n long: 151.2002\n },\n cors: true\n },\n {\n name: 'puredns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'puredns.org',\n ipv4: '146.190.6.13',\n cors: true\n },\n description: 'Public uncensored DNS resolver in Singapore - https://puredns.org\\n** Only available in Indonesia and Singapore **',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'quad101',\n endpoint: {\n protocol: 'https:',\n host: 'dns.twnic.tw',\n cors: true\n },\n description: 'DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\\nhttps://101.101.101.101/index_en.html',\n cors: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns11.quad9.net',\n ipv4: '149.112.112.11'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns.quad9.net',\n ipv4: '149.112.112.112'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns12.quad9.net',\n ipv4: '9.9.9.12'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns10.quad9.net',\n ipv4: '149.112.112.10'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip6-port5053-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns9.quad9.net'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'safesurfer-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.safesurfer.io'\n },\n 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',\n filter: true,\n log: true\n },\n {\n name: 'sth-ads-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse-noads.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n },\n filter: true\n },\n {\n name: 'sth-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n }\n },\n {\n name: 'switch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.switch.ch'\n },\n description: 'Public DoH service provided by SWITCH in Switzerland\\nhttps://www.switch.ch\\nProvides protection against malware, but does not block ads.',\n filter: true\n },\n {\n name: 'uncensoreddns-dk-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'unicast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'uncensoreddns-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'anycast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'v.dnscrypt.uk-doh-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'v.dnscrypt.uk'\n },\n description: 'DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\\nhttps://www.dnscrypt.uk',\n country: 'United Kingdom',\n location: {\n lat: 51.4964,\n long: -0.1224\n }\n }\n ],\n time: 1654187067783\n}\n","import { Logger } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { query, wellknown } from \"dns-query\";\nconst log = new Logger(\"dns-over-https\");\nexport class DnsOverHttps {\n endpoints;\n retries;\n /**\n * Create new Dns-Over-Http DNS client.\n *\n * @param endpoints The endpoints for Dns-Over-Https queries;\n * Defaults to using dns-query's API..\n * @param retries Retries if a given endpoint fails.\n *\n * @throws {code: string} If DNS query fails.\n */\n static async create(endpoints, retries) {\n const _endpoints = endpoints ?? (await wellknown.endpoints(\"doh\"));\n return new DnsOverHttps(_endpoints, retries);\n }\n constructor(endpoints, retries = 3) {\n this.endpoints = endpoints;\n this.retries = retries;\n }\n /**\n * Resolves a TXT record\n *\n * @param domain The domain name\n *\n * @throws if the query fails\n */\n async resolveTXT(domain) {\n let answers;\n try {\n const res = await query({\n question: { type: \"TXT\", name: domain }\n }, {\n endpoints: this.endpoints,\n retries: this.retries\n });\n answers = res.answers;\n }\n catch (error) {\n log.error(\"query failed: \", error);\n throw new Error(\"DNS query failed\");\n }\n if (!answers)\n throw new Error(`Could not resolve ${domain}`);\n const data = answers.map((a) => a.data);\n const result = [];\n data.forEach((d) => {\n if (typeof d === \"string\") {\n result.push(d);\n }\n else if (Array.isArray(d)) {\n d.forEach((sd) => {\n if (typeof sd === \"string\") {\n result.push(sd);\n }\n else {\n result.push(bytesToUtf8(sd));\n }\n });\n }\n else {\n result.push(bytesToUtf8(d));\n }\n });\n return result;\n }\n}\n//# sourceMappingURL=dns_over_https.js.map","import { ENR } from \"@waku/enr\";\nimport { keccak256, verifySignature } from \"@waku/enr\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport base32 from \"hi-base32\";\nimport { fromString } from \"uint8arrays/from-string\";\nexport class ENRTree {\n static RECORD_PREFIX = ENR.RECORD_PREFIX;\n static TREE_PREFIX = \"enrtree:\";\n static BRANCH_PREFIX = \"enrtree-branch:\";\n static ROOT_PREFIX = \"enrtree-root:\";\n /**\n * Extracts the branch subdomain referenced by a DNS tree root string after verifying\n * the root record signature with its base32 compressed public key.\n */\n static parseAndVerifyRoot(root, publicKey) {\n if (!root.startsWith(this.ROOT_PREFIX))\n throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);\n const rootValues = ENRTree.parseRootValues(root);\n const decodedPublicKey = base32.decode.asBytes(publicKey);\n // The signature is a 65-byte secp256k1 over the keccak256 hash\n // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string\n // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)\n const signedComponent = root.split(\" sig\")[0];\n const signedComponentBuffer = utf8ToBytes(signedComponent);\n const signatureBuffer = fromString(rootValues.signature, \"base64url\").slice(0, 64);\n const isVerified = verifySignature(signatureBuffer, keccak256(signedComponentBuffer), new Uint8Array(decodedPublicKey));\n if (!isVerified)\n throw new Error(\"Unable to verify ENRTree root signature\");\n return rootValues.eRoot;\n }\n static parseRootValues(txt) {\n const matches = txt.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\\d+) sig=([^ ]+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree root entry\");\n matches.shift(); // The first entry is the full match\n const [eRoot, lRoot, seq, signature] = matches;\n if (!eRoot)\n throw new Error(\"Could not parse 'e' value from ENRTree root entry\");\n if (!lRoot)\n throw new Error(\"Could not parse 'l' value from ENRTree root entry\");\n if (!seq)\n throw new Error(\"Could not parse 'seq' value from ENRTree root entry\");\n if (!signature)\n throw new Error(\"Could not parse 'sig' value from ENRTree root entry\");\n return { eRoot, lRoot, seq: Number(seq), signature };\n }\n /**\n * Returns the public key and top level domain of an ENR tree entry.\n * The domain is the starting point for traversing a set of linked DNS TXT records\n * and the public key is used to verify the root entry record\n */\n static parseTree(tree) {\n if (!tree.startsWith(this.TREE_PREFIX))\n throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);\n const matches = tree.match(/^enrtree:\\/\\/([^@]+)@(.+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree tree entry\");\n matches.shift(); // The first entry is the full match\n const [publicKey, domain] = matches;\n if (!publicKey)\n throw new Error(\"Could not parse public key from ENRTree tree entry\");\n if (!domain)\n throw new Error(\"Could not parse domain from ENRTree tree entry\");\n return { publicKey, domain };\n }\n /**\n * Returns subdomains listed in an ENR branch entry. These in turn lead to\n * either further branch entries or ENR records.\n */\n static parseBranch(branch) {\n if (!branch.startsWith(this.BRANCH_PREFIX))\n throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);\n return branch.split(this.BRANCH_PREFIX)[1].split(\",\");\n }\n}\n//# sourceMappingURL=enrtree.js.map","import { Logger } from \"@waku/utils\";\nconst log = new Logger(\"discovery:fetch_nodes\");\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peers = [];\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && isNewPeer(peer, peers)) {\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n peers.push(peer);\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n return peers;\n}\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function* yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peerNodeIds = new Set();\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && peer.nodeId && !peerNodeIds.has(peer.nodeId)) {\n peerNodeIds.add(peer.nodeId);\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n yield peer;\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n}\nfunction isSatisfied(wanted, actual) {\n return (actual.relay >= wanted.relay &&\n actual.store >= wanted.store &&\n actual.filter >= wanted.filter &&\n actual.lightPush >= wanted.lightPush);\n}\nfunction isNewPeer(peer, peers) {\n if (!peer.nodeId)\n return false;\n for (const existingPeer of peers) {\n if (peer.nodeId === existingPeer.nodeId) {\n return false;\n }\n }\n return true;\n}\nfunction addCapabilities(node, total) {\n if (node.relay)\n total.relay += 1;\n if (node.store)\n total.store += 1;\n if (node.filter)\n total.filter += 1;\n if (node.lightPush)\n total.lightPush += 1;\n}\n/**\n * Checks if the proposed ENR [[node]] helps satisfy the [[wanted]] capabilities,\n * considering the [[actual]] capabilities of nodes retrieved so far..\n *\n * @throws If the function is called when the wanted capabilities are already fulfilled.\n */\nfunction helpsSatisfyCapabilities(node, wanted, actual) {\n if (isSatisfied(wanted, actual)) {\n throw \"Internal Error: Waku2 wanted capabilities are already fulfilled\";\n }\n const missing = missingCapabilities(wanted, actual);\n return ((missing.relay && node.relay) ||\n (missing.store && node.store) ||\n (missing.filter && node.filter) ||\n (missing.lightPush && node.lightPush));\n}\n/**\n * Return a [[Waku2]] Object for which capabilities are set to true if they are\n * [[wanted]] yet missing from [[actual]].\n */\nfunction missingCapabilities(wanted, actual) {\n return {\n relay: actual.relay < wanted.relay,\n store: actual.store < wanted.store,\n filter: actual.filter < wanted.filter,\n lightPush: actual.lightPush < wanted.lightPush\n };\n}\n//# sourceMappingURL=fetch_nodes.js.map","import { EnrDecoder } from \"@waku/enr\";\nimport { Logger } from \"@waku/utils\";\nimport { DnsOverHttps } from \"./dns_over_https.js\";\nimport { ENRTree } from \"./enrtree.js\";\nimport { fetchNodesUntilCapabilitiesFulfilled, yieldNodesUntilCapabilitiesFulfilled } from \"./fetch_nodes.js\";\nconst log = new Logger(\"discovery:dns\");\nexport class DnsNodeDiscovery {\n dns;\n _DNSTreeCache;\n _errorTolerance = 10;\n static async dnsOverHttp(dnsClient) {\n if (!dnsClient) {\n dnsClient = await DnsOverHttps.create();\n }\n return new DnsNodeDiscovery(dnsClient);\n }\n /**\n * Returns a list of verified peers listed in an EIP-1459 DNS tree. Method may\n * return fewer peers than requested if @link wantedNodeCapabilityCount requires\n * larger quantity of peers than available or the number of errors/duplicate\n * peers encountered by randomized search exceeds the sum of the fields of\n * @link wantedNodeCapabilityCount plus the @link _errorTolerance factor.\n */\n async getPeers(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n const peers = await fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context));\n log.info(\"retrieved peers: \", peers.map((peer) => {\n return {\n id: peer.peerId?.toString(),\n multiaddrs: peer.multiaddrs?.map((ma) => ma.toString())\n };\n }));\n return peers;\n }\n constructor(dns) {\n this._DNSTreeCache = {};\n this.dns = dns;\n }\n /**\n * {@inheritDoc getPeers}\n */\n async *getNextPeer(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n for await (const peer of yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context))) {\n yield peer;\n }\n }\n /**\n * Runs a recursive, randomized descent of the DNS tree to retrieve a single\n * ENR record as an ENR. Returns null if parsing or DNS resolution fails.\n */\n async _search(subdomain, context) {\n try {\n const entry = await this._getTXTRecord(subdomain, context);\n context.visits[subdomain] = true;\n let next;\n let branches;\n const entryType = getEntryType(entry);\n try {\n switch (entryType) {\n case ENRTree.ROOT_PREFIX:\n next = ENRTree.parseAndVerifyRoot(entry, context.publicKey);\n return await this._search(next, context);\n case ENRTree.BRANCH_PREFIX:\n branches = ENRTree.parseBranch(entry);\n next = selectRandomPath(branches, context);\n return await this._search(next, context);\n case ENRTree.RECORD_PREFIX:\n return EnrDecoder.fromString(entry);\n default:\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to search DNS tree ${entryType} at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n /**\n * Retrieves the TXT record stored at a location from either\n * this DNS tree cache or via DNS query.\n *\n * @throws if the TXT Record contains non-UTF-8 values.\n */\n async _getTXTRecord(subdomain, context) {\n if (this._DNSTreeCache[subdomain]) {\n return this._DNSTreeCache[subdomain];\n }\n // Location is either the top level tree entry host or a subdomain of it.\n const location = subdomain !== context.domain\n ? `${subdomain}.${context.domain}`\n : context.domain;\n const response = await this.dns.resolveTXT(location);\n if (!response.length)\n throw new Error(\"Received empty result array while fetching TXT record\");\n if (!response[0].length)\n throw new Error(\"Received empty TXT record\");\n // Branch entries can be an array of strings of comma delimited subdomains, with\n // some subdomain strings split across the array elements\n const result = response.join(\"\");\n this._DNSTreeCache[subdomain] = result;\n return result;\n }\n}\nfunction getEntryType(entry) {\n if (entry.startsWith(ENRTree.ROOT_PREFIX))\n return ENRTree.ROOT_PREFIX;\n if (entry.startsWith(ENRTree.BRANCH_PREFIX))\n return ENRTree.BRANCH_PREFIX;\n if (entry.startsWith(ENRTree.RECORD_PREFIX))\n return ENRTree.RECORD_PREFIX;\n return \"\";\n}\n/**\n * Returns a randomly selected subdomain string from the list provided by a branch\n * entry record.\n *\n * The client must track subdomains which are already resolved to avoid\n * going into an infinite loop b/c branch entries can contain\n * circular references. It’s in the client’s best interest to traverse the\n * tree in random order.\n */\nfunction selectRandomPath(branches, context) {\n // Identify domains already visited in this traversal of the DNS tree.\n // Then filter against them to prevent cycles.\n const circularRefs = {};\n for (const [idx, subdomain] of branches.entries()) {\n if (context.visits[subdomain]) {\n circularRefs[idx] = true;\n }\n }\n // If all possible paths are circular...\n if (Object.keys(circularRefs).length === branches.length) {\n throw new Error(\"Unresolvable circular path detected\");\n }\n // Randomly select a viable path\n let index;\n do {\n index = Math.floor(Math.random() * branches.length);\n } while (circularRefs[index]);\n return branches[index];\n}\n//# sourceMappingURL=dns.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { DNS_DISCOVERY_TAG } from \"@waku/interfaces\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\nimport { DEFAULT_BOOTSTRAP_TAG_NAME, DEFAULT_BOOTSTRAP_TAG_TTL, DEFAULT_BOOTSTRAP_TAG_VALUE, DEFAULT_NODE_REQUIREMENTS } from \"./constants.js\";\nimport { DnsNodeDiscovery } from \"./dns.js\";\nconst log = new Logger(\"peer-discovery-dns\");\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n */\nexport class PeerDiscoveryDns extends TypedEventEmitter {\n nextPeer;\n _started;\n _components;\n _options;\n constructor(components, options) {\n super();\n this._started = false;\n this._components = components;\n this._options = options;\n const { enrUrls } = options;\n log.info(\"Use following EIP-1459 ENR Tree URLs: \", enrUrls);\n }\n /**\n * Start discovery process\n */\n async start() {\n log.info(\"Starting peer discovery via dns\");\n this._started = true;\n await this.findPeers();\n }\n async findPeers() {\n if (!this.nextPeer) {\n let { enrUrls } = this._options;\n if (!Array.isArray(enrUrls))\n enrUrls = [enrUrls];\n const { wantedNodeCapabilityCount } = this._options;\n const dns = await DnsNodeDiscovery.dnsOverHttp();\n this.nextPeer = dns.getNextPeer.bind(dns, enrUrls, wantedNodeCapabilityCount);\n }\n for await (const peerEnr of this.nextPeer()) {\n if (!this._started) {\n return;\n }\n const { peerInfo, shardInfo } = peerEnr;\n if (!peerInfo) {\n continue;\n }\n const tagsToUpdate = {\n [DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._options.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._options.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n };\n let isPeerChanged = false;\n const isPeerExists = await this._components.peerStore.has(peerInfo.id);\n if (isPeerExists) {\n const peer = await this._components.peerStore.get(peerInfo.id);\n const hasBootstrapTag = peer.tags.has(DEFAULT_BOOTSTRAP_TAG_NAME);\n if (!hasBootstrapTag) {\n isPeerChanged = true;\n await this._components.peerStore.merge(peerInfo.id, {\n tags: tagsToUpdate\n });\n }\n }\n else {\n isPeerChanged = true;\n await this._components.peerStore.save(peerInfo.id, {\n tags: tagsToUpdate,\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n }\n if (isPeerChanged) {\n this.dispatchEvent(new CustomEvent(\"peer\", { detail: peerInfo }));\n }\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n this._started = false;\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return DNS_DISCOVERY_TAG;\n }\n}\nexport function wakuDnsDiscovery(enrUrls, wantedNodeCapabilityCount = DEFAULT_NODE_REQUIREMENTS) {\n return (components) => new PeerDiscoveryDns(components, { enrUrls, wantedNodeCapabilityCount });\n}\n//# sourceMappingURL=dns_discovery.js.map","import { proto_peer_exchange as proto } from \"@waku/proto\";\n/**\n * PeerExchangeRPC represents a message conforming to the Waku Peer Exchange protocol\n */\nexport class PeerExchangeRPC {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(params) {\n const { numPeers } = params;\n return new PeerExchangeRPC({\n query: {\n numPeers: numPeers\n },\n response: undefined\n });\n }\n /**\n * Encode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n encode() {\n return proto.PeerExchangeRPC.encode(this.proto);\n }\n /**\n * Decode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n static decode(bytes) {\n const res = proto.PeerExchangeRPC.decode(bytes);\n return new PeerExchangeRPC(res);\n }\n get query() {\n return this.proto.query;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=rpc.js.map","import { BaseProtocol } from \"@waku/core/lib/base_protocol\";\nimport { EnrDecoder } from \"@waku/enr\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { isDefined } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { PeerExchangeRPC } from \"./rpc.js\";\nexport const PeerExchangeCodec = \"/vac/waku/peer-exchange/2.0.0-alpha1\";\nconst log = new Logger(\"peer-exchange\");\n/**\n * Implementation of the Peer Exchange protocol (https://rfc.vac.dev/spec/34/)\n */\nexport class WakuPeerExchange extends BaseProtocol {\n /**\n * @param components - libp2p components\n */\n constructor(components, pubsubTopics) {\n super(PeerExchangeCodec, components, log, pubsubTopics);\n }\n /**\n * Make a peer exchange query to a peer\n */\n async query(params) {\n const { numPeers, peerId } = params;\n const rpcQuery = PeerExchangeRPC.createRequest({\n numPeers: BigInt(numPeers)\n });\n const peer = await this.components.peerStore.get(peerId);\n if (!peer) {\n return {\n peerInfos: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (err) {\n log.error(\"Failed to get stream\", err);\n return {\n peerInfos: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const res = await pipe([rpcQuery.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n try {\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const { response } = PeerExchangeRPC.decode(bytes);\n if (!response) {\n log.error(\"PeerExchangeRPC message did not contains a `response` field\");\n return {\n peerInfos: null,\n error: ProtocolError.EMPTY_PAYLOAD\n };\n }\n const peerInfos = await Promise.all(response.peerInfos\n .map((peerInfo) => peerInfo.enr)\n .filter(isDefined)\n .map(async (enr) => {\n return { ENR: await EnrDecoder.fromRLP(enr) };\n }));\n return {\n peerInfos,\n error: null\n };\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n peerInfos: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n }\n}\n/**\n *\n * @returns A function that creates a new peer exchange protocol\n */\nexport function wakuPeerExchange(pubsubTopics) {\n return (components) => new WakuPeerExchange(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange.js.map","import { CustomEvent, TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, encodeRelayShard, Logger } from \"@waku/utils\";\nimport { PeerExchangeCodec, WakuPeerExchange } from \"./waku_peer_exchange.js\";\nconst log = new Logger(\"peer-exchange-discovery\");\nconst DEFAULT_PEER_EXCHANGE_REQUEST_NODES = 10;\nconst DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS = 10 * 1000;\nconst DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags.PEER_EXCHANGE;\nconst DEFAULT_PEER_EXCHANGE_TAG_VALUE = 50;\nconst DEFAULT_PEER_EXCHANGE_TAG_TTL = 100_000_000;\nexport class PeerExchangeDiscovery extends TypedEventEmitter {\n components;\n peerExchange;\n options;\n isStarted;\n queryingPeers = new Set();\n queryAttempts = new Map();\n handleDiscoveredPeer = (event) => {\n const { protocols, peerId } = event.detail;\n if (!protocols.includes(PeerExchangeCodec) ||\n this.queryingPeers.has(peerId.toString()))\n return;\n this.queryingPeers.add(peerId.toString());\n this.startRecurringQueries(peerId).catch((error) => log.error(`Error querying peer ${error}`));\n };\n constructor(components, pubsubTopics, options = {}) {\n super();\n this.components = components;\n this.peerExchange = new WakuPeerExchange(components, pubsubTopics);\n this.options = options;\n this.isStarted = false;\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted) {\n return;\n }\n this.dispatchEvent(new CustomEvent(\"waku:peer-exchange:started\", { detail: true }));\n log.info(\"Starting peer exchange node discovery, discovering peers\");\n // might be better to use \"peer:identify\" or \"peer:update\"\n this.components.events.addEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n /**\n * Remove event listener\n */\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping peer exchange node discovery\");\n this.isStarted = false;\n this.queryingPeers.clear();\n this.components.events.removeEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return \"@waku/peer-exchange\";\n }\n startRecurringQueries = async (peerId) => {\n const peerIdStr = peerId.toString();\n const { queryInterval = DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS, maxRetries = DEFAULT_MAX_RETRIES } = this.options;\n log.info(`Querying peer: ${peerIdStr} (attempt ${this.queryAttempts.get(peerIdStr) ?? 1})`);\n await this.query(peerId);\n const currentAttempt = this.queryAttempts.get(peerIdStr) ?? 1;\n if (currentAttempt > maxRetries) {\n this.abortQueriesForPeer(peerIdStr);\n return;\n }\n setTimeout(() => {\n this.queryAttempts.set(peerIdStr, currentAttempt + 1);\n this.startRecurringQueries(peerId).catch((error) => {\n log.error(`Error in startRecurringQueries: ${error}`);\n });\n }, queryInterval * currentAttempt);\n };\n async query(peerId) {\n const { error, peerInfos } = await this.peerExchange.query({\n numPeers: DEFAULT_PEER_EXCHANGE_REQUEST_NODES,\n peerId\n });\n if (error) {\n log.error(\"Peer exchange query failed\", error);\n return { error, peerInfos: null };\n }\n for (const _peerInfo of peerInfos) {\n const { ENR } = _peerInfo;\n if (!ENR) {\n log.warn(\"No ENR in peerInfo object, skipping\");\n continue;\n }\n const { peerId, peerInfo, shardInfo } = ENR;\n if (!peerId || !peerInfo) {\n continue;\n }\n const hasPeer = await this.components.peerStore.has(peerId);\n if (hasPeer) {\n const { hasMultiaddrDiff, hasShardDiff } = await this.checkPeerInfoDiff(peerInfo, shardInfo);\n if (hasMultiaddrDiff || hasShardDiff) {\n log.info(`Peer ${peerId.toString()} has updated multiaddrs or shardInfo, updating`);\n if (hasMultiaddrDiff) {\n log.info(`Peer ${peerId.toString()} has updated multiaddrs, updating`);\n await this.components.peerStore.patch(peerId, {\n multiaddrs: peerInfo.multiaddrs\n });\n }\n if (hasShardDiff && shardInfo) {\n log.info(`Peer ${peerId.toString()} has updated shardInfo, updating`);\n await this.components.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n }));\n }\n continue;\n }\n }\n // update the tags for the peer\n await this.components.peerStore.save(peerId, {\n tags: {\n [DEFAULT_PEER_EXCHANGE_TAG_NAME]: {\n value: this.options.tagValue ?? DEFAULT_PEER_EXCHANGE_TAG_VALUE,\n ttl: this.options.tagTTL ?? DEFAULT_PEER_EXCHANGE_TAG_TTL\n }\n },\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n }),\n ...(peerInfo.multiaddrs && {\n multiaddrs: peerInfo.multiaddrs\n })\n });\n log.info(`Discovered peer: ${peerId.toString()}`);\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n }));\n }\n return { error: null, peerInfos };\n }\n abortQueriesForPeer(peerIdStr) {\n log.info(`Aborting queries for peer: ${peerIdStr}`);\n this.queryingPeers.delete(peerIdStr);\n this.queryAttempts.delete(peerIdStr);\n }\n async checkPeerInfoDiff(peerInfo, shardInfo) {\n const { id: peerId } = peerInfo;\n const peer = await this.components.peerStore.get(peerId);\n const existingMultiaddrs = peer.addresses.map((a) => a.multiaddr.toString());\n const newMultiaddrs = peerInfo.multiaddrs.map((ma) => ma.toString());\n const hasMultiaddrDiff = existingMultiaddrs.some((ma) => !newMultiaddrs.includes(ma));\n let hasShardDiff = false;\n const existingShardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (existingShardInfoBytes) {\n const existingShardInfo = decodeRelayShard(existingShardInfoBytes);\n if (existingShardInfo || shardInfo) {\n hasShardDiff =\n existingShardInfo.clusterId !== shardInfo?.clusterId ||\n existingShardInfo.shards.some((shard) => !shardInfo?.shards.includes(shard));\n }\n }\n return { hasMultiaddrDiff, hasShardDiff };\n }\n}\nexport function wakuPeerExchangeDiscovery(pubsubTopics) {\n return (components) => new PeerExchangeDiscovery(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange_discovery.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { CustomEvent } from \"@libp2p/interface\";\nimport { createFromJSON } from \"@libp2p/peer-id-factory\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { Tags } from \"@waku/interfaces\";\nimport { getWsMultiaddrFromMultiaddrs, Logger } from \"@waku/utils\";\nconst log = new Logger(\"peer-exchange-discovery\");\nexport const DEFAULT_LOCAL_TAG_NAME = Tags.LOCAL;\nconst DEFAULT_LOCAL_TAG_VALUE = 50;\nconst DEFAULT_LOCAL_TAG_TTL = 100_000_000;\nexport class LocalPeerCacheDiscovery extends TypedEventEmitter {\n components;\n options;\n isStarted;\n peers = [];\n constructor(components, options) {\n super();\n this.components = components;\n this.options = options;\n this.isStarted = false;\n this.peers = this.getPeersFromLocalStorage();\n }\n get [Symbol.toStringTag]() {\n return \"@waku/local-peer-cache-discovery\";\n }\n async start() {\n if (this.isStarted)\n return;\n log.info(\"Starting Local Storage Discovery\");\n this.components.events.addEventListener(\"peer:identify\", this.handleNewPeers);\n for (const { id: idStr, address } of this.peers) {\n const peerId = await createFromJSON({ id: idStr });\n if (await this.components.peerStore.has(peerId))\n continue;\n await this.components.peerStore.save(peerId, {\n multiaddrs: [multiaddr(address)],\n tags: {\n [this.options?.tagName ?? DEFAULT_LOCAL_TAG_NAME]: {\n value: this.options?.tagValue ?? DEFAULT_LOCAL_TAG_VALUE,\n ttl: this.options?.tagTTL ?? DEFAULT_LOCAL_TAG_TTL\n }\n }\n });\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: [multiaddr(address)]\n }\n }));\n }\n log.info(`Discovered ${this.peers.length} peers`);\n this.isStarted = true;\n }\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping Local Storage Discovery\");\n this.components.events.removeEventListener(\"peer:identify\", this.handleNewPeers);\n this.isStarted = false;\n this.savePeersToLocalStorage();\n }\n handleNewPeers = (event) => {\n const { peerId, listenAddrs } = event.detail;\n const websocketMultiaddr = getWsMultiaddrFromMultiaddrs(listenAddrs);\n const localStoragePeers = this.getPeersFromLocalStorage();\n const existingPeerIndex = localStoragePeers.findIndex((_peer) => _peer.id === peerId.toString());\n if (existingPeerIndex >= 0) {\n localStoragePeers[existingPeerIndex].address =\n websocketMultiaddr.toString();\n }\n else {\n localStoragePeers.push({\n id: peerId.toString(),\n address: websocketMultiaddr.toString()\n });\n }\n this.peers = localStoragePeers;\n this.savePeersToLocalStorage();\n };\n getPeersFromLocalStorage() {\n try {\n const storedPeersData = localStorage.getItem(\"waku:peers\");\n if (!storedPeersData)\n return [];\n const peers = JSON.parse(storedPeersData);\n return peers.filter(isValidStoredPeer);\n }\n catch (error) {\n log.error(\"Error parsing peers from local storage:\", error);\n return [];\n }\n }\n savePeersToLocalStorage() {\n try {\n localStorage.setItem(\"waku:peers\", JSON.stringify(this.peers));\n }\n catch (error) {\n log.error(\"Error saving peers to local storage:\", error);\n }\n }\n}\nfunction isValidStoredPeer(peer) {\n return (peer &&\n typeof peer === \"object\" &&\n typeof peer.id === \"string\" &&\n typeof peer.address === \"string\");\n}\nexport function wakuLocalPeerCacheDiscovery() {\n return (components, options) => new LocalPeerCacheDiscovery(components, options);\n}\n//# sourceMappingURL=index.js.map","export * from \"./is_defined.js\";\nexport * from \"./random_subset.js\";\nexport * from \"./group_by.js\";\nexport * from \"./to_async_iterator.js\";\nexport * from \"./is_size_valid.js\";\nexport * from \"./sharding/index.js\";\nexport * from \"./push_or_init_map.js\";\nexport * from \"./relay_shard_codec.js\";\nexport * from \"./delay.js\";\nexport function removeItemFromArray(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n }\n return arr;\n}\nexport function getWsMultiaddrFromMultiaddrs(addresses) {\n const wsMultiaddr = addresses.find((addr) => addr.toString().includes(\"ws\") || addr.toString().includes(\"wss\"));\n if (!wsMultiaddr) {\n throw new Error(\"No ws multiaddr found in the given addresses\");\n }\n return wsMultiaddr;\n}\n//# sourceMappingURL=index.js.map","import { noise } from \"@chainsafe/libp2p-noise\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { mplex } from \"@libp2p/mplex\";\nimport { ping } from \"@libp2p/ping\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { all as filterAll, wss } from \"@libp2p/websockets/filters\";\nimport { wakuMetadata } from \"@waku/core\";\nimport { DefaultNetworkConfig } from \"@waku/interfaces\";\nimport { derivePubsubTopicsFromNetworkConfig, Logger } from \"@waku/utils\";\nimport { createLibp2p } from \"libp2p\";\nimport { DefaultPingMaxInboundStreams, DefaultUserAgent } from \"../waku/index.js\";\nimport { defaultPeerDiscoveries } from \"./discovery.js\";\nconst log = new Logger(\"sdk:create\");\nexport async function defaultLibp2p(pubsubTopics, options, userAgent) {\n if (!options?.hideWebSocketInfo && process?.env?.NODE_ENV !== \"test\") {\n /* eslint-disable no-console */\n console.info(\"%cIgnore WebSocket connection failures\", \"background: gray; color: white; font-size: x-large\");\n console.info(\"%cWaku tries to discover peers and some of them are expected to fail\", \"background: gray; color: white; font-size: x-large\");\n /* eslint-enable no-console */\n }\n const metadataService = pubsubTopics\n ? { metadata: wakuMetadata(pubsubTopics) }\n : {};\n const filter = options?.filterMultiaddrs === false || process?.env?.NODE_ENV === \"test\"\n ? filterAll\n : wss;\n return createLibp2p({\n connectionManager: {\n minConnections: 1\n },\n transports: [webSockets({ filter: filter })],\n streamMuxers: [mplex()],\n connectionEncryption: [noise()],\n ...options,\n services: {\n identify: identify({\n agentVersion: userAgent ?? DefaultUserAgent\n }),\n ping: ping({\n maxInboundStreams: options?.pingMaxInboundStreams ?? DefaultPingMaxInboundStreams\n }),\n ...metadataService,\n ...options?.services\n }\n }); // TODO: make libp2p include it;\n}\nexport async function createLibp2pAndUpdateOptions(options) {\n const { networkConfig } = options;\n const pubsubTopics = derivePubsubTopicsFromNetworkConfig(networkConfig ?? DefaultNetworkConfig);\n log.info(\"Creating Waku node with pubsub topics\", pubsubTopics);\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(...defaultPeerDiscoveries(pubsubTopics));\n }\n if (options?.bootstrapPeers) {\n peerDiscovery.push(bootstrap({ list: options.bootstrapPeers }));\n }\n libp2pOptions.peerDiscovery = peerDiscovery;\n const libp2p = await defaultLibp2p(pubsubTopics, libp2pOptions, options?.userAgent);\n return { libp2p, pubsubTopics };\n}\n//# sourceMappingURL=libp2p.js.map","/**\n * @packageDocumentation\n *\n * Use the `createLibp2p` function to create a libp2p node.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n *\n * const node = await createLibp2p({\n * // ...other options\n * })\n * ```\n */\nimport { createLibp2pNode } from './libp2p.js';\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n *\n * The node will be started unless `start: false` is passed as an option.\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { tcp } from '@libp2p/tcp'\n * import { mplex } from '@libp2p/mplex'\n * import { noise } from '@chainsafe/libp2p-noise'\n * import { yamux } from '@chainsafe/libp2p-yamux'\n *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [yamux(), mplex()],\n * connectionEncryption: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p(options = {}) {\n const node = await createLibp2pNode(options);\n if (options.start !== false) {\n await node.start();\n }\n return node;\n}\n//# sourceMappingURL=index.js.map","import { WakuNode } from \"../waku/index.js\";\nimport { createLibp2pAndUpdateOptions } from \"./libp2p.js\";\n/**\n * Create a Waku node that uses Waku Light Push, Filter and Store to send and\n * receive messages, enabling low resource consumption.\n * Uses Waku Filter V2 by default.\n */\nexport async function createLightNode(options = {}) {\n const { libp2p, pubsubTopics } = await createLibp2pAndUpdateOptions(options);\n return new WakuNode(pubsubTopics, options, libp2p, {\n store: true,\n lightpush: true,\n filter: true\n });\n}\n//# sourceMappingURL=create.js.map","export function isStaticSharding(config) {\n return (\"clusterId\" in config && \"shards\" in config && !(\"contentTopics\" in config));\n}\nexport function isAutoSharding(config) {\n return \"contentTopics\" in config;\n}\n//# sourceMappingURL=type_guards.js.map","import { enrTree, wakuDnsDiscovery, wakuLocalPeerCacheDiscovery, wakuPeerExchangeDiscovery } from \"@waku/discovery\";\nexport function defaultPeerDiscoveries(pubsubTopics) {\n const dnsEnrTrees = [enrTree[\"SANDBOX\"], enrTree[\"TEST\"]];\n const discoveries = [\n wakuDnsDiscovery(dnsEnrTrees),\n wakuLocalPeerCacheDiscovery(),\n wakuPeerExchangeDiscovery(pubsubTopics)\n ];\n return discoveries;\n}\n//# sourceMappingURL=discovery.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var TelemetryType;\n(function (TelemetryType) {\n TelemetryType[\"LIGHT_PUSH_FILTER\"] = \"LightPushFilter\";\n})(TelemetryType || (TelemetryType = {}));\nvar TelemetryClient = /** @class */ (function () {\n function TelemetryClient(url, intervalPeriod) {\n if (intervalPeriod === void 0) { intervalPeriod = 5000; }\n this.url = url;\n this.intervalPeriod = intervalPeriod;\n this.queue = [];\n this.intervalId = null;\n this.requestId = 0;\n }\n TelemetryClient.prototype.push = function (messages) {\n var _a;\n (_a = this.queue).push.apply(_a, messages);\n };\n TelemetryClient.prototype.start = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n if (!this.intervalId) {\n this.intervalId = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {\n var success;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.queue.length > 0)) return [3 /*break*/, 2];\n return [4 /*yield*/, this.send(this.queue)];\n case 1:\n success = _a.sent();\n if (success) {\n console.log(\"Sent \", this.queue.length, \" telemetry logs\");\n this.queue = [];\n }\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n }); }, this.intervalPeriod);\n }\n return [2 /*return*/];\n });\n });\n };\n TelemetryClient.prototype.stop = function () {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n };\n TelemetryClient.prototype.send = function (messages) {\n return __awaiter(this, void 0, void 0, function () {\n var telemetryRequests, res, e_1;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!window.location.hostname.includes(\"lab.waku.org\")) {\n return [2 /*return*/];\n }\n telemetryRequests = messages.map(function (message) { return ({\n id: ++_this.requestId,\n telemetryType: message.type.toString(),\n telemetryData: message\n }); });\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, fetch(this.url, {\n method: \"POST\",\n body: JSON.stringify(telemetryRequests),\n })];\n case 2:\n res = _a.sent();\n if (res.status !== 201) {\n console.log(\"DEBUG: Error sending messages to telemetry service: \", res.status, res.statusText, res.json);\n return [2 /*return*/, false];\n }\n return [2 /*return*/, true];\n case 3:\n e_1 = _a.sent();\n console.log(\"DEBUG: Error sending messages to telemetry service\", e_1);\n return [2 /*return*/, false];\n case 4: return [2 /*return*/];\n }\n });\n });\n };\n return TelemetryClient;\n}());\nexport { TelemetryClient };\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var generateRandomNumber = function () {\n return Math.floor(Math.random() * 1000000);\n};\nexport var sha256 = function (number) { return __awaiter(void 0, void 0, void 0, function () {\n var encoder, data, buffer;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n encoder = new TextEncoder();\n data = encoder.encode(number.toString());\n return [4 /*yield*/, crypto.subtle.digest(\"SHA-256\", data)];\n case 1:\n buffer = _a.sent();\n return [2 /*return*/, Array.from(new Uint8Array(buffer))\n .map(function (b) { return b.toString(16).padStart(2, \"0\"); })\n .join(\"\")];\n }\n });\n}); };\nvar DEFAULT_EXTRA_DATA = { sdk: \"0.0.29-rc\" };\nexport var DEFAULT_EXTRA_DATA_STR = JSON.stringify(DEFAULT_EXTRA_DATA);\nexport var buildExtraData = function (node, peerId) { return __awaiter(void 0, void 0, void 0, function () {\n var extraData, peer, websocket;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n extraData = __assign({}, DEFAULT_EXTRA_DATA);\n return [4 /*yield*/, node.libp2p.peerStore.all()];\n case 1:\n peer = (_a.sent()).find(function (p) { return p.id.toString() === peerId; });\n if (!peer || peerId === node.libp2p.peerId.toString()) {\n return [2 /*return*/, JSON.stringify(extraData)];\n }\n websocket = peer\n .addresses\n .map(function (addr) { return addr.multiaddr.toString(); })\n .some(function (addr) { return addr.includes(\"ws\") || addr.includes(\"wss\"); });\n return [2 /*return*/, JSON.stringify(__assign(__assign({}, extraData), { peerId: peerId, websocket: websocket, enabledProtocols: peer.protocols }))];\n }\n });\n}); };\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { createLightNode, createEncoder, createDecoder, utils, } from \"@waku/sdk\";\nimport { createFromPrivKey } from \"@libp2p/peer-id-factory\";\nimport { unmarshalPrivateKey, generateKeyPairFromSeed } from \"@libp2p/crypto/keys\";\nimport { fromString } from \"uint8arrays\";\nimport { Type, Field } from \"protobufjs\";\nimport { TelemetryClient, TelemetryType, } from \"./telemetry_client\";\nimport { generateRandomNumber, sha256, buildExtraData, DEFAULT_EXTRA_DATA_STR } from \"./util\";\nvar DEFAULT_CONTENT_TOPIC = \"/js-waku-examples/1/message-ratio/utf8\";\nvar DEFAULT_PUBSUB_TOPIC = utils.contentTopicToPubsubTopic(DEFAULT_CONTENT_TOPIC);\nvar TELEMETRY_URL = process.env.TELEMETRY_URL || \"http://localhost:8080/waku-metrics\";\nvar ProtoSequencedMessage = new Type(\"SequencedMessage\")\n .add(new Field(\"hash\", 1, \"string\"))\n .add(new Field(\"total\", 2, \"uint64\"))\n .add(new Field(\"index\", 3, \"uint64\"))\n .add(new Field(\"sender\", 4, \"string\"));\nvar sequenceCompletedEvent = new CustomEvent(\"sequenceCompleted\");\nvar messageSentEvent = new CustomEvent(\"messageSent\");\nvar messageReceivedEvent = new CustomEvent(\"messageReceived\");\nvar wakuNode = function () { return __awaiter(void 0, void 0, void 0, function () {\n var seed, privateKey, _a, _b;\n var _c, _d;\n return __generator(this, function (_e) {\n switch (_e.label) {\n case 0:\n seed = localStorage.getItem(\"seed\");\n if (!!seed) return [3 /*break*/, 2];\n return [4 /*yield*/, sha256(generateRandomNumber())];\n case 1:\n seed = (_e.sent()).slice(0, 32);\n localStorage.setItem(\"seed\", seed);\n _e.label = 2;\n case 2: return [4 /*yield*/, generateKeyPairFromSeed(\"Ed25519\", fromString(seed))];\n case 3:\n privateKey = _e.sent();\n _a = createLightNode;\n _c = {\n networkConfig: {\n contentTopics: [DEFAULT_CONTENT_TOPIC],\n },\n numPeersToUse: 2,\n defaultBootstrap: true\n };\n _d = {};\n _b = createFromPrivKey;\n return [4 /*yield*/, unmarshalPrivateKey(privateKey.bytes)];\n case 4: return [4 /*yield*/, _b.apply(void 0, [_e.sent()])];\n case 5: return [4 /*yield*/, _a.apply(void 0, [(_c.libp2p = (_d.peerId = _e.sent(),\n _d),\n _c)])];\n case 6: return [2 /*return*/, _e.sent()];\n }\n });\n}); };\nexport function app(telemetryClient) {\n return __awaiter(this, void 0, void 0, function () {\n var node, peerId, encoder, startLightPushSequence, startFilterSubscription;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, wakuNode()];\n case 1:\n node = _a.sent();\n window.waku = node;\n console.log(\"DEBUG: your peer ID is:\", node.peerId.toString());\n return [4 /*yield*/, node.start()];\n case 2:\n _a.sent();\n return [4 /*yield*/, node.waitForPeers()];\n case 3:\n _a.sent();\n peerId = node.libp2p.peerId.toString();\n encoder = createEncoder({\n contentTopic: DEFAULT_CONTENT_TOPIC,\n });\n node.libp2p.addEventListener(\"peer:discovery\", function (event) { return __awaiter(_this, void 0, void 0, function () {\n var discoveredPeerId, timestamp, extraData, hash;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n discoveredPeerId = event.detail.id.toString();\n timestamp = Math.floor(new Date().getTime() / 1000);\n return [4 /*yield*/, buildExtraData(node, discoveredPeerId)];\n case 1:\n extraData = _a.sent();\n return [4 /*yield*/, sha256(\"\".concat(peerId, \"-\").concat(discoveredPeerId, \"-\").concat(timestamp))];\n case 2:\n hash = _a.sent();\n telemetryClient.push([\n {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"discovery\",\n timestamp: timestamp,\n createdAt: timestamp,\n seenTimestamp: timestamp,\n peerId: peerId,\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false,\n messageHash: hash,\n errorMessage: \"\",\n extraData: extraData,\n },\n ]);\n return [2 /*return*/];\n }\n });\n }); });\n startLightPushSequence = function (numMessages_1) {\n var args_1 = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args_1[_i - 1] = arguments[_i];\n }\n return __awaiter(_this, __spreadArray([numMessages_1], args_1, true), void 0, function (numMessages, period) {\n var sequenceHash, sequenceTotal, sequenceIndex, sendMessage;\n var _this = this;\n if (period === void 0) { period = 3000; }\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, sha256(generateRandomNumber())];\n case 1:\n sequenceHash = _a.sent();\n sequenceTotal = numMessages;\n sequenceIndex = 0;\n sendMessage = function () { return __awaiter(_this, void 0, void 0, function () {\n var messageHash_1, timestamp_1, message, payload, result, successEvents, failureEvents, events, messageElement, messagesSent, error_1;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 4, , 5]);\n return [4 /*yield*/, sha256(\"\".concat(sequenceHash, \"-\").concat(sequenceIndex, \"-\").concat(sequenceTotal))];\n case 1:\n messageHash_1 = _a.sent();\n timestamp_1 = Math.floor(new Date().getTime() / 1000);\n message = ProtoSequencedMessage.create({\n hash: messageHash_1,\n seqHash: sequenceHash,\n total: sequenceTotal,\n index: sequenceIndex,\n sender: peerId,\n });\n payload = ProtoSequencedMessage.encode(message).finish();\n return [4 /*yield*/, node.lightPush.send(encoder, {\n payload: payload,\n timestamp: new Date(),\n }, { autoRetry: true })];\n case 2:\n result = _a.sent();\n console.log(\"DEBUG: light push successes: \", result.successes.length, result.successes.map(function (p) { return p.toString(); }));\n console.log(\"DEBUG: light push failures: \", result.failures.length, result.failures.map(function (f) { var _a; return ({ error: f.error, peerId: (_a = f === null || f === void 0 ? void 0 : f.peerId) === null || _a === void 0 ? void 0 : _a.toString() }); }));\n successEvents = result\n .successes\n .map(function (peerId) { return __awaiter(_this, void 0, void 0, function () {\n var extraData;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, buildExtraData(node, peerId.toString())];\n case 1:\n extraData = _a.sent();\n return [2 /*return*/, {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"lightPush\",\n timestamp: timestamp_1,\n createdAt: timestamp_1,\n seenTimestamp: timestamp_1,\n peerId: peerId.toString(),\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false,\n messageHash: messageHash_1,\n errorMessage: \"\",\n extraData: extraData,\n }];\n }\n });\n }); });\n failureEvents = result\n .failures\n .map(function (fail) { return __awaiter(_this, void 0, void 0, function () {\n var extraData;\n var _a, _b;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0: return [4 /*yield*/, buildExtraData(node, (_a = fail === null || fail === void 0 ? void 0 : fail.peerId) === null || _a === void 0 ? void 0 : _a.toString())];\n case 1:\n extraData = _c.sent();\n return [2 /*return*/, {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"lightPush\",\n timestamp: timestamp_1,\n createdAt: timestamp_1,\n seenTimestamp: timestamp_1,\n peerId: (_b = fail === null || fail === void 0 ? void 0 : fail.peerId) === null || _b === void 0 ? void 0 : _b.toString(),\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false,\n messageHash: messageHash_1,\n errorMessage: fail.error.toString(),\n extraData: extraData,\n }];\n }\n });\n }); });\n return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], successEvents, true), failureEvents, true))];\n case 3:\n events = _a.sent();\n if (events.length > 0) {\n telemetryClient.push(events);\n }\n if (result.successes.length > 0) {\n messageElement = document.createElement(\"div\");\n messagesSent = document.getElementById(\"messagesSent\");\n messageElement.textContent = \"Message: \".concat(messageHash_1, \" \").concat(sequenceIndex, \" of \").concat(sequenceTotal);\n messagesSent.insertBefore(messageElement, messagesSent.firstChild);\n messagesSent.insertBefore(document.createElement(\"br\"), messagesSent.firstChild);\n document.dispatchEvent(messageSentEvent);\n // Increment sequence\n sequenceIndex++;\n }\n if (sequenceIndex < sequenceTotal) {\n setTimeout(sendMessage, period); // Schedule the next send\n }\n else {\n document.dispatchEvent(sequenceCompletedEvent);\n }\n return [3 /*break*/, 5];\n case 4:\n error_1 = _a.sent();\n console.error(\"DEBUG: Error sending message\", error_1);\n return [3 /*break*/, 5];\n case 5: return [2 /*return*/];\n }\n });\n }); };\n sendMessage(); // Start the recursive sending\n return [2 /*return*/];\n }\n });\n });\n };\n startFilterSubscription = function () { return __awaiter(_this, void 0, void 0, function () {\n var decoder, messagesReceived, subscriptionCallback, result, errorEvent, timestamp, _a, _b, failEvents, successEvents, resolvedEvents, events;\n var _c;\n var _this = this;\n return __generator(this, function (_d) {\n switch (_d.label) {\n case 0:\n decoder = createDecoder(DEFAULT_CONTENT_TOPIC);\n messagesReceived = document.getElementById(\"messagesReceived\");\n subscriptionCallback = function (message) { return __awaiter(_this, void 0, void 0, function () {\n var decodedMessage, extraData, timestamp, messageElement;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n decodedMessage = ProtoSequencedMessage.decode(message.payload);\n // Don't bother reporting messages sent by this same node\n if (decodedMessage.sender === peerId) {\n return [2 /*return*/];\n }\n return [4 /*yield*/, buildExtraData(node, decodedMessage.sender)];\n case 1:\n extraData = _a.sent();\n timestamp = Math.floor(new Date().getTime() / 1000);\n telemetryClient.push([\n {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"filter\",\n timestamp: timestamp,\n createdAt: Math.floor(message.timestamp.getTime() / 1000),\n seenTimestamp: timestamp,\n peerId: peerId,\n contentTopic: message.contentTopic,\n pubsubTopic: message.pubsubTopic,\n ephemeral: message.ephemeral,\n messageHash: decodedMessage.hash,\n errorMessage: \"\",\n extraData: extraData,\n },\n ]);\n messageElement = document.createElement(\"div\");\n messageElement.textContent = \"Message: \".concat(decodedMessage.hash, \" \").concat(decodedMessage.index, \" of \").concat(decodedMessage.total);\n messagesReceived.appendChild(messageElement);\n messagesReceived.appendChild(document.createElement(\"br\"));\n document.dispatchEvent(messageReceivedEvent);\n return [2 /*return*/];\n }\n });\n }); };\n return [4 /*yield*/, node.filter.subscribe(decoder, subscriptionCallback, {}, { enableLightPushFilterCheck: true })];\n case 1:\n result = _d.sent();\n errorEvent = [];\n if (!result.error) return [3 /*break*/, 3];\n timestamp = Math.floor(new Date().getTime() / 1000);\n _b = (_a = errorEvent).push;\n _c = {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"filterCreateSubscription\",\n timestamp: timestamp,\n createdAt: timestamp,\n seenTimestamp: timestamp,\n peerId: peerId,\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false\n };\n return [4 /*yield*/, sha256(generateRandomNumber())];\n case 2:\n _b.apply(_a, [(_c.messageHash = _d.sent(),\n _c.errorMessage = result.error,\n _c.extraData = DEFAULT_EXTRA_DATA_STR,\n _c)]);\n _d.label = 3;\n case 3:\n failEvents = result.results.failures.map(function (fail) { return __awaiter(_this, void 0, void 0, function () {\n var extraData, timestamp;\n var _a;\n var _b, _c;\n return __generator(this, function (_d) {\n switch (_d.label) {\n case 0: return [4 /*yield*/, buildExtraData(node, (_b = fail === null || fail === void 0 ? void 0 : fail.peerId) === null || _b === void 0 ? void 0 : _b.toString())];\n case 1:\n extraData = _d.sent();\n timestamp = Math.floor(new Date().getTime() / 1000);\n _a = {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"filterCreateSubscription\",\n timestamp: timestamp,\n createdAt: timestamp,\n seenTimestamp: timestamp,\n peerId: (_c = fail === null || fail === void 0 ? void 0 : fail.peerId) === null || _c === void 0 ? void 0 : _c.toString(),\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false\n };\n return [4 /*yield*/, sha256(generateRandomNumber())];\n case 2: return [2 /*return*/, (_a.messageHash = _d.sent(),\n _a.errorMessage = fail.error,\n _a.extraData = extraData,\n _a)];\n }\n });\n }); });\n successEvents = result.results.successes.map(function (peerId) { return __awaiter(_this, void 0, void 0, function () {\n var extraData, timestamp;\n var _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, buildExtraData(node, peerId.toString())];\n case 1:\n extraData = _b.sent();\n timestamp = Math.floor(new Date().getTime() / 1000);\n _a = {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"filterCreateSubscription\",\n timestamp: timestamp,\n createdAt: timestamp,\n seenTimestamp: timestamp,\n peerId: peerId.toString(),\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false\n };\n return [4 /*yield*/, sha256(generateRandomNumber())];\n case 2: return [2 /*return*/, (_a.messageHash = _b.sent(),\n _a.errorMessage = \"\",\n _a.extraData = extraData,\n _a)];\n }\n });\n }); });\n return [4 /*yield*/, Promise.all(__spreadArray(__spreadArray([], failEvents, true), successEvents, true))];\n case 4:\n resolvedEvents = _d.sent();\n events = __spreadArray(__spreadArray([], errorEvent, true), resolvedEvents, true);\n if (events.length > 0) {\n telemetryClient.push(events);\n }\n return [2 /*return*/];\n }\n });\n }); };\n return [2 /*return*/, {\n node: node,\n startLightPushSequence: startLightPushSequence,\n startFilterSubscription: startFilterSubscription,\n }];\n }\n });\n });\n}\n(function () { return __awaiter(void 0, void 0, void 0, function () {\n function startSequence() {\n var numMessages = Math.floor(Math.random() * 16) + 5;\n var messagePeriod = Math.floor(Math.random() * 2001) + 5000;\n startLightPushSequence(numMessages, messagePeriod);\n }\n var telemetryClient, _a, node, startLightPushSequence, startFilterSubscription, peerIDBlock, runningScreen, sentMessagesCount, sentMessagesCounter, receivedMessagesCount, receivedMessagesCounter;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n telemetryClient = new TelemetryClient(TELEMETRY_URL, 5000);\n return [4 /*yield*/, app(telemetryClient)];\n case 1:\n _a = _b.sent(), node = _a.node, startLightPushSequence = _a.startLightPushSequence, startFilterSubscription = _a.startFilterSubscription;\n peerIDBlock = document.getElementById(\"peerID\");\n peerIDBlock.innerText = node.libp2p.peerId.toString();\n runningScreen = document.getElementById(\"runningScreen\");\n runningScreen.style.display = \"block\";\n return [4 /*yield*/, telemetryClient.start()];\n case 2:\n _b.sent();\n startFilterSubscription();\n sentMessagesCount = 0;\n sentMessagesCounter = document.getElementById(\"numSent\");\n document.addEventListener(\"messageSent\", function () {\n sentMessagesCount++;\n sentMessagesCounter.textContent = sentMessagesCount.toString();\n });\n receivedMessagesCount = 0;\n receivedMessagesCounter = document.getElementById(\"numReceived\");\n document.addEventListener(\"messageReceived\", function () {\n receivedMessagesCount++;\n receivedMessagesCounter.textContent = receivedMessagesCount.toString();\n });\n document.addEventListener(sequenceCompletedEvent.type, function () { return startSequence(); });\n startSequence();\n return [2 /*return*/];\n }\n });\n}); })();\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","inquire","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","moduleName","mod","eval","e","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","formatArgs","useColors","namespace","humanize","diff","color","lastC","match","save","namespaces","storage","setItem","removeItem","error","load","r","getItem","process","env","DEBUG","window","type","__nwjs","navigator","userAgent","toLowerCase","m","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","v","message","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","self","curr","Date","ms","prev","coerce","unshift","format","formatter","selectColor","extend","defineProperty","enumerable","configurable","get","set","init","delimiter","newDebug","toNamespace","regexp","substring","default","stack","disable","names","map","skips","enable","RegExp","name","forEach","key","hash","abs","assign","obj","props","code","TypeError","_","ErrClass","create","getPrototypeOf","event_iterator_1","EventIterator","EventQueue","constructor","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","remove","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","result","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","Events","EE","context","once","addListener","emitter","listener","_events","_eventsCount","clearEvent","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","max","cache","_cache","update","clear","root","HI_BASE32_NO_NODE_JS","versions","node","global","COMMON_JS","HI_BASE32_NO_COMMON_JS","AMD","BASE32_ENCODE_CHAR","BASE32_DECODE_CHAR","blocks","throwInvalidUtf8","position","partial","substr","decodeAsBytes","base32Str","v1","v2","v3","v4","v5","v6","v7","v8","bytes","count","remain","asciiOnly","str","followingChars","toUtf8String","indexOf","input","notString","ArrayBuffer","encodeBytes","encodeAscii","encodeUtf8","asBytes","base32","electron","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","isArray","isView","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","formatMessage","empty","cloneArray","array","newArray","createOutputMethod","bits","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","s","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","w","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","reset","finalized","block","blockCount","byteCount","outputBlocks","extraBytes","isString","lastByteIndex","f","x","right","o","encodeString","strs","paddingBytes","zeros","finalize","hex","arrayBuffer","Uint32Array","digest","h","c0","c3","c4","c5","c6","c7","c8","c9","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","globalThis","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneOptionObject","mergeKeys","merged","config","merge","resultIndex","indices","k","filter","includes","option","d","plural","msAbs","isPlural","exec","parseFloat","parse","isFinite","long","fmtShort","library","_validBytes","isInteger","_x86Multiply","_x86Rotl","_x86Fmix","_x64Add","_x64Multiply","_x64Rotl","_x64LeftShift","_x64Xor","_x64Fmix","x86","hash32","seed","inputValidation","remainder","h1","k1","hash128","h2","h3","h4","k2","k3","k4","x64","murmurHash3","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","ip","ref","base","dmax","net","mask","maskLong","error1","bitmask","netLong","hostmask","first","last","broadcast","contains","lastLong","common","timeType","commonRe","json","nested","google","protobuf","Any","fields","type_url","id","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","kind","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","values","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","util","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","low","high","unsigned","toNumber","arrayDefault","hasKs2","_fieldsArray","group","types","defaults","basic","packed","rfield","required","missing","wireType","mapKey","genTypePartial","optional","ReflectionObject","className","Namespace","comment","comments","valuesOptions","reserved","fromJSON","enm","toJSON","toJSONOptions","keepComments","Boolean","add","isReservedId","isReservedName","allow_alias","Field","Type","ruleRe","isObject","defaultValue","Long","extensionField","declaringField","_packed","getOption","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","newBuffer","emptyObject","emptyArray","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","_configure","Type_","build","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","configure","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","toArray","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","define","ptr","part","resolveAll","lookup","filterTypes","parentAlreadyChecked","found","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","propName","opt","find","newValue","setProperty","newOpt","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","peek","skip","cmnt","head","isProto3","applyCase","camelCase","illegal","insideTryCatch","line","readString","readValue","acceptTypeRef","parseNumber","readRanges","target","acceptStrings","parseId","dummy","ifBlock","parseOption","parseInlineOptions","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseType","parseEnum","service","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseMapField","parseOneOf","extensions","endsWith","startsWith","lcFirst","ucFirst","parseGroup","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","LongBits","indexOutOfRange","writeLength","RangeError","create_array","Buffer","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skipType","BufferReader_","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","deferred","files","SYNC","resolvePath","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","parsed","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","isReserved","q","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","unescape","lastCommentLine","stringDelim","subject","setComment","isLeading","lineEmpty","leading","commentOffset","lines","trim","text","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","re","lastIndex","repeat","isDoc","isLeadingComment","expected","actual","ret","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","fork","ldelim","typeName","bake","safePropBackslashRe","safePropQuoteRe","toUpperCase","camelCaseRe","a","decorateRoot","decorateEnumIndex","dst","setProp","zero","zzEncode","zeroHash","from","fromString","toLong","fromHash","toHash","part0","part1","part2","src","newError","CustomError","captureStackTrace","pool","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","Op","noop","State","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength","BufferSourceConverter","isArrayBuffer","data","toArrayBuffer","byteOffset","toUint8Array","toView","isArrayBufferView","isBufferSource","isEqual","aView","bView","buffers","res","view","STRING_TYPE","HEX_REGEX","BASE64_REGEX","BASE64URL_REGEX","Utf8Converter","encodeURIComponent","uintArray","encodedString","decodeURIComponent","escape","Utf16Converter","littleEndian","dataView","DataView","getUint16","setUint16","Convert","isHex","isBase64","isBase64Url","ToString","enc","ToUtf8String","ToBinary","ToHex","ToBase64","ToBase64Url","FromString","FromUtf8String","FromBinary","FromHex","FromBase64","FromBase64Url","btoa","formatted","formatString","base64url","Base64Padding","DEFAULT_UTF8_ENCODING","stringLength","resultView","byte","hexString","ToUtf16String","FromUtf16String","padCount","__webpack_module_cache__","leafPrototypes","getProto","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","mode","__esModule","ns","def","current","getOwnPropertyNames","definition","toStringTag","N1","N2","N3","N4","N5","N6","N7","MSB","REST","encodingLength","MAX_SAFE_INTEGER","encodeUint8Array","decodeUint8Array","encodeUint8ArrayList","decodeUint8ArrayList","d8b","MAX_SAFE_NUMBER_INTEGER","BigInt","MIN_SAFE_NUMBER_INTEGER","MIN_SAFE_INTEGER","toBigInt","fromBigInt","negative","TWO_32","readFixed32End","Uint8ArrayReader","int64Number","int64String","uint64Number","uint64String","sint64Number","sint64String","fixed64Number","fixed64String","sfixed64Number","sfixed64String","decodeMessage","codec","opts","createReader","ALPHABET","BASE_MAP","xc","BASE","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","carry","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","prefixCodePoint","codePointAt","or","ComposedDecoder","decoders","left","Codec","baseX","alphabet","rfc4648","bitsPerChar","pad","out","codes","written","SyntaxError","base10","base16","base16upper","base2","alphabetBytesToChars","reduce","alphabetCharsToBytes","codePoint","base256emoji","byts","char","byt","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64urlpad","base8","identity","TextDecoder","TextEncoder","textEncoder","textDecoder","MSBALL","INT","MSB$1","REST$1","N8","N9","num","oldOffset","counter","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","async","crypto","subtle","link","version","cid","toStringV0","baseCache","toStringV1","WeakMap","Map","CID","asCID","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","equals","other","unknown","aa","bb","ii","for","encodeCID","cidSymbol","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","createCodec","ascii","latin1","bufferPool","Uint8ArrayWriter","writeVarint32","super","encodeMessage","lengthDelimited","CODEC_TYPES","RateLimitProof","WakuMessage","FilterRequest","MessagePush","FilterRpc","TopicOnlyMessage","FilterSubscribeRequest","PushRequest","PushResponse","WakuMessageKeyValue","PeerInfo","PeerExchangeQuery","PeerExchangeResponse","WakuMetadataRequest","WakuMetadataResponse","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","MaxLengthError","isDefined","groupByContentTopic","groupedDecoders","decs","contentTopic","wait","_codec","proof","merkleRoot","epoch","shareX","shareY","nullifier","rlnIdentifier","tag","payload","timestamp","meta","rateLimitProof","ephemeral","limits","ContentFilter","subscribe","topic","contentFilters","contentFilters$","messages","messages$","requestId","FilterSubscribeType","__FilterSubscribeTypeValues","filterSubscribeType","pubsubTopic","contentTopics","SUBSCRIBER_PING","FilterSubscribeResponse","statusCode","statusDesc","wakuMessage","isSuccess","info","PushRpc","messageHash","StoreQueryRequest","includeData","timeStart","timeEnd","messageHashes","paginationCursor","paginationForward","paginationLimit","StoreQueryResponse","enr","numPeers","peerInfos","peerInfos$","PeerExchangeRPC","query","clusterId","shards","number","isSafeInteger","lengths","outputLen","blockLen","exists","instance","checkFinished","destroyed","finished","arr","rotr","word","nextTick","asyncLoop","iters","tick","ts","now","toBytes","Hash","_cloneInto","toStr","hashCons","hashC","msg","tmp","bytesLength","getRandomValues","randomBytes","Maj","HashMD","padOffset","isLE","take","roundClean","digestInto","output","fill","setBigUint64","_32n","_u32_max","wh","wl","setUint32","oview","outLen","state","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","B","C","D","E","F","G","H","getUint32","W15","W2","s0","s1","T1","T2","Protocols","Tags","EPeersByDiscoveryEvents","EConnectionStateEvents","DNS_DISCOVERY_TAG","DefaultNetworkConfig","HealthStatus","bytesToUtf8","byteArrays","totalLength","acc","shardInfoToPubsubTopics","shardInfo","Set","contentTopicToPubsubTopic","application","pubsubTopicToSingleShardInfo","pubsubTopics","shard","pubsubTopicsToShardInfo","shardInfoSet","clusterIds","ensurePubsubTopicIsConfigured","configuredTopics","networkShards","generation","topicName","ensureValidContentTopic","dataview","getBigUint64","contentTopicToShardIndex","determinePubsubTopic","pubsubTopicShardInfo","singleShardInfoToPubsubTopic","decodeRelayShard","byteIndex","bitIndex","getUint8","numIndices","encodeRelayShard","setUint8","APP_NAME","Logger","_info","_warn","_error","createDebugNamespace","level","logger","OneMillion","DecodedMessage","proto","_rawTimestamp","metaSetter","toWire","toProtoObj","protoMessage","valueOf","createEncoder","fromWireToProtoObj","fromProtoObj","createDecoder","entry","arrays","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","iterator","append","prepend","prependAll","reverse","consume","trunc","beginInclusive","endExclusive","_subList","sublist","list","bufStart","sliceStartInBuf","sliceEndsInBuf","search","needle","M","rightmostPositions","Int32Array","lastPatIndex","getInt8","setInt8","getInt16","setInt16","getInt32","setInt32","getBigInt64","setBigInt64","getFloat32","setFloat32","getFloat64","setFloat64","fromUint8Arrays","thing","defaultEncoder","lengthLength","lengthBuf","encodeLength","lengthEncoder","maybeYield","single","InvalidMessageLengthError","InvalidDataLengthError","InvalidDataLengthLengthError","UnexpectedEOFError","ReadMode","defaultDecoder","LENGTH","dataLength","lengthDecoder","maxLengthLength","maxDataLength","dataLengthLength","onLength","DATA","onData","pDefer","promise","fromReader","FixedFIFO","top","btm","hwm","isEmpty","FIFO","splitLimit","calculateSize","AbortError","pushable","getNext","onNext","ended","onEnd","drain","bufferNext","objectMode","bufferError","queueMicrotask","throw","readableLength","onEmpty","signal","throwIfAborted","cancel","addEventListener","race","removeEventListener","_pushable","sources","syncSources","all","item","pipe","rest","isDuplex","duplex","isIterable","fns","sink","duplexPipelineFn","rawPipe","stream","sourceWrap","selectOpenConnection","connections","timeline","at","STREAM_LOCK_KEY","StreamManager","multicodec","getConnections","ongoingCreation","streamPool","handlePeerUpdateStreamPool","getStream","peer","peerId","scheduledStream","delete","getOpenStreamForCodec","lockStream","createStream","retries","connection","lastError","newStream","createStreamWithLock","detail","protocols","scheduleNewStream","streams","protocol","writeStatus","isStreamLocked","metadata","BaseProtocol","components","addLibp2pEventListener","removeLibp2pEventListener","streamManager","connectionManager","allPeers","peerStore","peers","getPeersForProtocol","connectedPeers","getPeers","maxBootstrapPeers","filteredPeers","bootstrapPeers","tags","BOOTSTRAP","nonBootstrapPeers","selectedPeers","randomIndex","random","randomPeer","filterPeersByDiscovery","sortedFilteredPeers","pingBytes","ping","sortPeersByLatency","randomUUID","rnds8","rng","byteToHex","rnds","unsafeStringify","FilterPushRpc","FilterSubscribeRpc","createSubscribeRequest","SUBSCRIBE","createUnsubscribeRequest","UNSUBSCRIBE","createUnsubscribeAllRequest","UNSUBSCRIBE_ALL","createSubscriberPingRequest","FilterCodecs","FilterCore","handleIncomingMessage","libp2p","handle","onRequest","maxInboundStreams","success","failure","GENERIC_FAIL","REMOTE_PEER_REJECTED","unsubscribe","NO_STREAM_AVAILABLE","unsubscribeRequest","unsubscribeAll","NO_RESPONSE","streamData","remotePeer","createRequest","LightPushCodec","LightPushCore","preparePushMessage","EMPTY_PAYLOAD","isWireSizeUnderCap","isMessageSizeUnderCap","SIZE_TOO_BIG","ENCODE_FAILED","preparationError","DECODE_FAILED","rlnErrorCase","rlnErrorMap","RLN_IDENTITY_MISSING","RLN_MEMBERSHIP_INDEX","RLN_LIMIT_MISSING","infoLowerCase","errorKey","RLN_PROOF_GENERATION","matchRLNErrorMessage","EmptyMessage","ONE_MILLION","getTime","StoreCodec","StoreCore","queryPerPage","queryOpts","currentCursor","storeQueryRequest","storeQueryResponse","errorMessage","decodedMessages","protoMsg","wire","TypedEventEmitter","EventTarget","dispatchEvent","safeDispatchEvent","CustomEvent","KeepAliveManager","relay","pingKeepAliveTimers","relayKeepAliveTimers","pingKeepAlive","pingPeriodSecs","relayKeepAlive","relayPeriodSecs","peerIdStr","interval","setInterval","services","intervals","scheduleRelayPings","clearInterval","stopAll","timer","connectionsExist","getMeshPeers","ConnectionManager","configuredPubsubTopics","static","keepAliveManager","dialAttemptsForPeer","dialErrorsForPeer","currentActiveParallelDialCount","pendingPeerDialQueue","isP2PNetworkConnected","isConnected","onLine","keepAliveOptions","instances","onEventHandlers","stopNetworkStatusListener","dropConnection","hangUp","getPeersByDiscovery","peersDiscovered","peersConnected","conn","peersDiscoveredByBootstrap","peersDiscoveredByPeerExchange","peersDiscoveredByLocal","peersConnectedByBootstrap","peersConnectedByPeerExchange","peersConnectedByLocal","getTagNamesForPeer","PEER_EXCHANGE","LOCAL","DISCOVERED","CONNECTED","maxDialAttemptsForPeer","maxBootstrapPeersAllowed","maxParallelDials","startEventListeners","dialPeerStorePeers","dialPromises","peerInfo","attemptDial","startPeerDiscoveryListener","startPeerConnectionListener","startPeerDisconnectionListener","startNetworkStatusListener","dialPeer","dialAttempt","dial","AggregateError","errors","processDialQueue","attemptDnsDiscovery","dnsDiscovery","findPeers","shouldDialPeer","dispatchDiscoveryEvent","PEER_CONNECT_BOOTSTRAP","PEER_CONNECT_PEER_EXCHANGE","setP2PNetworkConnected","setP2PNetworkDisconnected","dispatchWakuConnectionEvent","isPeerTopicConfigured","getPeerShardInfo","isPeerDialableBasedOnBootstrapStatus","some","tagName","isBootstrap","PEER_DISCOVERY_BOOTSTRAP","PEER_DISCOVERY_PEER_EXCHANGE","shardInfoBytes","CONNECTION_STATUS","HealthManager","health","overallStatus","Unhealthy","protocolStatuses","getInstance","getHealthStatus","getProtocolStatus","updateProtocolHealth","getNameFromMulticodec","MinimallyHealthy","SufficientlyHealthy","lastUpdate","updateOverallHealth","Filter","LightPush","Store","statuses","getHealthManager","MetadataCodec","Metadata","libp2pComponents","handshakesConfirmed","registrar","NO_PEER_AVAILABLE","encodedResponse","decodeMetadataResponse","savePeerShardInfo","confirmOrAttemptHandshake","encodedShardInfo","wakuMetadata","peerIdSymbol","isPeerId","parser","readAtomically","parseWith","peekChar","readChar","readGivenChar","readSeparator","sep","inner","readNumber","radix","maxDigits","allowZeroPrefix","maxBytes","digitCount","leadingChar","hasLeadingZero","maxValue","digit","readIPv4Addr","ix","readIPv6Addr","readGroups","groups","ipv4","headSize","headIp4","limit","tailSize","readIPAddr","isIPv4","new","isIPv6","isIP","isV4","isV6","sections","v4Buffer","argv","V","convertToString","ipBuff","ipString","bytes2ip","bytes2str","bytes2port","address","bytes2mh","addrBytes","portBytes","bytes2onion","bytes2mb","convertToBytes","ip2bytes","str2bytes","port2bytes","mh","mh2bytes","addr","port","portBuf","onion2bytes","onion32bytes","mbstr","mb","anybaseDecoder","mb2bytes","row","resolvable","createProtocol","bytesToMultiaddrParts","tuples","stringTuples","sizeForAddr","stringAddr","stringTuplesToString","tup","cleanPath","tuplesToBytes","inspect","DNS_CODES","NoAvailableResolverError","Multiaddr","stringToMultiaddrParts","isMultiaddr","toOptions","family","transport","host","zone","tcp","udp","ip4","ip6","dns6","ip6zone","protos","protoCodes","protoNames","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","p2p","tuple","pop","getPath","resolvableProto","resolver","resolvers","nodeAddress","isThinWaistAddress","E_CANCELED","Semaphore","_value","_cancelError","_queue","_weightedWaiters","acquire","weight","priority","task","findIndexFromEnd","_dispatchItem","runExclusive","callback_1","thisArg","_arguments","generator","release","P","fulfilled","step","rejected","waitForUnlock","_couldLockImmediately","insertSorted","isLocked","getValue","setValue","_dispatchQueue","_drainUnlockWaiters","previousValue","_newReleaser","called","waiters","waiter","queuedPriority","findIndex","predicate","Mutex","cancelError","_semaphore","releaser","PeerManager","core","healthManager","readMutex","writeMutex","writeLockHolder","getWriteLockHolder","addPeer","removePeer","getPeerCount","hasPeers","removeExcessPeers","excessPeers","peersToRemove","findAndAddPeers","additionalPeers","addMultiplePeers","addedPeers","BaseProtocolSDK","peerManager","numPeersToUse","maintainPeersIntervalId","maintainPeersInterval","startMaintainPeersInterval","renewPeer","peerToDisconnect","newPeer","stopMaintainPeersInterval","forceUseAllPeers","maxAttempts","attempts","maintainPeers","currentPeerCount","numPeersToAdd","finalPeerCount","DEFAULT_KEEP_ALIVE","DEFAULT_LIGHT_PUSH_FILTER_CHECK","DEFAULT_SUBSCRIBE_OPTIONS","keepAlive","enableLightPushFilterCheck","pubsubTopicBytes","contentTopicBytes","timestampBytes","bigIntTimestamp","numberToBytes","tryConvertTimestampToBytes","ReceiverReliabilityMonitor","getContentTopics","protocolSubscribe","sendLightPushMessage","receivedMessagesFormPeer","receivedMessages","scheduledVerification","verifiedPeers","peerFailures","maxPingFailures","peerRenewalLocks","renewAndSubscribePeer","setMaxPingFailures","handlePingResult","failures","notifyMessageReceived","buildMessageHash","notifyMessageSent","timeout","receivedAnyMessage","receivedTestMessage","shouldVerifyPeer","isPeerVerified","isVerificationPending","messageHashStr","ReliabilityMonitorManager","createReceiverMonitor","receiverMonitors","monitor","SubscriptionManager","lightPush","reliabilityMonitor","keepAliveTimeout","keepAliveInterval","subscriptionCallbacks","sendLightPushCheckMessage","pingsBeforePeerRenewed","decodersArray","TOPIC_DECODER_MISMATCH","successes","buildLightPushContentTopic","decodersGroupedByCT","promises","subscribeWithPeerVerification","results","allSettled","finalResult","handleResult","subscriptionCallback","startSubscriptionsMaintenance","stopSubscriptionsMaintenance","pingSpecificPeer","processIncomingMessage","decodePromises","dec","decoded","decodedMessage","any","pushMessage","promiseResult","reason","coreResult","startKeepAlivePings","startConnectionListener","stopKeepAlivePings","stopConnectionListener","connectionListener","activeSubscriptions","subscription","getActiveSubscription","protocolUseOptions","subscribeOptions","uniquePubsubTopics","getUniquePubsubTopics","INVALID_DECODER_TOPICS","createSubscription","autoRetry","setActiveSubscription","subscribeWithUnsubscribe","toSubscriptionIterator","receiver","iteratorOptions","isWithTimeout","timeoutMs","startTime","toAsyncIterator","DEFAULT_SEND_OPTIONS","TOPIC_NOT_CONFIGURED","getConnectedPeers","attemptRetries","peerIDs","queryGenerator","decodersAsMap","validateDecodersAndPubsubTopic","responseGenerator","queryWithOrderedCallback","processMessages","queryWithPromiseCallback","abort","page","_promises","msgPromise","processedMessages","createCursor","uniquePubsubTopicsInQuery","pubsubTopicForQuery","waitForConnectedPeer","metadataService","awaitTimeout","rejectReason","_resolve","WakuNode","store","protocolsEnabled","lightpush","wakuLightPush","wakuFilter","getProtocols","_protocols","mapToPeerIdOrMultiaddr","Relay","codecs","gossipSub","multicodecs","dialProtocol","waitForPeers","waku","getEnabledProtocols","isStarted","enabledCodes","protocolToCodec","mapProtocolsToCodecs","every","waitForMetadata","rejectOnTimeout","waitForRemotePeer","AggregateCodeError","ERR_TIMEOUT","isPromise","finally","U32_MASK64","fromBig","u64","lst","Ah","Al","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","Bh","Bl","add3L","Cl","add3H","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_0n","_1n","_2n","abool","title","padStart","numberToHexUnpadded","hexToNumber","_0","_9","_A","_F","_a","_f","hl","al","ai","n1","n2","expectedLength","sum","isPosBig","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reseed","sl","pred","validatorFns","bigint","function","boolean","stringOrUint8Array","Fp","isValid","validateObject","validators","optValidators","checkField","isOptional","checkVal","entries","memoized","arg","computed","_3n","_4n","_5n","_8n","power","modulo","pow2","invert","y","u","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","ORDER","redef","BYTES","sqrtP","p1div4","eql","sqr","mul","nv","sub","ONE","legendreC","Q","S","Z","Q1div2","neg","g","ZERO","t2","ge","tonelliShanks","FpSqrt","MASK","is0","isOdd","lhs","rhs","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","pointPrecomputes","pointWindowSizes","wNAF","constTimeNegate","condition","negate","validateW","W","windows","windowSize","unsafeLadder","elm","precomputeWindow","points","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFCached","transform","comp","setWindowSize","pippenger","scalars","buckets","lastBits","scalar","resI","sumI","validateBasic","curve","validateField","Gx","Gy","VERIFY_DEFAULT","zip215","ED25519_P","ED25519_SQRT_M1","ed25519_pow_2_252_3","_10n","_20n","_40n","_80n","b80","b160","b240","b250","pow_p_5_8","adjustScalarBytes","uvRatio","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","curveDef","CURVE","domain","mapToCurve","validateOpts","prehash","cHash","cofactor","modP","Fn","phflag","aCoordinate","assertPoint","Point","toAffineMemo","iz","ex","ey","ez","z","ax","ay","zz","assertValidMemo","X","Y","et","T","X2","Y2","Z2","Z4","aX2","toAffine","fromAffine","normalizeZ","toInv","msm","_setWindowSize","wnaf","assertValidity","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","subtract","multiply","CURVE_ORDER","multiplyUnsafe","I","isSmallOrder","isTorsionFree","clearCofactor","fromHex","normed","lastByte","y2","isXOdd","isLastByteOdd","fromPrivateKey","privKey","getExtendedPublicKey","point","toRawBytes","toHex","modN","modN_LE","hashed","pointBytes","hashDomainToScalar","msgs","verifyOpts","getPublicKey","R","sig","publicKey","SB","ExtendedPoint","utils","randomPrivateKey","precompute","x25519","montgomeryBits","powPminus2","Gu","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","getSharedSecret","privateKey","montgomery","PUBLIC_KEY_BYTE_LENGTH","PRIVATE_KEY_BYTE_LENGTH","KEYS_BYTE_LENGTH","concatKeys","privateKeyRaw","win","nativeCrypto","derivedEmptyPasswordKey","alg","ext","key_ops","kty","exporter","password","cipher","keyLength","iterations","encrypt","salt","nonce","aesGcm","iv","cryptoKey","importKey","deriveParams","runtimeDerivedEmptyPassword","deriveKey","rawKey","ciphertext","decrypt","saltLength","plaintext","encryptedKey","KeyType","__KeyTypeValues","PublicKey","PrivateKey","Data","Ed25519PublicKey","_key","ensureKey","marshal","Ed25519","Ed25519PrivateKey","_publicKey","public","unmarshalEd25519PrivateKey","privateKeyBytes","publicKeyBytes","unmarshalEd25519PublicKey","generateKeyPairFromSeed","pair","derivePublicFromPrivate","exportKey","jwKey","keySize","jwk","HMAC","iHash","oHash","hmac","utilFromBase","inputBuffer","inputBase","utilToBase","internalReserved","internalValue","biggest","retBuf","retView","basis","utilConcatView","views","outputLength","prevLength","utilDecodeTC","valueHex","condition1","condition2","warnings","bigIntBuffer","bigIntView","bigInt","smallIntBuffer","smallIntView","padNumber","inputNumber","fullLength","dif","assertBigInt","baseBlock","inputOffset","inputLength","ViewWriter","items","final","powers2","digitsString","EMPTY_BUFFER","EMPTY_VIEW","END_OF_CONTENT_NAME","OCTET_STRING_NAME","BIT_STRING_NAME","HexBlock","BaseClass","isHexOnly","valueHexView","fromBER","endLength","blockLength","toBER","sizeOnly","NAME","LocalBaseBlock","EMPTY_STRING","valueBeforeDecode","valueBeforeDecodeView","blockName","ValueBlock","LocalIdentificationBlock","idBlock","_b","_c","_d","tagClass","tagNumber","isConstructed","firstOctet","encodedBuf","encodedView","curView","inputView","intBuffer","tagNumberMask","intTagNumberBuffer","tagNumberBufferMaxLength","tempBufferView","LocalLengthBlock","lenBlock","isIndefiniteForm","longFormUsed","lenOffset","lengthBufferView","typeStore","BaseBlock","primitiveSchema","parameters","valueBlockType","valueBlock","resultOffset","_writer","prepareIndefiniteForm","idBlockBuf","valueBlockBuf","lenBlockBuf","onAsciiEncoding","inputBuffer1","inputBuffer2","view1","view2","Constructed","BaseStringBlock","stringValueBlockType","fromBuffer","LocalPrimitiveValueBlock","_a$w","_a$v","_a$u","_a$t","_a$s","_a$r","_a$q","_a$p","_a$o","_a$n","_a$m","_a$l","_a$k","_a$j","_a$i","_a$h","_a$g","_a$f","_a$e","_a$d","_a$c","_a$b","_a$a","_a$9","_a$8","_a$7","_a$6","_a$5","_a$4","_a$3","_a$2","_a$1","Primitive","localFromBER","incomingOffset","returnObject","newASN1Type","EndOfContent","Integer","BitString","OctetString","Null","ObjectIdentifier","Enumerated","Utf8String","RelativeObjectIdentifier","TIME","Sequence","NumericString","PrintableString","TeletexString","VideotexString","IA5String","UTCTime","GeneralizedTime","GraphicString","VisibleString","GeneralString","UniversalString","CharacterString","BmpString","DATE","TimeOfDay","DateTime","newObject","inputObject","newType","localChangeType","LocalConstructedValueBlock","currentOffset","LocalEndOfContentValueBlock","override","LocalBooleanValueBlock","octet","LocalOctetStringValueBlock","currentBlockName","asn","content","LocalBitStringValueBlock","unusedBits","bitsStr","viewAdd","second","firstView","secondView","firstViewCopy","firstViewCopyLength","secondViewCopy","secondViewCopyLength","power2","digits","viewSub","LocalIntegerValueBlock","_valueDec","setValueHex","valueDec","modValue","tempBuf","tempView","fromDER","toDER","updatedView","firstBit","currentByte","bitNumber","asn1View","flag","byteNumber","bigIntValue","secondInt","convertToDER","integer","convertFromDER","LocalSidValueBlock","isFirstSid","valueBigInt","sidValue","LocalObjectIdentifierValueBlock","sidBlock","retBuffers","valueBuf","pos1","pos2","sid","plus","parsedSID","sidStr","sidArray","LocalRelativeSidValueBlock","LocalRelativeObjectIdentifierValueBlock","LocalStringValueBlock","LocalSimpleStringValueBlock","LocalSimpleStringBlock","inputString","strLen","LocalUtf8StringValueBlock","LocalBmpStringValueBlock","LocalUniversalStringValueBlock","copyBuffer","valueView","strLength","codeBuf","codeView","valueDate","year","month","day","hour","minute","fromDate","toBuffer","inputDate","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","toDate","UTC","parserArray","outputArray","toISOString","millisecond","getUTCMilliseconds","isUTC","timeString","dateTimeString","fractionPart","hourDifference","minuteDifference","multiplier","differencePosition","differenceString","fractionPointPosition","fractionPartCheck","fractionResult","tempDate","getUTCDay","bnToBuf","bn","u8","bufToBn","exportToPem","keyBuf","keyArr","encryptionKey","dkLen","asyncTick","DK","PRF","PRFSalt","_password","_salt","_opts","checkOpts","pbkdf2Init","prfW","ti","Ti","pbkdf2Output","encrypted","pbkdf2Params","encryptionAlgorithm","finalWrapperBuf","MAX_RSA_KEY_SIZE","RsaPublicKey","der","RSA","RsaPrivateKey","genSecret","dp","dq","qi","unmarshalRsaPublicKey","fromJwk","generateKey","modulusLength","publicExponent","validateSigVerOpts","lowS","b2n","h2b","DER","Err","_tlv","dataLen","lenLen","lengthBytes","_int","toSig","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrass","bits2int","bits2int_modN","compressedLen","uncompressedLen","invN","ProjectivePoint","normPrivateKeyToScalar","weierstrassEquation","isWithinCurveOrder","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_isCompressed","x2","x3","N","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","t0","t1","t3","t4","t5","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","isCompressed","_bits","weierstrassPoints","cat","sqrtError","suffix","numToNByteStr","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","minLen","reduced","isProbPub","delta","ORDER_MASK","int2octets","defaultSigOpts","defaultVerOpts","privateA","publicB","k2sig","extraEntropy","ent","h1int","seedArgs","kBytes","ik","normS","prepSig","drbg","signature","sg","_sig","derError","is","getHash","secp256k1P","secp256k1N","divNearest","_6n","_11n","_22n","_23n","_44n","_88n","b88","b176","b220","b223","secp256k1","defHash","createCurve","POW_2_128","validatePublicKey","Secp256k1PublicKey","Secp256k1","Secp256k1PrivateKey","unmarshalSecp256k1PrivateKey","unmarshalSecp256k1PublicKey","supportedKeys","rsa","unsupportedKey","supported","typeToKey","marshalPublicKey","unmarshalRsaPrivateKey","serviceCapabilities","serviceDependencies","baseDecoder","PeerIdImpl","toCID","peerIdFromString","RSAPeerIdImpl","Ed25519PeerIdImpl","Secp256k1PeerIdImpl","TRANSPORT_IPFS_GATEWAY_HTTP_CODE","URLPeerIdImpl","url","peerIdFromBytes","URL","peerIdFromCID","peerIdFromKeys","raceSignal","aborted","errorCode","errorName","QueuelessPushable","readNext","haveNext","nextResult","byteStream","readBuffer","abortPromise","unwrap","originalStream","yieldBytes","lpStream","decodeLength","lengthBuffer","writeV","flatMap","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","copyBytes","wrapCipher","clean","_utf8ToBytes","sigma16","sigma32","sigma16_32","sigma32_32","MAX_COUNTER","U32_EMPTY","createCipher","allowShortKeys","extendNonceFn","counterLength","counterRight","rounds","toClean","sigma","k32","nonceNcLen","nc","n32","isAligned","d32","o32","pos32","posj","runCipher","u8to16","Poly1305","Uint16Array","t6","t7","isLast","hibit","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h5","h6","h7","h8","h9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","opos","poly1305","wrapConstructorWithKey","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","oi","chacha20","xchacha20","ZEROS16","updatePadded","ZEROS32","computeTag","AAD","authKey","_poly1305_aead","xorStream","plength","clength","passedTag","chacha20poly1305","blockSize","nonceLength","tagLength","HKDF_COUNTER","defaultCrypto","hashSHA256","getHKDF","ck","ikm","prk","extract","okm","HMACTmp","expand","generateX25519KeyPair","secretKey","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","chaCha20Poly1305Decrypt","uint16BEEncode","uint16BEDecode","logLocalStaticKeys","keyLogger","logLocalEphemeralKeys","logRemoteEphemeralKey","logCipherState","cs1","cs2","getUint64","Nonce","increment","getBytes","assertValue","ZEROLEN","CipherState","hasKey","encryptWithAd","decryptWithAd","SymmetricState","cs","protocolName","protocolNameBytes","hashProtocolName","mixKey","tempK","hkdf","mixHash","encryptAndHash","decryptAndHash","tempK1","tempK2","AbstractHandshakeState","ss","rs","initiator","prologue","writeE","generateKeypair","writeS","writeEE","dh","writeES","writeSE","readE","readS","cipherLength","temp","readEE","readES","readSE","XXHandshakeState","writeMessageA","writeMessageB","encS","writeMessageC","readMessageA","readMessageB","consumed","readMessageC","NoiseExtensions","NoiseHandshakePayload","createHandshakePayload","staticPublicKey","identitySig","getSignaturePayload","identityKey","decodeHandshakePayload","payloadBytes","remoteStaticKey","remoteIdentityKey","remoteIdentityKeyBytes","signaturePayload","webtransportCerthashes","Noise","staticKey","metrics","staticNoiseKey","prologueBytes","_crypto","keypair","wrapCrypto","xxHandshakeSuccesses","registerCounter","help","xxHandshakeErrors","encryptedPackets","decryptedPackets","decryptErrors","registerMetrics","secureOutbound","localPeer","parseArgs","wrappedConnection","handshake","performHandshakeInitiator","createSecureConnection","remoteExtensions","secureInbound","performHandshakeResponder","xx","trace","receivedPayload","forComponent","secure","user","duplexPair","network","encryptStream","decryptStream","noise","peerDiscoverySymbol","DNS4","DNS6","DNSADDR","DNS","IP","TCP","and","UDP","UTP","QUIC","QUICV1","_WebSockets","WebSockets","_WebSocketsSecure","WebSocketsSecure","HTTP","HTTPS","_WebRTCDirect","WebRTCDirect","_WebTransport","WebTransport","P2PWebRTCStar","P2PWebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","P2P","makeMatchesFunction","partialMatch","ma","matches","pnames","Bootstrap","_init","candidate","peerData","multiaddrs","_discoverBootstrapPeers","tagValue","ttl","tagTTL","clearTimeout","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","PeerRecord","AddressInfo","multiaddr","addresses","peerRecord","seqNumber","DOMAIN","CODEC","marshaled","localeCompare","arrayEquals","Envelope","payloadType","RecordEnvelope","envelopeData","record","signData","formatSignaturePayload","envelope","createFromProtobuf","validate","domainUint8Array","domainLength","payloadTypeLength","payloadLength","func","vals","pattern","literal","certhash","matcher","matchers","fmt","toParts","exactMatch","_DNS4","_DNS6","_DNSADDR","_DNS","_IP4","_IP6","_IP","_IP_OR_DOMAIN","IP_OR_DOMAIN","_TCP","_UDP","_QUIC","_QUICV1","QUIC_V0_OR_V1","_WEB","pbStream","lp","pb","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","signedPeerRecord","isEnvWithDom","nodeType","isElectron","isBrowser","isElectronMain","isElectronRenderer","isWebWorker","importScripts","WorkerGlobalScope","isReactNative","product","defaultValues","AbstractIdentify","started","addressManager","maxOutboundStreams","maxMessageSize","maxObservedAddresses","runOnTransientConnection","nodeInfo","protocolPrefix","AgentVersion","ProtocolVersion","handleProtocol","unhandle","runOnConnectionOpen","identify","_identify","AbortSignal","close","cleanObservedAddr","getCleanMultiaddr","getObservedAddrs","addObservedAddr","isCertified","peerRecordEnvelope","openAndCertify","existingPeer","storedEnvelope","storedRecord","patch","consumeIdentifyMessage","getAddresses","seal","remoteAddr","closeSource","getIterator","createAbortError","clearMethods","defaultClear","defaultSet","milliseconds","timeoutId","settle","rejectFunction","signalListener","delayPromise","createDelay","RateLimiter","memoryStorage","duration","blockDuration","execEvenly","execEvenlyMinDelayMs","keyPrefix","MemoryStorage","pointsToConsume","rlKey","getKey","secDuration","_getKeySecDuration","incrby","remainingPoints","consumedPoints","msBeforeNext","isFirstInDuration","delayMs","penalty","reward","msDuration","initPoints","customDuration","parseKey","durationSec","existing","msBeforeExpires","expiresAt","durationMs","unref","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","MAX_MSG_SIZE","_buffer","_headerInfo","_maxMessageSize","_maxUnprocessedMessageQueueSize","maxUnprocessedMessageQueueSize","_decodeHeader","readVarInt","POOL_SIZE","_pool","_poolOffset","header","AbstractStream","direction","readStatus","sinkController","sinkEnd","closed","endErr","streamSource","onCloseRead","onCloseWrite","onReset","onAbort","sendCloseWriteTimeout","sendingData","AbortController","onSourceEnd","sendNewStream","abortListener","sendData","sendCloseWrite","onSinkEnd","closeRead","closeWrite","sendCloseRead","sendReset","_closeSinkAndSource","_closeSink","_closeSource","remoteCloseWrite","remoteCloseRead","sourcePush","sourceReadableLength","MplexStream","streamId","maxDataSize","toSend","printMessage","MplexStreamMuxer","_streamId","_streams","_source","closeController","rateLimiter","closeTimeout","initiators","receivers","_createSink","disconnectThreshold","registry","_newStream","_newReceiverStream","maxMsgSize","onStreamEnd","_handleIncoming","onIncomingStream","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","mplex","ERR_WRONG_PING_ACK","PingService","handleMessage","received","openConnection","transportSymbol","FaultTolerance","ASSUME_HTTP_CODES","extractSNI","sniProtoCode","hasTLS","interpretNext","headProtoCode","headProtoVal","restMa","interpreter","interpreters","restVal","tailProto","dnsaddr","dns4","dns","ipfs","http","maHasTLS","sni","baseVal","tls","https","ws","wss","socket","cleanup","handleOpen","handleErr","closeOnEnd","ready","CLOSING","CLOSED","wasClean","connect","location","wsUrl","httpProto","wsProto","connectedSource","binaryType","connected","connError","cleanUp","cont","onOpen","onError","onMessage","remoteAddress","remotePort","hostname","CONNECTING","OPEN","terminate","websocket","CustomProgressEvent","Event","testMa","dialerEvents","registerCounterGroup","label","maConn","metricPrefix","socketToMaConn","_connect","upgrader","upgradeOutbound","cOpts","errorPromise","rawSocket","uri","onProgress","createListener","listenFilter","dialFilter","webSockets","contentRoutingSymbol","peerRoutingSymbol","fmtLong","isError","setupFormatters","defaultLogger","createDisabledLogger","mapIterable","iter","PeerSet","intersection","difference","union","createFromPrivKey","createFromJSON","pubKey","createFromPubKey","createFromParts","PeerMap","TimeoutError","getDOMException","DOMException","getAbortedReason","pTimeout","fallback","customTimers","cancelablePromise","POSITIVE_INFINITY","timeoutError","PriorityQueue","enqueue","run","element","it","lowerBound","dequeue","PQueue","carryoverConcurrencyCount","intervalCap","concurrency","autoStart","queueClass","throwOnTimeout","delay","canInitializeInterval","job","newConcurrency","function_","operation","addAll","functions","pause","onSizeLessThan","onIdle","sizeBy","observable","worker","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","identifier","MessageEvent","handler","postMessage","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","defaultOptions","singleProcess","mutexes","implementation","createReleaseable","Peer","Address","Tag","bytesToPeer","peerIdFromPeerId","expiry","Peer$metadataEntry","Peer$tagsEntry","pathSepS","pathSepB","pathSep","Key","_buf","uint8Array","withNamespaces","asKey","less","list1","list2","baseNamespace","namespaceType","namespaceValue","child","isAncestorOf","isDecendantOf","isTopLevel","NAMESPACE_COMMON","peerIdToDatastoreKey","b32key","dedupeFilterAndSortAddresses","addressMap","maStr","existingAddr","toPeerPB","strategy","createSortedMap","validateMetadata","validateTag","mapTag","metadataEntries","tagsEntries","mergedTags","addressFilter","decodePeer","cached","PersistentStore","datastore","lock","isWorker","readLock","writeLock","masterQueue","readQueue","localReadQueue","readPromise","createMutex","existingBuf","peerPb","peerCache","filters","orders","mapQuery","previous","updated","put","PersistentPeerStore","consumePeerRecord","expectedPeer","peekable","iterable","sorter","BaseDatastore","putMany","getMany","deleteMany","batch","puts","dels","commit","_all","_allKeys","queryKeys","MemoryDatastore","defaultAddressFilter","addrs","stripPeerId","observedPeerIdStr","DefaultAddressManager","announce","observed","announceFilter","_updatePeerStoreAddresses","debounce","getAnnounceAddrs","transportManager","getAddrs","confident","getListenAddrs","confirmObservedAddr","startingConfidence","removeObservedAddr","addrSet","DefaultComponents","_started","_invokeStartableMethod","isStartable","startable","beforeStart","afterStart","beforeStop","afterStop","OPTIONAL_SERVICES","NON_SERVICE_PROPERTIES","getServiceCapabilities","getServiceDependencies","getServiceName","NETMASK_RANGES","ipRange","ipv4Check","ipAddr","isPrivateIp","octet34","octet12","ipv4MappedIpv6Check","ipv4EmbeddedIpv6Check","ipv6Check","connectionGater","gater","denyDialPeer","denyDialMultiaddr","denyInboundConnection","denyOutboundConnection","denyInboundEncryptedConnection","denyOutboundEncryptedConnection","denyInboundUpgradedConnection","denyOutboundUpgradedConnection","filterMultiaddrForPeer","isPrivate","defaultAddressSort","publicResult","isAPrivate","isBPrivate","publicAddressesFirst","relayResult","isACircuit","isBCircuit","circuitRelayAddressesLast","certifiedResult","certifiedAddressesFirst","getTypes","DEFAULT_TYPES","RecordType","toDNSResponse","Status","TC","flag_tc","RD","flag_rd","RA","flag_ra","AD","flag_ad","CD","flag_cd","Question","questions","question","Answer","answers","answer","TTL","dnsJsonOverHttps","httpQueue","queryConcurrency","fqdn","searchParams","URLSearchParams","headers","accept","statusText","CachedAnswers","lru","maxSize","hashlru","foundAllAnswers","getAnswers","cachedAnswers","expires","cacheSize","tld","dnsaddrCode","RecursionLimitError","dnsaddrResolver","recursionLimit","maxRecursiveDepth","TXT","DefaultConfig","noAnnounce","addressSorter","faultTolerance","FATAL_ALL","getPeerAddress","ERR_INVALID_MULTIADDR","maPeerIdStr","ERR_INVALID_PARAMETERS","maPeerId","raceEvent","eventName","removeListeners","eventListener","errorEvent","errorEventListener","JobRecipient","Job","recipients","controller","created","recipient","Queue","metricName","registerMetricGroup","calculate","running","tryToStartAnother","toGenerator","onQueueJobComplete","onQueueError","onQueueIdle","onSignalAbort","PeerQueue","AUTO_DIAL_PEER_RETRY_THRESHOLD","LAST_DIAL_FAILURE_KEY","AutoDial","minConnections","autoDialPriority","autoDialIntervalMs","autoDialMaxQueueLength","autoDialPeerRetryThresholdMs","autoDialDiscoveredPeersDebounce","autoDialInterval","maxQueueLength","autoDialPeerRetryThreshold","autoDialConcurrency","autoDial","getConnectionsMap","numConnections","sheduleNextAutodial","dialQueue","getDialQueue","shuffledPeers","peerValues","peersThatHaveNotFailed","peerAValue","peerBValue","lastDialFailure","lastDialFailureTimestamp","DEFAULT_CLOSABLE_PROTOCOLS","maxConnections","allow","ConnectionPruner","maybePruneConnections","sortedConnections","sortConnections","toPrune","toClose","streamProtocols","closableProtocols","safelyCloseConnectionIfUnused","connectionALifespan","connectionBLifespan","anySignal","signals","maxDialQueueLength","maxPeerAddrsToDial","dialTimeout","DialQueue","shutDownController","peerIdOrMultiaddr","existingConnection","flat","force","existingDial","createDialAbortController","addrsToDial","calculateMultiaddrs","dialed","ERR_TOO_MANY_ADDRESSES","ERR_TRANSPORT_DIAL_FAILED","DEFAULT_DIAL_PRIORITY","userSignal","ERR_DIALED_SELF","ERR_PEER_DIAL_INTERCEPTED","ERR_NOT_FOUND","peerRouting","findPeer","ERR_NO_ROUTERS_AVAILABLE","resolvedAddresses","resolveMultiaddrs","peerIdMultiaddr","lastProto","filteredAddrs","dialTransportForMultiaddr","addrPeerId","dedupedAddrs","dedupedMultiaddrs","ERR_NO_VALID_ADDRESSES","gatedAdrs","sortedGatedAddrs","isDialable","DefaultConnectionManager","deny","maxIncomingPendingConnections","incomingPendingConnections","connectionPruner","inboundConnectionRateLimiter","onConnect","onDisconnect","inboundConnectionThreshold","metric","inbound","outbound","conns","allStreams","counts","keepAlivePeers","tasks","connectionList","_onConnect","storedConns","isNewPeer","storedConn","ERR_NODE_NOT_STARTED","transient","peerConnections","trackedConnection","closeConnections","acceptIncomingConnection","afterUpgradeInbound","statusMap","errored","complete","MovingAverage","movingAverage","variance","deviation","forecast","timespan","previousTime","alpha","pt","exp","time","incr","AdaptiveTimeout","timeoutMultiplier","failureMultiplier","minTimeout","getTimeoutSignal","timeoutFactor","sendTimeout","timeoutSignal","failureMovingAverage","failureDeviation","failureForecast","failureVariance","successMovingAverage","successDeviation","successForecast","successVariance","ConnectionMonitor","heartbeatInterval","pingIntervalMs","abortController","pingInterval","pingTimeout","bs","rtt","CompoundContentRouting","routers","findProviders","seen","router","provide","NOT_STARTED_YET","Fingerprint","fp","fingerprintSize","fnv","hashV","getRandomInt","Bucket","fingerprint","FNV_PRIMES","FNV_OFFSETS","cachedEncoder","utf8Buffer","fnvPrime","remaining","encodeInto","asUintN","fnv1aEncodeInto","fnv1aUint8Array","fnv1a","numberToBuffer","CuckooFilter","bucketSize","filterSize","rand","swapped","inJ","inK","reliable","MAX_LOAD","optimize","maxItems","errorRate","calculateBucketSize","log2","ScalableCuckooFilter","scale","filterSeries","cuckoo","curSize","DefaultPeerRouting","ERR_FIND_SELF","NOT_FOUND","getClosestPeers","createScalableCuckooFilter","ordered","ops","sourceErr","slotAvailable","resultAvailable","sourceFinished","opErred","valuesAvailable","op","yieldOrderedValues","ok","yieldUnOrderedValues","parallel","useCache","RandomWalk","walking","walkers","shutdownController","walkController","needNext","walk","startWalk","DefaultRegistrar","topologies","_onDisconnect","_onPeerUpdate","_onPeerIdentify","getHandler","ERR_NO_HANDLER_FOR_PROTOCOL","getTopologies","ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED","register","topology","unregister","removed","notifyOnTransient","TrackedMap","registerMetric","updateComponentMetric","deleted","DefaultTransportManager","transports","trackedMap","ERR_INVALID_KEY","ERR_DUPLICATE_TRANSPORT","ERR_TRANSPORT_UNAVAILABLE","getTransports","of","getListeners","listenTransportForMultiaddr","couldNotListen","supportedAddrs","NO_FATAL","removeAll","PROTOCOL_ID","MAX_PROTOCOL_LENGTH","NewLine","negotiateFully","originalSink","originalSource","negotiated","negotiating","doneNegotiating","sentProtocol","sendingProtocol","doneSendingProtocol","readProtocol","readingProtocol","doneReadingProtocol","negotiate","doSendProtocol","doReadProtocol","sentData","protocolString","originalCloseRead","originalCloseWrite","originalClose","optimisticSelect","p1","p2","connectionSymbol","ConnectionImpl","multiplexer","encryption","_close","_abort","_getStreams","getStreams","countStreams","streamCount","DefaultUpgrader","connectionEncryption","muxers","inboundUpgradeTimeout","encrypter","muxer","shouldBlockConnection","connectionType","ERR_CONNECTION_INTERCEPTED","upgradeInbound","ERR_CONNECTION_DENIED","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","trackMultiaddrConnection","protectedConn","skipProtection","protector","connectionProtector","protect","skipEncryption","_encryptInbound","idStr","remotePeerId","multiplexed","_multiplexInbound","_createConnection","_encryptOutbound","ERR_INVALID_PEER","_multiplexOutbound","muxedStream","incomingLimit","findIncomingStreamLimit","ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS","trackProtocolStream","_onStream","ERR_MUXER_UNAVAILABLE","outgoingLimit","findOutgoingStreamLimit","ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS","ERR_UNSUPPORTED_PROTOCOL","_timeline","Proxy","Reflect","upgraded","ERR_CONNECTION_NOT_MULTIPLEXED","ERR_ENCRYPTION_FAILED","Libp2pNode","contentRouting","originalDispatch","internalResult","externalResult","defaultComponents","configureComponent","streamMuxers","connectionMonitor","peerRouters","contentRouters","peerDiscovery","createService","capability","checkServiceDependencies","component","peerSet","ERR_INVALID_PROTOCOLS_FOR_STREAM","getMultiaddrs","peerKey","ERR_DISCOVERED_SELF","createLibp2pNode","generateKeyPair","createEd25519PeerId","resultingOptions","LIBP2P_FORCE_PNET","ERR_PROTECTOR_REQUIRED","validateConfig","DEFAULT_NODE_REQUIREMENTS","USE_ENDOMORPHISM","ShaError","assertJacPoint","JacobianPoint","toAffineBatch","scratch","Z1Z1","Z2Z2","S1","S2","x1b","HH","HHH","P0","normalizeScalar","affinePoint","_WINDOW_SIZE","invZ","iz1","iz2","iz3","fromCompressedHex","isShort","bytesToNumber","isValidFieldElement","rt","isYOdd","fromUncompressedHex","normalizePrivateKey","fromSignature","normalizeSignature","truncateHash","rinv","numTo32bStr","toHexX","toRawX","aP","bQ","sliceDER","parseDERInt","rBytesLeft","parseDERSignature","HALF","sHex","rHex","sHexL","rHexL","sLen","rLen","uint8a","POW_2_256","hexByte","truncateOnly","groupLen","bits2int_2","_sha256Sync","_hmacSha256Sync","HmacDrbg","hmacSha256","hmacSync","checkSync","reseedSync","generate","generateSync","kmdToSig","kinv","bits2octets","z1","vopts","strict","web","bytesToHex","hexToBytes","concatBytes","_bigintTo32Bytes","_normalizePrivateKey","hashToPrivateKey","sha256","createHash","ckey","createHmac","sha256Sync","hmacSha256Sync","taggedHash","tagP","tagH","taggedHashSync","_JacobianPoint","keccak256","sha3","verifySignature","normalizePublicKey","sinv","ERR_INVALID_ID","locationMultiaddrFromEnrFields","isIpv6","ipVal","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","encodeMultiaddrs","encodeWaku2","RawEnr","kvs","rsv","getStringValue","setStringValue","getNumberAsStringValue","setNumberAsStringValue","tcp6","udp6","raw","multiaddrBytes","decodeMultiaddrs","deleteUndefined","waku2","decodeWaku2","initSigArgs","canonical","recSig","recovered","finalizeSig","TransportProtocol","TransportProtocolPerIpVersion","createPeerIdFromPublicKey","nodeId","uncompressedPubkey","getLocationMultiaddr","setLocationMultiaddr","getAllLocationMultiaddrs","_multiaddrs","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","_permanentCensorErrors","_censorErrors","LogLevels","warning","_logLevel","_globalLogger","_normalizeError","form","_checkNormalize","LogLevel","ErrorCode","HEX","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","globalLogger","setCensorship","censorship","permanent","setLogLevel","isHexable","addSlice","arrayify","allowMissingPrefix","toHexString","isHexString","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","_decode","BUFFER_OVERRUN","EnrDecoder","encoded","RECORD_PREFIX","fromRLP","checkValues","_seq","decodeSeq","rlpEncodedBytes","checkSignature","fromValues","v4Regex","v6Regex","isFormat","buff","hexN","decN","prevColon","useDec","sizeOf","toType","rcode","opcode","klass","toClass","toCode","SURROGATE_A","SURROGATE_B","nextCode","numA","isU8Arr","bytelength","P_24","P_16","P_8","readUInt32BE","readUInt16BE","writeUInt32BE","writeUInt16BE","targetStart","sourceStart","sourceEnd","nb","sourceLen","_copyActual","consumedBytes","jumped","jumpOffset","flags","authorities","additionals","flag_qr","flag_aa","flag_z","runknown","dLen","rns","dd","rsoa","mname","rname","serial","refresh","retry","expire","minimum","rtxt","rnull","rhinfo","cpu","os","rptr","rsrv","rcaa","issuerCritical","ISSUER_CRITICAL","rmx","preference","exchange","ra","raaaa","roption","spl","sourcePrefixLength","fam","ipBuf","ipLen","scopePrefixLength","tagsLen","padded","ropt","rdlen","encodingLengthList","encodeList","rdnskey","keydata","PROTOCOL_DNSSEC","ZONE_KEY","SECURE_ENTRYPOINT","rrrsig","typeCovered","labels","originalTTL","expiration","inception","keyTag","signersName","rrp","mbox","txt","typebitmap","typelist","typesByWindow","typeid","windowBuf","windowLength","extents","rnsec","nextDomain","rrtypes","rnsec3","hashLength","rds","digestdata","digestType","renc","udpPayloadSize","extendedRcode","ednsVersion","class","flush","flag_do","packet","allocing","decodeList","sanitizeSingle","sanitized","make","charset","paddingMode","byCharCode","byNum","padCode","safeLen","safeEnd","base64URL","require","HTTPStatusError","endpoint","ResponseError","cause","reduceError","baseParts","httpFlags","updFlags","parseFlags","regex","InvalidProtocolError","supportedProtocols","BaseEndpoint","isHTTP","pk","UDPEndpoint","ipv6","UDP4Endpoint","UDP6Endpoint","safeHost","HTTPEndpoint","v6Parts","toEndpoint","post","parseEndpoint","contentType","requestRaw","abortSignal","setRequestHeader","ontimeout","onerror","onload","onabort","cors","endpoints","resolverByName","byName","endpointByName","backup","description","country","lat","UPDATE_URL","isNameString","wellknown","updateURL","persist","localStoragePrefix","maxAge","_dataP","_data","outdated","cacheKey","maxTime","filterDoh","filterDns","queryN","singleQuery","toMultiQuery","queryDoh","queryOne","DnsOverHttps","_endpoints","resolveTXT","sd","ENRTree","parseAndVerifyRoot","ROOT_PREFIX","rootValues","parseRootValues","decodedPublicKey","signedComponent","signedComponentBuffer","eRoot","lRoot","parseTree","tree","TREE_PREFIX","parseBranch","branch","BRANCH_PREFIX","isSatisfied","wanted","addCapabilities","total","helpsSatisfyCapabilities","missingCapabilities","DnsNodeDiscovery","_DNSTreeCache","_errorTolerance","dnsOverHttp","dnsClient","enrTreeUrls","wantedNodeCapabilityCount","networkIndex","visits","errorTolerance","getNode","maxSearches","totalSearches","fetchNodesUntilCapabilitiesFulfilled","_search","getNextPeer","peerNodeIds","yieldNodesUntilCapabilitiesFulfilled","subdomain","_getTXTRecord","branches","entryType","getEntryType","circularRefs","selectRandomPath","PeerDiscoveryDns","nextPeer","_components","_options","enrUrls","peerEnr","tagsToUpdate","isPeerChanged","wakuDnsDiscovery","PeerExchangeCodec","WakuPeerExchange","rpcQuery","ENR","DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS","DEFAULT_MAX_RETRIES","DEFAULT_PEER_EXCHANGE_TAG_NAME","PeerExchangeDiscovery","peerExchange","queryingPeers","queryAttempts","handleDiscoveredPeer","startRecurringQueries","queryInterval","maxRetries","currentAttempt","abortQueriesForPeer","_peerInfo","hasMultiaddrDiff","hasShardDiff","checkPeerInfoDiff","existingMultiaddrs","newMultiaddrs","existingShardInfoBytes","existingShardInfo","wakuPeerExchangeDiscovery","DEFAULT_LOCAL_TAG_NAME","LocalPeerCacheDiscovery","getPeersFromLocalStorage","handleNewPeers","savePeersToLocalStorage","websocketMultiaddr","wsMultiaddr","getWsMultiaddrFromMultiaddrs","localStoragePeers","existingPeerIndex","_peer","storedPeersData","isValidStoredPeer","defaultLibp2p","hideWebSocketInfo","createLibp2p","filterMultiaddrs","pingMaxInboundStreams","createLightNode","networkConfig","isAutoSharding","derivePubsubTopicsFromNetworkConfig","libp2pOptions","defaultBootstrap","defaultPeerDiscoveries","createLibp2pAndUpdateOptions","TelemetryType","__generator","sent","trys","Iterator","verb","TelemetryClient","intervalPeriod","intervalId","_this","telemetryRequests","e_1","telemetryType","telemetryData","__assign","generateRandomNumber","DEFAULT_EXTRA_DATA","sdk","DEFAULT_EXTRA_DATA_STR","buildExtraData","extraData","enabledProtocols","__spreadArray","pack","ar","DEFAULT_CONTENT_TOPIC","DEFAULT_PUBSUB_TOPIC","ProtoSequencedMessage","sequenceCompletedEvent","messageSentEvent","messageReceivedEvent","app","telemetryClient","startLightPushSequence","startFilterSubscription","_e","discoveredPeerId","LIGHT_PUSH_FILTER","createdAt","seenTimestamp","numMessages_1","args_1","_i","numMessages","period","sequenceHash","sequenceTotal","sequenceIndex","sendMessage","messageHash_1","timestamp_1","successEvents","failureEvents","messageElement","messagesSent","error_1","seqHash","sender","createElement","getElementById","textContent","insertBefore","firstChild","messagesReceived","failEvents","resolvedEvents","appendChild","startSequence","messagePeriod","sentMessagesCount","sentMessagesCounter","receivedMessagesCount","receivedMessagesCounter","innerText","display"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"index.js","mappings":";qDACAA,EAAOC,QAmBP,SAAmBC,EAAIC,GAKnB,IAJA,IAAIC,EAAU,IAAIC,MAAMC,UAAUC,OAAS,GACvCC,EAAU,EACVC,EAAU,EACVC,GAAU,EACPD,EAAQH,UAAUC,QACrBH,EAAOI,KAAYF,UAAUG,KACjC,OAAO,IAAIE,SAAQ,SAAkBC,EAASC,GAC1CT,EAAOI,GAAU,SAAkBM,GAC/B,GAAIJ,EAEA,GADAA,GAAU,EACNI,EACAD,EAAOC,OACN,CAGD,IAFA,IAAIV,EAAS,IAAIC,MAAMC,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P,KAAK,EAgBD,OAfA76F,EAAUi0B,GAAck0G,IACxB9yF,EAAuB,SAAUz1D,GAAW,OAAO,GAAU2nJ,OAAO,OAAQ,GAAQ,WAChF,IAAI7xF,EACJ,OAAO,GAAYv/D,MAAM,SAAUihF,GAE/B,OADA1hB,EAAiB2yF,GAAsBt0J,OAAO6L,EAAQ4pC,UACnCsgH,SAAW/tG,IAGlBppD,KAAKmD,OAAM,IAAIuK,MAAOo6B,UAAY,KAC7B97B,SAASorJ,cAAc,OACzBC,YAAc,YAAYhkJ,OAAO0vD,EAAe9yD,MAC/DjE,SAASijD,cAAc2mG,KALZ,CAAC,EAOhB,GACJ,GAAI,EACG,CAAC,EAAalhJ,EAAKhF,OAAO0nC,UAAU/pB,EAASq1C,IACxD,KAAK,EAED,OADA+hB,EAAG4vE,OACI,CAAC,GAEpB,GACJ,GAAI,EACG,CAAC,EAAc,CACd3/I,KAAMA,EACNshJ,uBAAwBA,EACxBC,wBAAyBA,IAG7C,GACJ,GACJ,CACsB,QAAU,OAAQ,OAAQ,GAAQ,WACpD,IAAqBxxE,EAAUuxE,EAC/B,OAAO,GAAYxyJ,MAAM,SAAUkiF,GAC/B,OAAQA,EAAGwiC,OACP,KAAK,EAED,MAAO,CAAC,EAAa4tC,GADH,IAAIrB,GAvMlB,2CAuMiD,OAEzD,KAAK,EAOD,OANAhwE,EAAKiB,EAAG2uE,QAAkB3/I,KAAMshJ,EAAyBvxE,EAAGuxE,wBAAwBC,EAA0BxxE,EAAGwxE,2BAEjHjqJ,SAASo7C,iBAAiBuuG,GAAuBjqJ,MAAM,WACnD,OAAOsqJ,EAAuB,GAAI,IACtC,IACAA,EAAuB,GAAI,KACpB,CAAC,GAEpB,GACJ","sources":["webpack://waku-dogfooding/./node_modules/@protobufjs/aspromise/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/base64/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/codegen/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/eventemitter/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/fetch/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/float/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/inquire/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/path/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/pool/index.js","webpack://waku-dogfooding/./node_modules/@protobufjs/utf8/index.js","webpack://waku-dogfooding/./node_modules/debug/src/browser.js","webpack://waku-dogfooding/./node_modules/debug/src/common.js","webpack://waku-dogfooding/./node_modules/event-iterator/lib/dom.js","webpack://waku-dogfooding/./node_modules/event-iterator/lib/event-iterator.js","webpack://waku-dogfooding/./node_modules/eventemitter3/index.js","webpack://waku-dogfooding/./node_modules/hashlru/index.js","webpack://waku-dogfooding/./node_modules/hi-base32/src/base32.js","webpack://waku-dogfooding/./node_modules/is-electron/index.js","webpack://waku-dogfooding/./node_modules/is-plain-obj/index.js","webpack://waku-dogfooding/./node_modules/js-sha3/src/sha3.js","webpack://waku-dogfooding/./node_modules/merge-options/index.js","webpack://waku-dogfooding/./node_modules/ms/index.js","webpack://waku-dogfooding/./node_modules/murmurhash3js-revisited/index.js","webpack://waku-dogfooding/./node_modules/murmurhash3js-revisited/lib/murmurHash3js.js","webpack://waku-dogfooding/./node_modules/netmask/lib/netmask.js","webpack://waku-dogfooding/./node_modules/protobufjs/index.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/common.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/converter.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/decoder.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/encoder.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/enum.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/field.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/index-light.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/index-minimal.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/index.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/mapfield.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/message.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/method.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/namespace.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/object.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/oneof.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/parse.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/reader.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/reader_buffer.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/root.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/roots.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/rpc.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/rpc/service.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/service.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/tokenize.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/type.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/types.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/util.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/util/longbits.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/util/minimal.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/verifier.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/wrappers.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/writer.js","webpack://waku-dogfooding/./node_modules/protobufjs/src/writer_buffer.js","webpack://waku-dogfooding/./node_modules/pvtsutils/build/index.js","webpack://waku-dogfooding/./node_modules/retry/index.js","webpack://waku-dogfooding/./node_modules/retry/lib/retry.js","webpack://waku-dogfooding/./node_modules/retry/lib/retry_operation.js","webpack://waku-dogfooding/webpack/bootstrap","webpack://waku-dogfooding/webpack/runtime/create fake namespace object","webpack://waku-dogfooding/webpack/runtime/amd options","webpack://waku-dogfooding/webpack/runtime/define property getters","webpack://waku-dogfooding/webpack/runtime/hasOwnProperty shorthand","webpack://waku-dogfooding/webpack/runtime/make namespace object","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/alloc.js","webpack://waku-dogfooding/./node_modules/uint8-varint/dist/src/index.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/float.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/longbits.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/utf8.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/reader.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/decode.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bytes.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/vendor/base-x.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base10.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base16.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base2.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base256emoji.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base32.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base36.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base58.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base64.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/base8.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/bases/identity.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/codecs/json.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/codecs/raw.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/vendor/varint.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/varint.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/hashes/digest.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/hashes/identity.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/hashes/hasher.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/hashes/sha2-browser.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/cid.js","webpack://waku-dogfooding/./node_modules/multiformats/dist/src/basics.js","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/util/bases.js","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/from-string.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/writer.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/utils/pool.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/encode.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/codec.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/message.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/filter.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/topic_only_message.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/filter_v2.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/light_push.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/store_v3.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/peer_exchange.js","webpack://waku-dogfooding/./node_modules/@waku/proto/dist/generated/metadata.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/codecs/enum.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/codecs/message.js","webpack://waku-dogfooding/./node_modules/protons-runtime/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/is_defined.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/group_by.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/to_async_iterator.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/_assert.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/crypto.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/utils.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/_md.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/sha256.js","webpack://waku-dogfooding/./node_modules/@waku/interfaces/dist/protocols.js","webpack://waku-dogfooding/./node_modules/@waku/interfaces/dist/connection_manager.js","webpack://waku-dogfooding/./node_modules/@waku/interfaces/dist/dns_discovery.js","webpack://waku-dogfooding/./node_modules/@waku/interfaces/dist/constants.js","webpack://waku-dogfooding/./node_modules/@waku/interfaces/dist/health_manager.js","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/to-string.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/bytes/index.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/sharding/index.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/relay_shard_codec.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/logger/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/message/version_0.js","webpack://waku-dogfooding/./node_modules/it-all/dist/src/index.js","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/concat.js","webpack://waku-dogfooding/./node_modules/uint8arrays/dist/src/equals.js","webpack://waku-dogfooding/./node_modules/uint8arraylist/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed/dist/src/utils.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed/dist/src/encode.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed/dist/src/decode.js","webpack://waku-dogfooding/./node_modules/p-defer/index.js","webpack://waku-dogfooding/./node_modules/it-pushable/dist/src/fifo.js","webpack://waku-dogfooding/./node_modules/it-pushable/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-merge/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-pipe/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/stream_manager/utils.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/stream_manager/stream_manager.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/base_protocol.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/uuid/dist/esm-browser/native.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/uuid/dist/esm-browser/rng.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/uuid/dist/esm-browser/stringify.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/uuid/dist/esm-browser/v4.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/filter_rpc.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/light_push/push_rpc.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/light_push/utils.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/light_push/index.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/is_size_valid.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/to_proto_message.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/store/rpc.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/store/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/event-target.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/connection_manager/keep_alive_manager.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/connection_manager/utils.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/connection_manager/connection_manager.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/health_manager.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/metadata/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/peer-id/index.js","webpack://waku-dogfooding/./node_modules/@chainsafe/is-ip/lib/parse.js","webpack://waku-dogfooding/./node_modules/@chainsafe/is-ip/lib/parser.js","webpack://waku-dogfooding/./node_modules/@chainsafe/netmask/dist/src/ip.js","webpack://waku-dogfooding/./node_modules/@chainsafe/netmask/dist/src/util.js","webpack://waku-dogfooding/./node_modules/@chainsafe/netmask/dist/src/cidr.js","webpack://waku-dogfooding/./node_modules/@chainsafe/netmask/dist/src/ipnet.js","webpack://waku-dogfooding/./node_modules/@chainsafe/is-ip/lib/is-ip.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/ip.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/convert.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/codec.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/multiaddr.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/message-hash/dist/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/filter/subscription_monitor.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/filter/subscription.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/filter/constants.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/filter/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/filter/utils.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/light_push/light_push.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/peer_manager.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/protocols/store/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/waku/wait_for_remote_peer.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/waku/waku.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/_u64.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/sha512.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/utils.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/modular.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/curve.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/edwards.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/montgomery.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/ed25519.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/ed25519/index.browser.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/ed25519/ed25519.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/ed25519/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/keys.js","webpack://waku-dogfooding/./node_modules/pvutils/build/utils.es.js","webpack://waku-dogfooding/./node_modules/asn1js/build/index.es.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/webcrypto/webcrypto.browser.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/webcrypto/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/rsa/rsa.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/rsa/index.browser.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/rsa/utils.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/hmac.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/abstract/weierstrass.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/_shortw_utils.js","webpack://waku-dogfooding/./node_modules/@noble/curves/esm/secp256k1.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/util.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/secp256k1.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/secp256k1/index.browser.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/keys/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-id/dist/src/peer-id.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-id/dist/src/index.js","webpack://waku-dogfooding/./node_modules/race-signal/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-queueless-pushable/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-byte-stream/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/it-byte-stream/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed-stream/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/it-length-prefixed-stream/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-pair/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/constants.js","webpack://waku-dogfooding/./node_modules/@noble/ciphers/esm/_assert.js","webpack://waku-dogfooding/./node_modules/@noble/ciphers/esm/utils.js","webpack://waku-dogfooding/./node_modules/@noble/ciphers/esm/_arx.js","webpack://waku-dogfooding/./node_modules/@noble/ciphers/esm/_poly1305.js","webpack://waku-dogfooding/./node_modules/@noble/ciphers/esm/chacha.js","webpack://waku-dogfooding/./node_modules/@noble/hashes/esm/hkdf.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/crypto/index.browser.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/crypto/js.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/encoder.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/logger.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/nonce.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/protocol.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/proto/payload.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/utils.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/noise.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/crypto.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/metrics.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/performHandshake.js","webpack://waku-dogfooding/./node_modules/it-pair/dist/src/duplex.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/streaming.js","webpack://waku-dogfooding/./node_modules/@chainsafe/libp2p-noise/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/peer-discovery/index.js","webpack://waku-dogfooding/./node_modules/@multiformats/mafmt/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/bootstrap/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/array-equals.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/envelope/errors.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-record/dist/src/envelope/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/private-ip.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-protobuf-stream/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/identify/dist/src/pb/message.js","webpack://waku-dogfooding/./node_modules/wherearewe/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/identify/dist/src/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/identify/dist/src/consts.js","webpack://waku-dogfooding/./node_modules/@libp2p/identify/dist/src/identify.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/multiaddr/is-global-unicast.js","webpack://waku-dogfooding/./node_modules/@chainsafe/netmask/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/identify/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/close-source.js","webpack://waku-dogfooding/./node_modules/get-iterator/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/is-promise.js","webpack://waku-dogfooding/./node_modules/delay/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/rate-limiter.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/message-types.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/decode.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/encode.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/abstract-stream.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/stream.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/mplex.js","webpack://waku-dogfooding/./node_modules/@libp2p/mplex/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/crypto/dist/src/random-bytes.js","webpack://waku-dogfooding/./node_modules/@libp2p/ping/dist/src/ping.js","webpack://waku-dogfooding/./node_modules/@libp2p/ping/dist/src/constants.js","webpack://waku-dogfooding/./node_modules/it-first/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/ping/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/transport/index.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/ready.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/sink.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/source.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/web-socket.browser.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/ws-url.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/client.js","webpack://waku-dogfooding/./node_modules/it-ws/dist/src/duplex.js","webpack://waku-dogfooding/./node_modules/progress-events/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/websockets/dist/src/filters.js","webpack://waku-dogfooding/./node_modules/@libp2p/websockets/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/websockets/dist/src/socket-to-conn.js","webpack://waku-dogfooding/./node_modules/@libp2p/websockets/dist/src/constants.js","webpack://waku-dogfooding/./node_modules/@libp2p/websockets/dist/src/listener.browser.js","webpack://waku-dogfooding/./node_modules/p-timeout/index.js","webpack://waku-dogfooding/./node_modules/p-queue/dist/priority-queue.js","webpack://waku-dogfooding/./node_modules/p-queue/dist/lower-bound.js","webpack://waku-dogfooding/./node_modules/p-queue/dist/index.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/utils/get-types.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/utils/to-dns-response.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/resolvers/dns-json-over-https.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/utils/cache.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/dns.js","webpack://waku-dogfooding/./node_modules/@multiformats/dns/dist/src/resolvers/default.browser.js","webpack://waku-dogfooding/./node_modules/@multiformats/multiaddr/dist/src/resolvers/dnsaddr.js","webpack://waku-dogfooding/./node_modules/merge-options/index.mjs","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/content-routing/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/peer-routing/index.js","webpack://waku-dogfooding/./node_modules/weald/node_modules/ms/dist/index.mjs","webpack://waku-dogfooding/./node_modules/weald/dist/src/browser.js","webpack://waku-dogfooding/./node_modules/weald/dist/src/common.js","webpack://waku-dogfooding/./node_modules/weald/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/logger/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-collections/dist/src/util.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-collections/dist/src/set.js","webpack://waku-dogfooding/./node_modules/observable-webworkers/dist/src/index.js","webpack://waku-dogfooding/./node_modules/mortice/dist/src/constants.js","webpack://waku-dogfooding/./node_modules/mortice/dist/src/browser.js","webpack://waku-dogfooding/./node_modules/mortice/dist/src/utils.js","webpack://waku-dogfooding/./node_modules/mortice/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/pb/peer.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/utils/bytes-to-peer.js","webpack://waku-dogfooding/./node_modules/interface-datastore/dist/src/key.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/utils/peer-id-to-datastore-key.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/utils/dedupe-addresses.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/utils/to-peer-pb.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/store.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-store/dist/src/index.js","webpack://waku-dogfooding/./node_modules/interface-store/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/it-drain/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-filter/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-peekable/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-sort/dist/src/index.js","webpack://waku-dogfooding/./node_modules/it-take/dist/src/index.js","webpack://waku-dogfooding/./node_modules/datastore-core/dist/src/base.js","webpack://waku-dogfooding/./node_modules/datastore-core/dist/src/memory.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/startable.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/components.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config/connection-gater.browser.js","webpack://waku-dogfooding/./node_modules/@libp2p/peer-collections/dist/src/map.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/close.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/connection-pruner.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js","webpack://waku-dogfooding/./node_modules/race-event/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/queue/recipient.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/queue/job.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/queue/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/priority-queue.js","webpack://waku-dogfooding/./node_modules/any-signal/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/address-sorter.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/dial-queue.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/peer-store/tags.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/peer-queue.js","webpack://waku-dogfooding/./node_modules/is-network-error/index.js","webpack://waku-dogfooding/./node_modules/p-retry/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/reconnect-queue.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/moving-average.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/adaptive-timeout.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-monitor.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/content-routing.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/utils.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/bucket.js","webpack://waku-dogfooding/./node_modules/@sindresorhus/fnv1a/index.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/hashes.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/cuckoo-filter.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/filters/scalable-cuckoo-filter.js","webpack://waku-dogfooding/./node_modules/it-parallel/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/peer-routing.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/random-walk.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js","webpack://waku-dogfooding/./node_modules/@libp2p/utils/dist/src/tracked-map.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/transport-manager.js","webpack://waku-dogfooding/./node_modules/@libp2p/multistream-select/dist/src/constants.js","webpack://waku-dogfooding/./node_modules/@libp2p/multistream-select/dist/src/multistream.js","webpack://waku-dogfooding/./node_modules/@libp2p/multistream-select/dist/src/handle.js","webpack://waku-dogfooding/./node_modules/@libp2p/multistream-select/dist/src/select.js","webpack://waku-dogfooding/./node_modules/@libp2p/interface/dist/src/connection/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/upgrader.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/libp2p.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/version.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/constants.js","webpack://waku-dogfooding/./node_modules/@noble/secp256k1/lib/esm/index.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/crypto.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/constants.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/get_multiaddr.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/multiaddr_from_fields.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/multiaddrs_codec.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/waku2_codec.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/raw_enr.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/v4.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/enr.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/peer_id.js","webpack://waku-dogfooding/./node_modules/@ethersproject/logger/lib.esm/index.js","webpack://waku-dogfooding/./node_modules/@ethersproject/logger/lib.esm/_version.js","webpack://waku-dogfooding/./node_modules/@ethersproject/bytes/lib.esm/_version.js","webpack://waku-dogfooding/./node_modules/@ethersproject/bytes/lib.esm/index.js","webpack://waku-dogfooding/./node_modules/@ethersproject/rlp/lib.esm/_version.js","webpack://waku-dogfooding/./node_modules/@ethersproject/rlp/lib.esm/index.js","webpack://waku-dogfooding/./node_modules/@waku/enr/dist/decoder.js","webpack://waku-dogfooding/./node_modules/@leichtgewicht/ip-codec/index.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/types.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/rcodes.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/opcodes.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/classes.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/optioncodes.mjs","webpack://waku-dogfooding/./node_modules/utf8-codec/index.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/buffer_utils.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/dns-packet/index.mjs","webpack://waku-dogfooding/./node_modules/@leichtgewicht/base64-codec/index.mjs","webpack://waku-dogfooding/./node_modules/dns-query/common.mjs","webpack://waku-dogfooding/./node_modules/dns-query/lib.browser.mjs","webpack://waku-dogfooding/./node_modules/dns-query/index.mjs","webpack://waku-dogfooding/./node_modules/dns-query/resolvers.mjs","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/dns_over_https.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/enrtree.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/fetch_nodes.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/dns.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/dns/dns_discovery.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/node_modules/@waku/core/dist/lib/stream_manager/utils.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/node_modules/@waku/core/dist/lib/stream_manager/stream_manager.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/node_modules/@waku/core/dist/lib/base_protocol.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/peer-exchange/rpc.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/peer-exchange/waku_peer_exchange.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/peer-exchange/waku_peer_exchange_discovery.js","webpack://waku-dogfooding/./node_modules/@waku/discovery/dist/local-peer-cache/index.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/create/libp2p.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/index.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/create/create.js","webpack://waku-dogfooding/./node_modules/@waku/utils/dist/common/sharding/type_guards.js","webpack://waku-dogfooding/./node_modules/@waku/sdk/dist/create/discovery.js","webpack://waku-dogfooding/./src/telemetry_client.ts","webpack://waku-dogfooding/./src/util.ts","webpack://waku-dogfooding/./src/index.ts"],"sourcesContent":["\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(\"@protobufjs/aspromise\"),\r\n inquire = require(\"@protobufjs/inquire\");\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(' ', ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst event_iterator_1 = require(\"./event-iterator\");\nexports.EventIterator = event_iterator_1.EventIterator;\nfunction subscribe(event, options, evOptions) {\n return new event_iterator_1.EventIterator(({ push }) => {\n this.addEventListener(event, push, options);\n return () => this.removeEventListener(event, push, options);\n }, evOptions);\n}\nexports.subscribe = subscribe;\nexports.default = event_iterator_1.EventIterator;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass EventQueue {\n constructor() {\n this.pullQueue = [];\n this.pushQueue = [];\n this.eventHandlers = {};\n this.isPaused = false;\n this.isStopped = false;\n }\n push(value) {\n if (this.isStopped)\n return;\n const resolution = { value, done: false };\n if (this.pullQueue.length) {\n const placeholder = this.pullQueue.shift();\n if (placeholder)\n placeholder.resolve(resolution);\n }\n else {\n this.pushQueue.push(Promise.resolve(resolution));\n if (this.highWaterMark !== undefined &&\n this.pushQueue.length >= this.highWaterMark &&\n !this.isPaused) {\n this.isPaused = true;\n if (this.eventHandlers.highWater) {\n this.eventHandlers.highWater();\n }\n else if (console) {\n console.warn(`EventIterator queue reached ${this.pushQueue.length} items`);\n }\n }\n }\n }\n stop() {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n for (const placeholder of this.pullQueue) {\n placeholder.resolve({ value: undefined, done: true });\n }\n this.pullQueue.length = 0;\n }\n fail(error) {\n if (this.isStopped)\n return;\n this.isStopped = true;\n this.remove();\n if (this.pullQueue.length) {\n for (const placeholder of this.pullQueue) {\n placeholder.reject(error);\n }\n this.pullQueue.length = 0;\n }\n else {\n const rejection = Promise.reject(error);\n /* Attach error handler to avoid leaking an unhandled promise rejection. */\n rejection.catch(() => { });\n this.pushQueue.push(rejection);\n }\n }\n remove() {\n Promise.resolve().then(() => {\n if (this.removeCallback)\n this.removeCallback();\n });\n }\n [Symbol.asyncIterator]() {\n return {\n next: (value) => {\n const result = this.pushQueue.shift();\n if (result) {\n if (this.lowWaterMark !== undefined &&\n this.pushQueue.length <= this.lowWaterMark &&\n this.isPaused) {\n this.isPaused = false;\n if (this.eventHandlers.lowWater) {\n this.eventHandlers.lowWater();\n }\n }\n return result;\n }\n else if (this.isStopped) {\n return Promise.resolve({ value: undefined, done: true });\n }\n else {\n return new Promise((resolve, reject) => {\n this.pullQueue.push({ resolve, reject });\n });\n }\n },\n return: () => {\n this.isStopped = true;\n this.pushQueue.length = 0;\n this.remove();\n return Promise.resolve({ value: undefined, done: true });\n },\n };\n }\n}\nclass EventIterator {\n constructor(listen, { highWaterMark = 100, lowWaterMark = 1 } = {}) {\n const queue = new EventQueue();\n queue.highWaterMark = highWaterMark;\n queue.lowWaterMark = lowWaterMark;\n queue.removeCallback =\n listen({\n push: value => queue.push(value),\n stop: () => queue.stop(),\n fail: error => queue.fail(error),\n on: (event, fn) => {\n queue.eventHandlers[event] = fn;\n },\n }) || (() => { });\n this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();\n Object.freeze(this);\n }\n}\nexports.EventIterator = EventIterator;\nexports.default = EventIterator;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","module.exports = function (max) {\n\n if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')\n\n var size = 0, cache = Object.create(null), _cache = Object.create(null)\n\n function update (key, value) {\n cache[key] = value\n size ++\n if(size >= max) {\n size = 0\n _cache = cache\n cache = Object.create(null)\n }\n }\n\n return {\n has: function (key) {\n return cache[key] !== undefined || _cache[key] !== undefined\n },\n remove: function (key) {\n if(cache[key] !== undefined)\n cache[key] = undefined\n if(_cache[key] !== undefined)\n _cache[key] = undefined\n },\n get: function (key) {\n var v = cache[key]\n if(v !== undefined) return v\n if((v = _cache[key]) !== undefined) {\n update(key, v)\n return v\n }\n },\n set: function (key, value) {\n if(cache[key] !== undefined) cache[key] = value\n else update(key, value)\n },\n clear: function () {\n cache = Object.create(null)\n _cache = Object.create(null)\n }\n }\n}\n\n\n\n\n\n\n\n","/*\n * [hi-base32]{@link https://github.com/emn178/hi-base32}\n *\n * @version 0.5.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var root = typeof window === 'object' ? window : {};\n var NODE_JS = !root.HI_BASE32_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n }\n var COMMON_JS = !root.HI_BASE32_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var BASE32_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('');\n var BASE32_DECODE_CHAR = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16,\n 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,\n 'Z': 25, '2': 26, '3': 27, '4': 28, '5': 29, '6': 30, '7': 31\n };\n\n var blocks = [0, 0, 0, 0, 0, 0, 0, 0];\n\n var throwInvalidUtf8 = function (position, partial) {\n if (partial.length > 10) {\n partial = '...' + partial.substr(-10);\n }\n var err = new Error('Decoded data is not valid UTF-8.'\n + ' Maybe try base32.decode.asBytes()?'\n + ' Partial data after reading ' + position + ' bytes: ' + partial + ' <-');\n err.position = position;\n throw err;\n };\n\n var toUtf8String = function (bytes) {\n var str = '', length = bytes.length, i = 0, followingChars = 0, b, c;\n while (i < length) {\n b = bytes[i++];\n if (b <= 0x7F) {\n str += String.fromCharCode(b);\n continue;\n } else if (b > 0xBF && b <= 0xDF) {\n c = b & 0x1F;\n followingChars = 1;\n } else if (b <= 0xEF) {\n c = b & 0x0F;\n followingChars = 2;\n } else if (b <= 0xF7) {\n c = b & 0x07;\n followingChars = 3;\n } else {\n throwInvalidUtf8(i, str);\n }\n\n for (var j = 0; j < followingChars; ++j) {\n b = bytes[i++];\n if (b < 0x80 || b > 0xBF) {\n throwInvalidUtf8(i, str);\n }\n c <<= 6;\n c += b & 0x3F;\n }\n if (c >= 0xD800 && c <= 0xDFFF) {\n throwInvalidUtf8(i, str);\n }\n if (c > 0x10FFFF) {\n throwInvalidUtf8(i, str);\n }\n\n if (c <= 0xFFFF) {\n str += String.fromCharCode(c);\n } else {\n c -= 0x10000;\n str += String.fromCharCode((c >> 10) + 0xD800);\n str += String.fromCharCode((c & 0x3FF) + 0xDC00);\n }\n }\n return str;\n };\n\n var decodeAsBytes = function (base32Str) {\n if (base32Str === '') {\n return [];\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n base32Str = base32Str.replace(/=/g, '');\n var v1, v2, v3, v4, v5, v6, v7, v8, bytes = [], index = 0, length = base32Str.length;\n\n // 4 char to 3 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n bytes[index++] = (v7 << 5 | v8) & 255;\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n }\n return bytes;\n };\n\n var encodeAscii = function (str) {\n var v1, v2, v3, v4, v5, base32Str = '', length = str.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i++);\n v5 = str.charCodeAt(i++);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encodeUtf8 = function (str) {\n var v1, v2, v3, v4, v5, code, end = false, base32Str = '',\n index = 0, i, start = 0, bytes = 0, length = str.length;\n if (str === '') {\n return base32Str;\n }\n do {\n blocks[0] = blocks[5];\n blocks[1] = blocks[6];\n blocks[2] = blocks[7];\n for (i = start; index < length && i < 5; ++index) {\n code = str.charCodeAt(index);\n if (code < 0x80) {\n blocks[i++] = code;\n } else if (code < 0x800) {\n blocks[i++] = 0xc0 | (code >> 6);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i++] = 0xe0 | (code >> 12);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++index) & 0x3ff));\n blocks[i++] = 0xf0 | (code >> 18);\n blocks[i++] = 0x80 | ((code >> 12) & 0x3f);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n }\n }\n bytes += i - start;\n start = i - 5;\n if (index === length) {\n ++index;\n }\n if (index > length && i < 6) {\n end = true;\n }\n v1 = blocks[0];\n if (i > 4) {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n v5 = blocks[4];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n } else if (i === 1) {\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (i === 2) {\n v2 = blocks[1];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (i === 3) {\n v2 = blocks[1];\n v3 = blocks[2];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n } while (!end);\n return base32Str;\n };\n\n var encodeBytes = function (bytes) {\n var v1, v2, v3, v4, v5, base32Str = '', length = bytes.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i++];\n v5 = bytes[i++];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = bytes[i++];\n v2 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encode = function (input, asciiOnly) {\n var notString = typeof(input) !== 'string';\n if (notString && input.constructor === ArrayBuffer) {\n input = new Uint8Array(input);\n }\n if (notString) {\n return encodeBytes(input);\n } else if (asciiOnly) {\n return encodeAscii(input);\n } else {\n return encodeUtf8(input);\n }\n };\n\n var decode = function (base32Str, asciiOnly) {\n if (!asciiOnly) {\n return toUtf8String(decodeAsBytes(base32Str));\n }\n if (base32Str === '') {\n return '';\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n var v1, v2, v3, v4, v5, v6, v7, v8, str = '', length = base32Str.indexOf('=');\n if (length === -1) {\n length = base32Str.length;\n }\n\n // 8 char to 5 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255) +\n String.fromCharCode((v7 << 5 | v8) & 255);\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255);\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255);\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255);\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255);\n }\n return str;\n };\n\n var exports = {\n encode: encode,\n decode: decode\n };\n decode.asBytes = decodeAsBytes;\n\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n root.base32 = exports;\n if (AMD) {\n define(function() {\n return exports;\n });\n }\n }\n})();\n","// https://github.com/electron/electron/issues/2288\nfunction isElectron() {\n // Renderer process\n if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {\n return true;\n }\n\n // Main process\n if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {\n return true;\n }\n\n // Detect the user agent when the `nodeIntegration` option is set to false\n if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = isElectron;\n","'use strict';\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(value) !== '[object Object]') {\n\t\treturn false;\n\t}\n\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === null || prototype === Object.prototype;\n};\n","/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.9.3\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2023\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = global;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;\n var AMD = typeof define === 'function' && define.amd;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n\n var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray\n ? function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n }\n : Array.isArray;\n\n var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))\n ? function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n }\n : ArrayBuffer.isView;\n\n // [message: string, isString: bool]\n var formatMessage = function (message) {\n var type = typeof message;\n if (type === 'string') {\n return [message, true];\n }\n if (type !== 'object' || message === null) {\n throw new Error(INPUT_ERROR);\n }\n if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n return [new Uint8Array(message), false];\n }\n if (!isArray(message) && !isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n return [message, false];\n }\n\n var empty = function (message) {\n return formatMessage(message)[0].length === 0;\n };\n\n var cloneArray = function (array) {\n var newArray = [];\n for (var i = 0; i < array.length; ++i) {\n newArray[i] = array[i];\n }\n return newArray;\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (empty(n) && empty(s)) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var result = formatMessage(message);\n message = result[0];\n var isString = result[1];\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (isString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var result = formatMessage(str);\n str = result[0];\n var isString = result[1];\n var bytes = 0, length = str.length;\n if (isString) {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n } else {\n bytes = length;\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = (w - bytes % w) % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n array[j] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n define(function () {\n return methods;\n });\n }\n }\n})();\n","'use strict';\nconst isOptionObject = require('is-plain-obj');\n\nconst {hasOwnProperty} = Object.prototype;\nconst {propertyIsEnumerable} = Object;\nconst defineProperty = (object, name, value) => Object.defineProperty(object, name, {\n\tvalue,\n\twritable: true,\n\tenumerable: true,\n\tconfigurable: true\n});\n\nconst globalThis = this;\nconst defaultMergeOptions = {\n\tconcatArrays: false,\n\tignoreUndefined: false\n};\n\nconst getEnumerableOwnPropertyKeys = value => {\n\tconst keys = [];\n\n\tfor (const key in value) {\n\t\tif (hasOwnProperty.call(value, key)) {\n\t\t\tkeys.push(key);\n\t\t}\n\t}\n\n\t/* istanbul ignore else */\n\tif (Object.getOwnPropertySymbols) {\n\t\tconst symbols = Object.getOwnPropertySymbols(value);\n\n\t\tfor (const symbol of symbols) {\n\t\t\tif (propertyIsEnumerable.call(value, symbol)) {\n\t\t\t\tkeys.push(symbol);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn keys;\n};\n\nfunction clone(value) {\n\tif (Array.isArray(value)) {\n\t\treturn cloneArray(value);\n\t}\n\n\tif (isOptionObject(value)) {\n\t\treturn cloneOptionObject(value);\n\t}\n\n\treturn value;\n}\n\nfunction cloneArray(array) {\n\tconst result = array.slice(0, 0);\n\n\tgetEnumerableOwnPropertyKeys(array).forEach(key => {\n\t\tdefineProperty(result, key, clone(array[key]));\n\t});\n\n\treturn result;\n}\n\nfunction cloneOptionObject(object) {\n\tconst result = Object.getPrototypeOf(object) === null ? Object.create(null) : {};\n\n\tgetEnumerableOwnPropertyKeys(object).forEach(key => {\n\t\tdefineProperty(result, key, clone(object[key]));\n\t});\n\n\treturn result;\n}\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {string[]} keys keys to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nconst mergeKeys = (merged, source, keys, config) => {\n\tkeys.forEach(key => {\n\t\tif (typeof source[key] === 'undefined' && config.ignoreUndefined) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Do not recurse into prototype chain of merged\n\t\tif (key in merged && merged[key] !== Object.getPrototypeOf(merged)) {\n\t\t\tdefineProperty(merged, key, merge(merged[key], source[key], config));\n\t\t} else {\n\t\t\tdefineProperty(merged, key, clone(source[key]));\n\t\t}\n\t});\n\n\treturn merged;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n *\n * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat)\n */\nconst concatArrays = (merged, source, config) => {\n\tlet result = merged.slice(0, 0);\n\tlet resultIndex = 0;\n\n\t[merged, source].forEach(array => {\n\t\tconst indices = [];\n\n\t\t// `result.concat(array)` with cloning\n\t\tfor (let k = 0; k < array.length; k++) {\n\t\t\tif (!hasOwnProperty.call(array, k)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tindices.push(String(k));\n\n\t\t\tif (array === merged) {\n\t\t\t\t// Already cloned\n\t\t\t\tdefineProperty(result, resultIndex++, array[k]);\n\t\t\t} else {\n\t\t\t\tdefineProperty(result, resultIndex++, clone(array[k]));\n\t\t\t}\n\t\t}\n\n\t\t// Merge non-index keys\n\t\tresult = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config);\n\t});\n\n\treturn result;\n};\n\n/**\n * @param {*} merged already cloned\n * @param {*} source something to merge\n * @param {Object} config Config Object\n * @returns {*} cloned Object\n */\nfunction merge(merged, source, config) {\n\tif (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) {\n\t\treturn concatArrays(merged, source, config);\n\t}\n\n\tif (!isOptionObject(source) || !isOptionObject(merged)) {\n\t\treturn clone(source);\n\t}\n\n\treturn mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config);\n}\n\nmodule.exports = function (...options) {\n\tconst config = merge(clone(defaultMergeOptions), (this !== globalThis && this) || {}, defaultMergeOptions);\n\tlet merged = {_: {}};\n\n\tfor (const option of options) {\n\t\tif (option === undefined) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!isOptionObject(option)) {\n\t\t\tthrow new TypeError('`' + option + '` is not an Option Object');\n\t\t}\n\n\t\tmerged = merge(merged, {_: option}, config);\n\t}\n\n\treturn merged._;\n};\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","module.exports = require('./lib/murmurHash3js');\n","/* jshint -W086: true */\n// +----------------------------------------------------------------------+\n// | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js\n// | A javascript implementation of MurmurHash3's x86 hashing algorithms. |\n// |----------------------------------------------------------------------|\n// | Copyright (c) 2012-2015 Karan Lyons |\n// | https://github.com/karanlyons/murmurHash3.js/blob/c1778f75792abef7bdd74bc85d2d4e1a3d25cfe9/murmurHash3.js |\n// | Freely distributable under the MIT license. |\n// +----------------------------------------------------------------------+\n\n;(function (root, undefined) {\n 'use strict';\n\n // Create a local object that'll be exported or referenced globally.\n var library = {\n 'version': '3.0.0',\n 'x86': {},\n 'x64': {},\n 'inputValidation': true\n };\n\n // PRIVATE FUNCTIONS\n // -----------------\n\n function _validBytes(bytes) {\n // check the input is an array or a typed array\n if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) {\n return false;\n }\n\n // check all bytes are actually bytes\n for (var i = 0; i < bytes.length; i++) {\n if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {\n return false;\n }\n }\n return true;\n }\n\n function _x86Multiply(m, n) {\n //\n // Given two 32bit ints, returns the two multiplied together as a\n // 32bit int.\n //\n\n return ((m & 0xffff) * n) + ((((m >>> 16) * n) & 0xffff) << 16);\n }\n\n function _x86Rotl(m, n) {\n //\n // Given a 32bit int and an int representing a number of bit positions,\n // returns the 32bit int rotated left by that number of positions.\n //\n\n return (m << n) | (m >>> (32 - n));\n }\n\n function _x86Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x86 mix of that block.\n //\n\n h ^= h >>> 16;\n h = _x86Multiply(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = _x86Multiply(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h;\n }\n\n function _x64Add(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // added together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] + n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] + n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] + n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += m[0] + n[0];\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Multiply(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // multiplied together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] * n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] * n[3];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[2] += m[3] * n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] * n[3];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[2] * n[2];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[3] * n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Rotl(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) rotated left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 32) {\n return [m[1], m[0]];\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];\n } else {\n n -= 32;\n return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];\n }\n }\n\n function _x64LeftShift(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) shifted left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 0) {\n return m;\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];\n } else {\n return [m[1] << (n - 32), 0];\n }\n }\n\n function _x64Xor(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // xored together as a 64bit int (as an array of two 32bit ints).\n //\n\n return [m[0] ^ n[0], m[1] ^ n[1]];\n }\n\n function _x64Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x64 mix of that block.\n // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the\n // only place where we need to right shift 64bit ints.)\n //\n\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xff51afd7, 0xed558ccd]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n\n return h;\n }\n\n // PUBLIC FUNCTIONS\n // ----------------\n\n library.x86.hash32 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 32 bit hash\n // using the x86 flavor of MurmurHash3, as an unsigned int.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 4;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n\n var k1 = 0;\n\n var c1 = 0xcc9e2d51;\n var c2 = 0x1b873593;\n\n for (var i = 0; i < blocks; i = i + 4) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n\n h1 ^= k1;\n h1 = _x86Rotl(h1, 13);\n h1 = _x86Multiply(h1, 5) + 0xe6546b64;\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h1 = _x86Fmix(h1);\n\n return h1 >>> 0;\n };\n\n library.x86.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x86 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n\n seed = seed || 0;\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n var h2 = seed;\n var h3 = seed;\n var h4 = seed;\n\n var k1 = 0;\n var k2 = 0;\n var k3 = 0;\n var k4 = 0;\n\n var c1 = 0x239b961b;\n var c2 = 0xab0e9789;\n var c3 = 0x38b34ae5;\n var c4 = 0xa1e38b93;\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n k2 = (bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24);\n k3 = (bytes[i + 8]) | (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24);\n k4 = (bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n\n h1 = _x86Rotl(h1, 19);\n h1 += h2;\n h1 = _x86Multiply(h1, 5) + 0x561ccd1b;\n\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n h2 = _x86Rotl(h2, 17);\n h2 += h3;\n h2 = _x86Multiply(h2, 5) + 0x0bcaa747;\n\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n h3 = _x86Rotl(h3, 15);\n h3 += h4;\n h3 = _x86Multiply(h3, 5) + 0x96cd1c35;\n\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n h4 = _x86Rotl(h4, 13);\n h4 += h1;\n h4 = _x86Multiply(h4, 5) + 0x32ac3b17;\n }\n\n k1 = 0;\n k2 = 0;\n k3 = 0;\n k4 = 0;\n\n switch (remainder) {\n case 15:\n k4 ^= bytes[i + 14] << 16;\n\n case 14:\n k4 ^= bytes[i + 13] << 8;\n\n case 13:\n k4 ^= bytes[i + 12];\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n case 12:\n k3 ^= bytes[i + 11] << 24;\n\n case 11:\n k3 ^= bytes[i + 10] << 16;\n\n case 10:\n k3 ^= bytes[i + 9] << 8;\n\n case 9:\n k3 ^= bytes[i + 8];\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n case 8:\n k2 ^= bytes[i + 7] << 24;\n\n case 7:\n k2 ^= bytes[i + 6] << 16;\n\n case 6:\n k2 ^= bytes[i + 5] << 8;\n\n case 5:\n k2 ^= bytes[i + 4];\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n case 4:\n k1 ^= bytes[i + 3] << 24;\n\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h2 ^= bytes.length;\n h3 ^= bytes.length;\n h4 ^= bytes.length;\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n h1 = _x86Fmix(h1);\n h2 = _x86Fmix(h2);\n h3 = _x86Fmix(h3);\n h4 = _x86Fmix(h4);\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n return (\"00000000\" + (h1 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h3 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h4 >>> 0).toString(16)).slice(-8);\n };\n\n library.x64.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x64 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = [0, seed];\n var h2 = [0, seed];\n\n var k1 = [0, 0];\n var k2 = [0, 0];\n\n var c1 = [0x87c37b91, 0x114253d5];\n var c2 = [0x4cf5ad43, 0x2745937f];\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = [(bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24), (bytes[i]) |\n (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)];\n k2 = [(bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24), (bytes[i + 8]) |\n (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24)];\n\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n\n h1 = _x64Rotl(h1, 27);\n h1 = _x64Add(h1, h2);\n h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 0x52dce729]);\n\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n h2 = _x64Rotl(h2, 31);\n h2 = _x64Add(h2, h1);\n h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);\n }\n\n k1 = [0, 0];\n k2 = [0, 0];\n\n switch (remainder) {\n case 15:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 14]], 48));\n\n case 14:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 13]], 40));\n\n case 13:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 12]], 32));\n\n case 12:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 11]], 24));\n\n case 11:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 10]], 16));\n\n case 10:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 9]], 8));\n\n case 9:\n k2 = _x64Xor(k2, [0, bytes[i + 8]]);\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n case 8:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 7]], 56));\n\n case 7:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 6]], 48));\n\n case 6:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 5]], 40));\n\n case 5:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 4]], 32));\n\n case 4:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 3]], 24));\n\n case 3:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 2]], 16));\n\n case 2:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 1]], 8));\n\n case 1:\n k1 = _x64Xor(k1, [0, bytes[i]]);\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n }\n\n h1 = _x64Xor(h1, [0, bytes.length]);\n h2 = _x64Xor(h2, [0, bytes.length]);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n h1 = _x64Fmix(h1);\n h2 = _x64Fmix(h2);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n return (\"00000000\" + (h1[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h1[1] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[1] >>> 0).toString(16)).slice(-8);\n };\n\n // INITIALIZATION\n // --------------\n\n // Export murmurHash3 for CommonJS, either as an AMD module or just as part\n // of the global object.\n if (typeof exports !== 'undefined') {\n\n if (typeof module !== 'undefined' && module.exports) {\n exports = module.exports = library;\n }\n\n exports.murmurHash3 = library;\n\n } else if (typeof define === 'function' && define.amd) {\n\n define([], function () {\n return library;\n });\n } else {\n\n // Use murmurHash3.noConflict to restore `murmurHash3` back to its\n // original value. Returns a reference to the library object, to allow\n // it to be used under a different name.\n library._murmurHash3 = root.murmurHash3;\n\n library.noConflict = function () {\n root.murmurHash3 = library._murmurHash3;\n library._murmurHash3 = undefined;\n library.noConflict = undefined;\n\n return library;\n };\n\n root.murmurHash3 = library;\n }\n})(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n var Netmask, atob, chr, chr0, chrA, chra, ip2long, long2ip;\n\n long2ip = function(long) {\n var a, b, c, d;\n a = (long & (0xff << 24)) >>> 24;\n b = (long & (0xff << 16)) >>> 16;\n c = (long & (0xff << 8)) >>> 8;\n d = long & 0xff;\n return [a, b, c, d].join('.');\n };\n\n ip2long = function(ip) {\n var b, c, i, j, n, ref;\n b = [];\n for (i = j = 0; j <= 3; i = ++j) {\n if (ip.length === 0) {\n break;\n }\n if (i > 0) {\n if (ip[0] !== '.') {\n throw new Error('Invalid IP');\n }\n ip = ip.substring(1);\n }\n ref = atob(ip), n = ref[0], c = ref[1];\n ip = ip.substring(c);\n b.push(n);\n }\n if (ip.length !== 0) {\n throw new Error('Invalid IP');\n }\n switch (b.length) {\n case 1:\n if (b[0] > 0xFFFFFFFF) {\n throw new Error('Invalid IP');\n }\n return b[0] >>> 0;\n case 2:\n if (b[0] > 0xFF || b[1] > 0xFFFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1]) >>> 0;\n case 3:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFFFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2]) >>> 0;\n case 4:\n if (b[0] > 0xFF || b[1] > 0xFF || b[2] > 0xFF || b[3] > 0xFF) {\n throw new Error('Invalid IP');\n }\n return (b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]) >>> 0;\n default:\n throw new Error('Invalid IP');\n }\n };\n\n chr = function(b) {\n return b.charCodeAt(0);\n };\n\n chr0 = chr('0');\n\n chra = chr('a');\n\n chrA = chr('A');\n\n atob = function(s) {\n var base, dmax, i, n, start;\n n = 0;\n base = 10;\n dmax = '9';\n i = 0;\n if (s.length > 1 && s[i] === '0') {\n if (s[i + 1] === 'x' || s[i + 1] === 'X') {\n i += 2;\n base = 16;\n } else if ('0' <= s[i + 1] && s[i + 1] <= '9') {\n i++;\n base = 8;\n dmax = '7';\n }\n }\n start = i;\n while (i < s.length) {\n if ('0' <= s[i] && s[i] <= dmax) {\n n = (n * base + (chr(s[i]) - chr0)) >>> 0;\n } else if (base === 16) {\n if ('a' <= s[i] && s[i] <= 'f') {\n n = (n * base + (10 + chr(s[i]) - chra)) >>> 0;\n } else if ('A' <= s[i] && s[i] <= 'F') {\n n = (n * base + (10 + chr(s[i]) - chrA)) >>> 0;\n } else {\n break;\n }\n } else {\n break;\n }\n if (n > 0xFFFFFFFF) {\n throw new Error('too large');\n }\n i++;\n }\n if (i === start) {\n throw new Error('empty octet');\n }\n return [n, i];\n };\n\n Netmask = (function() {\n function Netmask(net, mask) {\n var error, i, j, ref;\n if (typeof net !== 'string') {\n throw new Error(\"Missing `net' parameter\");\n }\n if (!mask) {\n ref = net.split('/', 2), net = ref[0], mask = ref[1];\n }\n if (!mask) {\n mask = 32;\n }\n if (typeof mask === 'string' && mask.indexOf('.') > -1) {\n try {\n this.maskLong = ip2long(mask);\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid mask: \" + mask);\n }\n for (i = j = 32; j >= 0; i = --j) {\n if (this.maskLong === (0xffffffff << (32 - i)) >>> 0) {\n this.bitmask = i;\n break;\n }\n }\n } else if (mask || mask === 0) {\n this.bitmask = parseInt(mask, 10);\n this.maskLong = 0;\n if (this.bitmask > 0) {\n this.maskLong = (0xffffffff << (32 - this.bitmask)) >>> 0;\n }\n } else {\n throw new Error(\"Invalid mask: empty\");\n }\n try {\n this.netLong = (ip2long(net) & this.maskLong) >>> 0;\n } catch (error1) {\n error = error1;\n throw new Error(\"Invalid net address: \" + net);\n }\n if (!(this.bitmask <= 32)) {\n throw new Error(\"Invalid mask for ip4: \" + mask);\n }\n this.size = Math.pow(2, 32 - this.bitmask);\n this.base = long2ip(this.netLong);\n this.mask = long2ip(this.maskLong);\n this.hostmask = long2ip(~this.maskLong);\n this.first = this.bitmask <= 30 ? long2ip(this.netLong + 1) : this.base;\n this.last = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 2) : long2ip(this.netLong + this.size - 1);\n this.broadcast = this.bitmask <= 30 ? long2ip(this.netLong + this.size - 1) : void 0;\n }\n\n Netmask.prototype.contains = function(ip) {\n if (typeof ip === 'string' && (ip.indexOf('/') > 0 || ip.split('.').length !== 4)) {\n ip = new Netmask(ip);\n }\n if (ip instanceof Netmask) {\n return this.contains(ip.base) && this.contains(ip.broadcast || ip.last);\n } else {\n return (ip2long(ip) & this.maskLong) >>> 0 === (this.netLong & this.maskLong) >>> 0;\n }\n };\n\n Netmask.prototype.next = function(count) {\n if (count == null) {\n count = 1;\n }\n return new Netmask(long2ip(this.netLong + (this.size * count)), this.mask);\n };\n\n Netmask.prototype.forEach = function(fn) {\n var index, lastLong, long;\n long = ip2long(this.first);\n lastLong = ip2long(this.last);\n index = 0;\n while (long <= lastLong) {\n fn(long2ip(long), long, index);\n index++;\n long++;\n }\n };\n\n Netmask.prototype.toString = function() {\n return this.base + \"/\" + this.bitmask;\n };\n\n return Netmask;\n\n })();\n\n exports.ip2long = ip2long;\n\n exports.long2ip = long2ip;\n\n exports.Netmask = Netmask;\n\n}).call(this);\n","// full library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index\");\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(\"./enum\"),\n util = require(\"./util\");\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"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\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(\"./namespace\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(\"./enum\"),\n types = require(\"./types\"),\n util = require(\"./util\");\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(\"./index-minimal\");\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(\"./encoder\");\nprotobuf.decoder = require(\"./decoder\");\nprotobuf.verifier = require(\"./verifier\");\nprotobuf.converter = require(\"./converter\");\n\n// Reflection\nprotobuf.ReflectionObject = require(\"./object\");\nprotobuf.Namespace = require(\"./namespace\");\nprotobuf.Root = require(\"./root\");\nprotobuf.Enum = require(\"./enum\");\nprotobuf.Type = require(\"./type\");\nprotobuf.Field = require(\"./field\");\nprotobuf.OneOf = require(\"./oneof\");\nprotobuf.MapField = require(\"./mapfield\");\nprotobuf.Service = require(\"./service\");\nprotobuf.Method = require(\"./method\");\n\n// Runtime\nprotobuf.Message = require(\"./message\");\nprotobuf.wrappers = require(\"./wrappers\");\n\n// Utility\nprotobuf.types = require(\"./types\");\nprotobuf.util = require(\"./util\");\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(\"./writer\");\nprotobuf.BufferWriter = require(\"./writer_buffer\");\nprotobuf.Reader = require(\"./reader\");\nprotobuf.BufferReader = require(\"./reader_buffer\");\n\n// Utility\nprotobuf.util = require(\"./util/minimal\");\nprotobuf.rpc = require(\"./rpc\");\nprotobuf.roots = require(\"./roots\");\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(\"./index-light\");\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(\"./tokenize\");\nprotobuf.parse = require(\"./parse\");\nprotobuf.common = require(\"./common\");\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(\"./field\");\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(\"./types\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(\"./util\");\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(\"./field\"),\n util = require(\"./util\"),\n OneOf = require(\"./oneof\");\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(\"./util\");\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(\"./object\");\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(\"./field\"),\n util = require(\"./util\");\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(\"./tokenize\"),\n Root = require(\"./root\"),\n Type = require(\"./type\"),\n Field = require(\"./field\"),\n MapField = require(\"./mapfield\"),\n OneOf = require(\"./oneof\"),\n Enum = require(\"./enum\"),\n Service = require(\"./service\"),\n Method = require(\"./method\"),\n types = require(\"./types\"),\n util = require(\"./util\");\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n // Syntax is needed to understand the meaning of the optional field rule\n // Otherwise the meaning is ambiguous between proto2 and proto3\n root.setOption(\"syntax\", syntax);\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(\"./reader\");\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(\"./field\"),\n Enum = require(\"./enum\"),\n OneOf = require(\"./oneof\"),\n util = require(\"./util\");\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(\"./rpc/service\");\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(\"../util/minimal\");\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(\"./method\"),\n util = require(\"./util\"),\n rpc = require(\"./rpc\");\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(\"./namespace\");\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(\"./enum\"),\n OneOf = require(\"./oneof\"),\n Field = require(\"./field\"),\n MapField = require(\"./mapfield\"),\n Service = require(\"./service\"),\n Message = require(\"./message\"),\n Reader = require(\"./reader\"),\n Writer = require(\"./writer\"),\n util = require(\"./util\"),\n encoder = require(\"./encoder\"),\n decoder = require(\"./decoder\"),\n verifier = require(\"./verifier\"),\n converter = require(\"./converter\"),\n wrappers = require(\"./wrappers\");\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(\"./util\");\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(\"./util/minimal\");\n\nvar roots = require(\"./roots\");\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(\"@protobufjs/codegen\");\nutil.fetch = require(\"@protobufjs/fetch\");\nutil.path = require(\"@protobufjs/path\");\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n 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(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(\"./type\");\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(\"./enum\");\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(\"./root\"))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(\"../util/minimal\");\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(\"@protobufjs/aspromise\");\n\n// converts to / from base64 encoded strings\nutil.base64 = require(\"@protobufjs/base64\");\n\n// base class of rpc.Service\nutil.EventEmitter = require(\"@protobufjs/eventemitter\");\n\n// float handling accross browsers\nutil.float = require(\"@protobufjs/float\");\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(\"@protobufjs/inquire\");\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(\"@protobufjs/utf8\");\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(\"@protobufjs/pool\");\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(\"./longbits\");\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(\"./enum\"),\n util = require(\"./util\");\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(\"./message\");\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(\"./writer\");\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n","/*!\n * MIT License\n * \n * Copyright (c) 2017-2024 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n'use strict';\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f\\s]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n","module.exports = require('./lib/retry');","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; typeof current == 'object' && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","__webpack_require__.amdO = {};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nexport function alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nexport function allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map","/* eslint-disable no-fallthrough */\nimport { allocUnsafe } from 'uint8arrays/alloc';\nconst N1 = Math.pow(2, 7);\nconst N2 = Math.pow(2, 14);\nconst N3 = Math.pow(2, 21);\nconst N4 = Math.pow(2, 28);\nconst N5 = Math.pow(2, 35);\nconst N6 = Math.pow(2, 42);\nconst N7 = Math.pow(2, 49);\n/** Most significant bit of a byte */\nconst MSB = 0x80;\n/** Rest of the bits in a byte */\nconst REST = 0x7f;\nexport function encodingLength(value) {\n if (value < N1) {\n return 1;\n }\n if (value < N2) {\n return 2;\n }\n if (value < N3) {\n return 3;\n }\n if (value < N4) {\n return 4;\n }\n if (value < N5) {\n return 5;\n }\n if (value < N6) {\n return 6;\n }\n if (value < N7) {\n return 7;\n }\n if (Number.MAX_SAFE_INTEGER != null && value > Number.MAX_SAFE_INTEGER) {\n throw new RangeError('Could not encode varint');\n }\n return 8;\n}\nexport function encodeUint8Array(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 7: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 6: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 5: {\n buf[offset++] = (value & 0xFF) | MSB;\n value /= 128;\n }\n case 4: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 3: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 2: {\n buf[offset++] = (value & 0xFF) | MSB;\n value >>>= 7;\n }\n case 1: {\n buf[offset++] = (value & 0xFF);\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function encodeUint8ArrayList(value, buf, offset = 0) {\n switch (encodingLength(value)) {\n case 8: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 7: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 6: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 5: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value /= 128;\n }\n case 4: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 3: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 2: {\n buf.set(offset++, (value & 0xFF) | MSB);\n value >>>= 7;\n }\n case 1: {\n buf.set(offset++, (value & 0xFF));\n value >>>= 7;\n break;\n }\n default: throw new Error('unreachable');\n }\n return buf;\n}\nexport function decodeUint8Array(buf, offset) {\n let b = buf[offset];\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 1];\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 2];\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 3];\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 4];\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 5];\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 6];\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf[offset + 7];\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function decodeUint8ArrayList(buf, offset) {\n let b = buf.get(offset);\n let res = 0;\n res += b & REST;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 1);\n res += (b & REST) << 7;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 2);\n res += (b & REST) << 14;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 3);\n res += (b & REST) << 21;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 4);\n res += (b & REST) * N4;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 5);\n res += (b & REST) * N5;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 6);\n res += (b & REST) * N6;\n if (b < MSB) {\n return res;\n }\n b = buf.get(offset + 7);\n res += (b & REST) * N7;\n if (b < MSB) {\n return res;\n }\n throw new RangeError('Could not decode varint');\n}\nexport function encode(value, buf, offset = 0) {\n if (buf == null) {\n buf = allocUnsafe(encodingLength(value));\n }\n if (buf instanceof Uint8Array) {\n return encodeUint8Array(value, buf, offset);\n }\n else {\n return encodeUint8ArrayList(value, buf, offset);\n }\n}\nexport function decode(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n return decodeUint8Array(buf, offset);\n }\n else {\n return decodeUint8ArrayList(buf, offset);\n }\n}\n//# sourceMappingURL=index.js.map","const f32 = new Float32Array([-0]);\nconst f8b = new Uint8Array(f32.buffer);\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nexport function writeFloatLE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[0];\n buf[pos + 1] = f8b[1];\n buf[pos + 2] = f8b[2];\n buf[pos + 3] = f8b[3];\n}\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nexport function writeFloatBE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[3];\n buf[pos + 1] = f8b[2];\n buf[pos + 2] = f8b[1];\n buf[pos + 3] = f8b[0];\n}\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nexport function readFloatLE(buf, pos) {\n f8b[0] = buf[pos];\n f8b[1] = buf[pos + 1];\n f8b[2] = buf[pos + 2];\n f8b[3] = buf[pos + 3];\n return f32[0];\n}\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nexport function readFloatBE(buf, pos) {\n f8b[3] = buf[pos];\n f8b[2] = buf[pos + 1];\n f8b[1] = buf[pos + 2];\n f8b[0] = buf[pos + 3];\n return f32[0];\n}\nconst f64 = new Float64Array([-0]);\nconst d8b = new Uint8Array(f64.buffer);\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nexport function writeDoubleLE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[0];\n buf[pos + 1] = d8b[1];\n buf[pos + 2] = d8b[2];\n buf[pos + 3] = d8b[3];\n buf[pos + 4] = d8b[4];\n buf[pos + 5] = d8b[5];\n buf[pos + 6] = d8b[6];\n buf[pos + 7] = d8b[7];\n}\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nexport function writeDoubleBE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[7];\n buf[pos + 1] = d8b[6];\n buf[pos + 2] = d8b[5];\n buf[pos + 3] = d8b[4];\n buf[pos + 4] = d8b[3];\n buf[pos + 5] = d8b[2];\n buf[pos + 6] = d8b[1];\n buf[pos + 7] = d8b[0];\n}\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nexport function readDoubleLE(buf, pos) {\n d8b[0] = buf[pos];\n d8b[1] = buf[pos + 1];\n d8b[2] = buf[pos + 2];\n d8b[3] = buf[pos + 3];\n d8b[4] = buf[pos + 4];\n d8b[5] = buf[pos + 5];\n d8b[6] = buf[pos + 6];\n d8b[7] = buf[pos + 7];\n return f64[0];\n}\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nexport function readDoubleBE(buf, pos) {\n d8b[7] = buf[pos];\n d8b[6] = buf[pos + 1];\n d8b[5] = buf[pos + 2];\n d8b[4] = buf[pos + 3];\n d8b[3] = buf[pos + 4];\n d8b[2] = buf[pos + 5];\n d8b[1] = buf[pos + 6];\n d8b[0] = buf[pos + 7];\n return f64[0];\n}\n//# sourceMappingURL=float.js.map","// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nexport class LongBits {\n lo;\n hi;\n constructor(lo, hi) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n /**\n * Low bits\n */\n this.lo = lo | 0;\n /**\n * High bits\n */\n this.hi = hi | 0;\n }\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber(unsigned = false) {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n }\n /**\n * Converts this long bits to a bigint\n */\n toBigInt(unsigned = false) {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n));\n }\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n /**\n * Converts this long bits to a string\n */\n toString(unsigned = false) {\n return this.toBigInt(unsigned).toString();\n }\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode() {\n const mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = (this.lo << 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode() {\n const mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = (this.hi >>> 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length() {\n const part0 = this.lo;\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;\n const part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt(value) {\n if (value === 0n) {\n return zero;\n }\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value));\n }\n const negative = value < 0n;\n if (negative) {\n value = -value;\n }\n let hi = value >> 32n;\n let lo = value - (hi << 32n);\n if (negative) {\n hi = ~hi | 0n;\n lo = ~lo | 0n;\n if (++lo > TWO_32) {\n lo = 0n;\n if (++hi > TWO_32) {\n hi = 0n;\n }\n }\n }\n return new LongBits(Number(lo), Number(hi));\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber(value) {\n if (value === 0) {\n return zero;\n }\n const sign = value < 0;\n if (sign) {\n value = -value;\n }\n let lo = value >>> 0;\n let hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295) {\n hi = 0;\n }\n }\n }\n return new LongBits(lo, hi);\n }\n /**\n * Constructs new long bits from a number, long or string\n */\n static from(value) {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value);\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value);\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value));\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n }\n}\nconst zero = new LongBits(0, 0);\nzero.toBigInt = function () { return 0n; };\nzero.zzEncode = zero.zzDecode = function () { return this; };\nzero.length = function () { return 1; };\nconst TWO_32 = 4294967296n;\n//# sourceMappingURL=longbits.js.map","/**\n * Calculates the UTF8 byte length of a string\n */\nexport function length(string) {\n let len = 0;\n let c = 0;\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i);\n if (c < 128) {\n len += 1;\n }\n else if (c < 2048) {\n len += 2;\n }\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i;\n len += 4;\n }\n else {\n len += 3;\n }\n }\n return len;\n}\n/**\n * Reads UTF8 bytes as a string\n */\nexport function read(buffer, start, end) {\n const len = end - start;\n if (len < 1) {\n return '';\n }\n let parts;\n const chunk = [];\n let i = 0; // char offset\n let t; // temporary\n while (start < end) {\n t = buffer[start++];\n if (t < 128) {\n chunk[i++] = t;\n }\n else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\n }\n else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\n chunk[i++] = 0xD800 + (t >> 10);\n chunk[i++] = 0xDC00 + (t & 1023);\n }\n else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\n }\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n }\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n/**\n * Writes a string as UTF8 bytes\n */\nexport function write(string, buffer, offset) {\n const start = offset;\n let c1; // character 1\n let c2; // character 2\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i);\n if (c1 < 128) {\n buffer[offset++] = c1;\n }\n else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192;\n buffer[offset++] = c1 & 63 | 128;\n }\n else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\n ++i;\n buffer[offset++] = c1 >> 18 | 240;\n buffer[offset++] = c1 >> 12 & 63 | 128;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n else {\n buffer[offset++] = c1 >> 12 | 224;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n }\n return offset - start;\n}\n//# sourceMappingURL=utf8.js.map","import { decodeUint8Array, encodingLength } from 'uint8-varint';\nimport { readFloatLE, readDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport * as utf8 from './utf8.js';\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);\n}\nfunction readFixed32End(buf, end) {\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0;\n}\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nexport class Uint8ArrayReader {\n buf;\n pos;\n len;\n _slice = Uint8Array.prototype.subarray;\n constructor(buffer) {\n /**\n * Read buffer\n */\n this.buf = buffer;\n /**\n * Read buffer position\n */\n this.pos = 0;\n /**\n * Read buffer length\n */\n this.len = buffer.length;\n }\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32() {\n let value = 4294967295;\n value = (this.buf[this.pos] & 127) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n }\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32() {\n const value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n }\n /**\n * Reads a varint as a boolean\n */\n bool() {\n return this.uint32() !== 0;\n }\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4);\n return res;\n }\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4) | 0;\n return res;\n }\n /**\n * Reads a float (32 bit) as a number\n */\n float() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n }\n /**\n * Reads a double (64 bit float) as a number\n */\n double() {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n }\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes() {\n const length = this.uint32();\n const start = this.pos;\n const end = this.pos + length;\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end);\n }\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string() {\n const bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n }\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip(length) {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n }\n else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n } while ((this.buf[this.pos++] & 128) !== 0);\n }\n return this;\n }\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);\n }\n return this;\n }\n readLongVarint() {\n // tends to deopt with local vars for octet etc.\n const bits = new LongBits(0, 0);\n let i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n i = 0;\n }\n else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n throw Error('invalid varint encoding');\n }\n readFixed64() {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8);\n }\n const lo = readFixed32End(this.buf, this.pos += 4);\n const hi = readFixed32End(this.buf, this.pos += 4);\n return new LongBits(lo, hi);\n }\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64() {\n return this.readLongVarint().toBigInt();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number() {\n return this.readLongVarint().toNumber();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String() {\n return this.readLongVarint().toString();\n }\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64() {\n return this.readLongVarint().toBigInt(true);\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number() {\n const value = decodeUint8Array(this.buf, this.pos);\n this.pos += encodingLength(value);\n return value;\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String() {\n return this.readLongVarint().toString(true);\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64() {\n return this.readLongVarint().zzDecode().toBigInt();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number() {\n return this.readLongVarint().zzDecode().toNumber();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String() {\n return this.readLongVarint().zzDecode().toString();\n }\n /**\n * Reads fixed 64 bits\n */\n fixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String() {\n return this.readFixed64().toString();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String() {\n return this.readFixed64().toString();\n }\n}\nexport function createReader(buf) {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());\n}\n//# sourceMappingURL=reader.js.map","import { createReader } from './utils/reader.js';\nexport function decodeMessage(buf, codec, opts) {\n const reader = createReader(buf);\n return codec.decode(reader, undefined, opts);\n}\n//# sourceMappingURL=decode.js.map","export const empty = new Uint8Array(0);\nexport function toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nexport function fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nexport function equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nexport function coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nexport function isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nexport function fromString(str) {\n return new TextEncoder().encode(str);\n}\nexport function toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map","/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\nexport default _brrp__multiformats_scope_baseX;\n//# sourceMappingURL=base-x.js.map","import { coerce } from '../bytes.js';\nimport basex from '../vendor/base-x.js';\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nexport function or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nexport class Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nexport function from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nexport function baseX({ name, prefix, alphabet }) {\n const { encode, decode } = basex(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => coerce(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nexport function rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map","import { baseX } from './base.js';\nexport const base10 = baseX({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map","import { rfc4648 } from './base.js';\nexport const base16 = rfc4648({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nexport const base16upper = rfc4648({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map","import { rfc4648 } from './base.js';\nexport const base2 = rfc4648({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map","import { from } from './base.js';\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nexport const base256emoji = from({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map","import { rfc4648 } from './base.js';\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map","import { baseX } from './base.js';\nexport const base36 = baseX({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nexport const base36upper = baseX({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map","import { baseX } from './base.js';\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map","import { rfc4648 } from './base.js';\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map","import { rfc4648 } from './base.js';\nexport const base8 = rfc4648({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map","import { fromString, toString } from '../bytes.js';\nimport { from } from './base.js';\nexport const identity = from({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => toString(buf),\n decode: (str) => fromString(str)\n});\n//# sourceMappingURL=identity.js.map","const textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nexport const name = 'json';\nexport const code = 0x0200;\nexport function encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nexport function decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map","import { coerce } from '../bytes.js';\nexport const name = 'raw';\nexport const code = 0x55;\nexport function encode(node) {\n return coerce(node);\n}\nexport function decode(data) {\n return coerce(data);\n}\n//# sourceMappingURL=raw.js.map","/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\nexport default _brrp_varint;\n//# sourceMappingURL=varint.js.map","import varint from './vendor/varint.js';\nexport function decode(data, offset = 0) {\n const code = varint.decode(data, offset);\n return [code, varint.decode.bytes];\n}\nexport function encodeTo(int, target, offset = 0) {\n varint.encode(int, target, offset);\n return target;\n}\nexport function encodingLength(int) {\n return varint.encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map","import { coerce, equals as equalBytes } from '../bytes.js';\nimport * as varint from '../varint.js';\n/**\n * Creates a multihash digest.\n */\nexport function create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = varint.encodingLength(code);\n const digestOffset = sizeOffset + varint.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n varint.encodeTo(code, bytes, 0);\n varint.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode(multihash) {\n const bytes = coerce(multihash);\n const [code, sizeOffset] = varint.decode(bytes);\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nexport function hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map","import { coerce } from '../bytes.js';\nimport * as Digest from './digest.js';\nconst code = 0x0;\nconst name = 'identity';\nconst encode = coerce;\nfunction digest(input) {\n return Digest.create(code, encode(input));\n}\nexport const identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map","import * as Digest from './digest.js';\nexport function from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map","/* global crypto */\nimport { from } from './hasher.js';\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map","import { base32 } from './bases/base32.js';\nimport { base36 } from './bases/base36.js';\nimport { base58btc } from './bases/base58.js';\nimport { coerce } from './bytes.js';\nimport * as Digest from './hashes/digest.js';\nimport * as varint from './varint.js';\n// This way TS will also expose all the types from module\nexport * from './link/interface.js';\nexport function format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? base32.encoder));\n }\n}\nexport function toJSON(link) {\n return {\n '/': format(link)\n };\n}\nexport function fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nexport class CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = Digest.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = Digest.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new Digest.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = varint.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc;\n return [\n base58btc.prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ];\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc;\n return [base58btc.prefix, decoder.decode(source)];\n }\n case base32.prefix: {\n const decoder = base ?? base32;\n return [base32.prefix, decoder.decode(source)];\n }\n case base36.prefix: {\n const decoder = base ?? base36;\n return [base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = varint.encodingLength(version);\n const hashOffset = codeOffset + varint.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n varint.encodeTo(version, bytes, 0);\n varint.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map","import * as base10 from './bases/base10.js';\nimport * as base16 from './bases/base16.js';\nimport * as base2 from './bases/base2.js';\nimport * as base256emoji from './bases/base256emoji.js';\nimport * as base32 from './bases/base32.js';\nimport * as base36 from './bases/base36.js';\nimport * as base58 from './bases/base58.js';\nimport * as base64 from './bases/base64.js';\nimport * as base8 from './bases/base8.js';\nimport * as identityBase from './bases/identity.js';\nimport * as json from './codecs/json.js';\nimport * as raw from './codecs/raw.js';\nimport * as identity from './hashes/identity.js';\nimport * as sha2 from './hashes/sha2.js';\nimport { CID, hasher, digest, varint, bytes } from './index.js';\nexport const bases = { ...identityBase, ...base2, ...base8, ...base10, ...base16, ...base32, ...base36, ...base58, ...base64, ...base256emoji };\nexport const hashes = { ...sha2, ...identity };\nexport const codecs = { raw, json };\nexport { CID, hasher, digest, varint, bytes };\n//# sourceMappingURL=basics.js.map","import { bases } from 'multiformats/basics';\nimport { allocUnsafe } from '#alloc';\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = allocUnsafe(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...bases\n};\nexport default BASES;\n//# sourceMappingURL=bases.js.map","import bases, {} from './util/bases.js';\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function fromString(string, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map","import { encodeUint8Array, encodingLength } from 'uint8-varint';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { writeFloatLE, writeDoubleLE } from './float.js';\nimport { LongBits } from './longbits.js';\nimport pool from './pool.js';\nimport * as utf8 from './utf8.js';\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n fn;\n /**\n * Value byte length\n */\n len;\n /**\n * Next operation\n */\n next;\n /**\n * Value to write\n */\n val;\n constructor(fn, len, val) {\n this.fn = fn;\n this.len = len;\n this.next = undefined;\n this.val = val; // type varies\n }\n}\n/* istanbul ignore next */\nfunction noop() { } // eslint-disable-line no-empty-function\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n head;\n /**\n * Current tail\n */\n tail;\n /**\n * Current buffer length\n */\n len;\n /**\n * Next state\n */\n next;\n constructor(writer) {\n this.head = writer.head;\n this.tail = writer.tail;\n this.len = writer.len;\n this.next = writer.states;\n }\n}\nconst bufferPool = pool();\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc(size) {\n if (globalThis.Buffer != null) {\n return allocUnsafe(size);\n }\n return bufferPool(size);\n}\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter {\n /**\n * Current length\n */\n len;\n /**\n * Operations head\n */\n head;\n /**\n * Operations tail\n */\n tail;\n /**\n * Linked forked states\n */\n states;\n constructor() {\n this.len = 0;\n this.head = new Op(noop, 0, 0);\n this.tail = this.head;\n this.states = null;\n }\n /**\n * Pushes a new operation to the queue\n */\n _push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n }\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5, value)).len;\n return this;\n }\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n }\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value) {\n return this._push(encodeUint8Array, encodingLength(value), value);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value) {\n return this.uint64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value) {\n return this.uint64(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value) {\n return this.uint64Number(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value) {\n return this.uint64String(value);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value) {\n const bits = LongBits.fromBigInt(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value) {\n const bits = LongBits.fromNumber(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value) {\n return this.sint64(BigInt(value));\n }\n /**\n * Writes a boolish value as a varint\n */\n bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n }\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n }\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value) {\n return this.fixed32(value);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value) {\n const bits = LongBits.fromBigInt(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value) {\n const bits = LongBits.fromNumber(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value) {\n return this.fixed64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value) {\n return this.fixed64(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value) {\n return this.fixed64Number(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value) {\n return this.fixed64String(value);\n }\n /**\n * Writes a float (32 bit)\n */\n float(value) {\n return this._push(writeFloatLE, 4, value);\n }\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double(value) {\n return this._push(writeDoubleLE, 8, value);\n }\n /**\n * Writes a sequence of bytes\n */\n bytes(value) {\n const len = value.length >>> 0;\n if (len === 0) {\n return this._push(writeByte, 1, 0);\n }\n return this.uint32(len)._push(writeBytes, len, value);\n }\n /**\n * Writes a string\n */\n string(value) {\n const len = utf8.length(value);\n return len !== 0\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n }\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n }\n /**\n * Resets this instance to the last state\n */\n reset() {\n if (this.states != null) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n }\n else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n }\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim() {\n const head = this.head;\n const tail = this.tail;\n const len = this.len;\n this.reset().uint32(len);\n if (len !== 0) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n }\n /**\n * Finishes the write operation\n */\n finish() {\n let head = this.head.next; // skip noop\n const buf = alloc(this.len);\n let pos = 0;\n while (head != null) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n }\n}\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n next;\n constructor(len, val) {\n super(writeVarint32, len, val);\n this.next = undefined;\n }\n}\nfunction writeVarint64(val, buf, pos) {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\nfunction writeFixed32(val, buf, pos) {\n buf[pos] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\nfunction writeBytes(val, buf, pos) {\n buf.set(val, pos);\n}\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value) {\n const len = value.length >>> 0;\n this.uint32(len);\n if (len > 0) {\n this._push(writeBytesBuffer, len, value);\n }\n return this;\n };\n Uint8ArrayWriter.prototype.string = function (value) {\n const len = globalThis.Buffer.byteLength(value);\n this.uint32(len);\n if (len > 0) {\n this._push(writeStringBuffer, len, value);\n }\n return this;\n };\n}\nfunction writeBytesBuffer(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n utf8.write(val, buf, pos);\n // @ts-expect-error buf isn't a Uint8Array?\n }\n else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos);\n }\n else {\n buf.set(uint8ArrayFromString(val), pos);\n }\n}\n/**\n * Creates a new writer\n */\nexport function createWriter() {\n return new Uint8ArrayWriter();\n}\n//# sourceMappingURL=writer.js.map","import { allocUnsafe } from 'uint8arrays/alloc';\n/**\n * A general purpose buffer pool\n */\nexport default function pool(size) {\n const SIZE = size ?? 8192;\n const MAX = SIZE >>> 1;\n let slab;\n let offset = SIZE;\n return function poolAlloc(size) {\n if (size < 1 || size > MAX) {\n return allocUnsafe(size);\n }\n if (offset + size > SIZE) {\n slab = allocUnsafe(SIZE);\n offset = 0;\n }\n const buf = slab.subarray(offset, offset += size);\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1;\n }\n return buf;\n };\n}\n//# sourceMappingURL=pool.js.map","import { createWriter } from './utils/writer.js';\nexport function encodeMessage(message, codec) {\n const w = createWriter();\n codec.encode(message, w, {\n lengthDelimited: false\n });\n return w.finish();\n}\n//# sourceMappingURL=encode.js.map","// https://developers.google.com/protocol-buffers/docs/encoding#structure\nexport var CODEC_TYPES;\n(function (CODEC_TYPES) {\n CODEC_TYPES[CODEC_TYPES[\"VARINT\"] = 0] = \"VARINT\";\n CODEC_TYPES[CODEC_TYPES[\"BIT64\"] = 1] = \"BIT64\";\n CODEC_TYPES[CODEC_TYPES[\"LENGTH_DELIMITED\"] = 2] = \"LENGTH_DELIMITED\";\n CODEC_TYPES[CODEC_TYPES[\"START_GROUP\"] = 3] = \"START_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"END_GROUP\"] = 4] = \"END_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"BIT32\"] = 5] = \"BIT32\";\n})(CODEC_TYPES || (CODEC_TYPES = {}));\nexport function createCodec(name, type, encode, decode) {\n return {\n name,\n type,\n encode,\n decode\n };\n}\n//# sourceMappingURL=codec.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterRequest;\n(function (FilterRequest) {\n let ContentFilter;\n (function (ContentFilter) {\n let _codec;\n ContentFilter.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(10);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ContentFilter.encode = (obj) => {\n return encodeMessage(obj, ContentFilter.codec());\n };\n ContentFilter.decode = (buf, opts) => {\n return decodeMessage(buf, ContentFilter.codec(), opts);\n };\n })(ContentFilter = FilterRequest.ContentFilter || (FilterRequest.ContentFilter = {}));\n let _codec;\n FilterRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.subscribe != null && obj.subscribe !== false)) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (obj.contentFilters != null) {\n for (const value of obj.contentFilters) {\n w.uint32(26);\n FilterRequest.ContentFilter.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscribe: false,\n topic: '',\n contentFilters: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n case 3: {\n if (opts.limits?.contentFilters != null && obj.contentFilters.length === opts.limits.contentFilters) {\n throw new MaxLengthError('Decode error - map field \"contentFilters\" had too many elements');\n }\n obj.contentFilters.push(FilterRequest.ContentFilter.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.contentFilters$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRequest.encode = (obj) => {\n return encodeMessage(obj, FilterRequest.codec());\n };\n FilterRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRequest.codec(), opts);\n };\n})(FilterRequest || (FilterRequest = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(10);\n WakuMessage.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new MaxLengthError('Decode error - map field \"messages\" had too many elements');\n }\n obj.messages.push(WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var FilterRpc;\n(function (FilterRpc) {\n let _codec;\n FilterRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n FilterRequest.codec().encode(obj.request, w);\n }\n if (obj.push != null) {\n w.uint32(26);\n MessagePush.codec().encode(obj.push, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = FilterRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.push = MessagePush.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.push\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterRpc.encode = (obj) => {\n return encodeMessage(obj, FilterRpc.codec());\n };\n FilterRpc.decode = (buf, opts) => {\n return decodeMessage(buf, FilterRpc.codec(), opts);\n };\n})(FilterRpc || (FilterRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nexport var TopicOnlyMessage;\n(function (TopicOnlyMessage) {\n let _codec;\n TopicOnlyMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n TopicOnlyMessage.encode = (obj) => {\n return encodeMessage(obj, TopicOnlyMessage.codec());\n };\n TopicOnlyMessage.decode = (buf, opts) => {\n return decodeMessage(buf, TopicOnlyMessage.codec(), opts);\n };\n})(TopicOnlyMessage || (TopicOnlyMessage = {}));\n//# sourceMappingURL=topic_only_message.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, enumeration, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var FilterSubscribeRequest;\n(function (FilterSubscribeRequest) {\n let FilterSubscribeType;\n (function (FilterSubscribeType) {\n FilterSubscribeType[\"SUBSCRIBER_PING\"] = \"SUBSCRIBER_PING\";\n FilterSubscribeType[\"SUBSCRIBE\"] = \"SUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE\"] = \"UNSUBSCRIBE\";\n FilterSubscribeType[\"UNSUBSCRIBE_ALL\"] = \"UNSUBSCRIBE_ALL\";\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let __FilterSubscribeTypeValues;\n (function (__FilterSubscribeTypeValues) {\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBER_PING\"] = 0] = \"SUBSCRIBER_PING\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"SUBSCRIBE\"] = 1] = \"SUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE\"] = 2] = \"UNSUBSCRIBE\";\n __FilterSubscribeTypeValues[__FilterSubscribeTypeValues[\"UNSUBSCRIBE_ALL\"] = 3] = \"UNSUBSCRIBE_ALL\";\n })(__FilterSubscribeTypeValues || (__FilterSubscribeTypeValues = {}));\n (function (FilterSubscribeType) {\n FilterSubscribeType.codec = () => {\n return enumeration(__FilterSubscribeTypeValues);\n };\n })(FilterSubscribeType = FilterSubscribeRequest.FilterSubscribeType || (FilterSubscribeRequest.FilterSubscribeType = {}));\n let _codec;\n FilterSubscribeRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.filterSubscribeType != null && __FilterSubscribeTypeValues[obj.filterSubscribeType] !== 0) {\n w.uint32(16);\n FilterSubscribeRequest.FilterSubscribeType.codec().encode(obj.filterSubscribeType, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(82);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentTopics != null) {\n for (const value of obj.contentTopics) {\n w.uint32(90);\n w.string(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n filterSubscribeType: FilterSubscribeType.SUBSCRIBER_PING,\n contentTopics: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.filterSubscribeType = FilterSubscribeRequest.FilterSubscribeType.codec().decode(reader);\n break;\n }\n case 10: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 11: {\n if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {\n throw new MaxLengthError('Decode error - map field \"contentTopics\" had too many elements');\n }\n obj.contentTopics.push(reader.string());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeRequest.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeRequest.codec());\n };\n FilterSubscribeRequest.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeRequest.codec(), opts);\n };\n})(FilterSubscribeRequest || (FilterSubscribeRequest = {}));\nexport var FilterSubscribeResponse;\n(function (FilterSubscribeResponse) {\n let _codec;\n FilterSubscribeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if ((obj.statusCode != null && obj.statusCode !== 0)) {\n w.uint32(80);\n w.uint32(obj.statusCode);\n }\n if (obj.statusDesc != null) {\n w.uint32(90);\n w.string(obj.statusDesc);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n statusCode: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 10: {\n obj.statusCode = reader.uint32();\n break;\n }\n case 11: {\n obj.statusDesc = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n FilterSubscribeResponse.encode = (obj) => {\n return encodeMessage(obj, FilterSubscribeResponse.codec());\n };\n FilterSubscribeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, FilterSubscribeResponse.codec(), opts);\n };\n})(FilterSubscribeResponse || (FilterSubscribeResponse = {}));\nexport var MessagePush;\n(function (MessagePush) {\n let _codec;\n MessagePush.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.wakuMessage != null) {\n w.uint32(10);\n WakuMessage.codec().encode(obj.wakuMessage, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(18);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.wakuMessage = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.wakuMessage\n });\n break;\n }\n case 2: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n MessagePush.encode = (obj) => {\n return encodeMessage(obj, MessagePush.codec());\n };\n MessagePush.decode = (buf, opts) => {\n return decodeMessage(buf, MessagePush.codec(), opts);\n };\n})(MessagePush || (MessagePush = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=filter_v2.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var PushRequest;\n(function (PushRequest) {\n let _codec;\n PushRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.pubsubTopic != null && obj.pubsubTopic !== '')) {\n w.uint32(10);\n w.string(obj.pubsubTopic);\n }\n if (obj.message != null) {\n w.uint32(18);\n WakuMessage.codec().encode(obj.message, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n pubsubTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 2: {\n obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.message\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRequest.encode = (obj) => {\n return encodeMessage(obj, PushRequest.codec());\n };\n PushRequest.decode = (buf, opts) => {\n return decodeMessage(buf, PushRequest.codec(), opts);\n };\n})(PushRequest || (PushRequest = {}));\nexport var PushResponse;\n(function (PushResponse) {\n let _codec;\n PushResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.isSuccess != null && obj.isSuccess !== false)) {\n w.uint32(8);\n w.bool(obj.isSuccess);\n }\n if (obj.info != null) {\n w.uint32(18);\n w.string(obj.info);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n isSuccess: false\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.isSuccess = reader.bool();\n break;\n }\n case 2: {\n obj.info = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushResponse.encode = (obj) => {\n return encodeMessage(obj, PushResponse.codec());\n };\n PushResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PushResponse.codec(), opts);\n };\n})(PushResponse || (PushResponse = {}));\nexport var PushRpc;\n(function (PushRpc) {\n let _codec;\n PushRpc.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.request != null) {\n w.uint32(18);\n PushRequest.codec().encode(obj.request, w);\n }\n if (obj.response != null) {\n w.uint32(26);\n PushResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.request = PushRequest.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.request\n });\n break;\n }\n case 3: {\n obj.response = PushResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PushRpc.encode = (obj) => {\n return encodeMessage(obj, PushRpc.codec());\n };\n PushRpc.decode = (buf, opts) => {\n return decodeMessage(buf, PushRpc.codec(), opts);\n };\n})(PushRpc || (PushRpc = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=light_push.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var WakuMessageKeyValue;\n(function (WakuMessageKeyValue) {\n let _codec;\n WakuMessageKeyValue.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messageHash != null) {\n w.uint32(10);\n w.bytes(obj.messageHash);\n }\n if (obj.message != null) {\n w.uint32(18);\n WakuMessage.codec().encode(obj.message, w);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(26);\n w.string(obj.pubsubTopic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.messageHash = reader.bytes();\n break;\n }\n case 2: {\n obj.message = WakuMessage.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.message\n });\n break;\n }\n case 3: {\n obj.pubsubTopic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessageKeyValue.encode = (obj) => {\n return encodeMessage(obj, WakuMessageKeyValue.codec());\n };\n WakuMessageKeyValue.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessageKeyValue.codec(), opts);\n };\n})(WakuMessageKeyValue || (WakuMessageKeyValue = {}));\nexport var StoreQueryRequest;\n(function (StoreQueryRequest) {\n let _codec;\n StoreQueryRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if ((obj.includeData != null && obj.includeData !== false)) {\n w.uint32(16);\n w.bool(obj.includeData);\n }\n if (obj.pubsubTopic != null) {\n w.uint32(82);\n w.string(obj.pubsubTopic);\n }\n if (obj.contentTopics != null) {\n for (const value of obj.contentTopics) {\n w.uint32(90);\n w.string(value);\n }\n }\n if (obj.timeStart != null) {\n w.uint32(96);\n w.sint64(obj.timeStart);\n }\n if (obj.timeEnd != null) {\n w.uint32(104);\n w.sint64(obj.timeEnd);\n }\n if (obj.messageHashes != null) {\n for (const value of obj.messageHashes) {\n w.uint32(162);\n w.bytes(value);\n }\n }\n if (obj.paginationCursor != null) {\n w.uint32(410);\n w.bytes(obj.paginationCursor);\n }\n if ((obj.paginationForward != null && obj.paginationForward !== false)) {\n w.uint32(416);\n w.bool(obj.paginationForward);\n }\n if (obj.paginationLimit != null) {\n w.uint32(424);\n w.uint64(obj.paginationLimit);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n includeData: false,\n contentTopics: [],\n messageHashes: [],\n paginationForward: false\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 2: {\n obj.includeData = reader.bool();\n break;\n }\n case 10: {\n obj.pubsubTopic = reader.string();\n break;\n }\n case 11: {\n if (opts.limits?.contentTopics != null && obj.contentTopics.length === opts.limits.contentTopics) {\n throw new MaxLengthError('Decode error - map field \"contentTopics\" had too many elements');\n }\n obj.contentTopics.push(reader.string());\n break;\n }\n case 12: {\n obj.timeStart = reader.sint64();\n break;\n }\n case 13: {\n obj.timeEnd = reader.sint64();\n break;\n }\n case 20: {\n if (opts.limits?.messageHashes != null && obj.messageHashes.length === opts.limits.messageHashes) {\n throw new MaxLengthError('Decode error - map field \"messageHashes\" had too many elements');\n }\n obj.messageHashes.push(reader.bytes());\n break;\n }\n case 51: {\n obj.paginationCursor = reader.bytes();\n break;\n }\n case 52: {\n obj.paginationForward = reader.bool();\n break;\n }\n case 53: {\n obj.paginationLimit = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n StoreQueryRequest.encode = (obj) => {\n return encodeMessage(obj, StoreQueryRequest.codec());\n };\n StoreQueryRequest.decode = (buf, opts) => {\n return decodeMessage(buf, StoreQueryRequest.codec(), opts);\n };\n})(StoreQueryRequest || (StoreQueryRequest = {}));\nexport var StoreQueryResponse;\n(function (StoreQueryResponse) {\n let _codec;\n StoreQueryResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.requestId != null && obj.requestId !== '')) {\n w.uint32(10);\n w.string(obj.requestId);\n }\n if (obj.statusCode != null) {\n w.uint32(80);\n w.uint32(obj.statusCode);\n }\n if (obj.statusDesc != null) {\n w.uint32(90);\n w.string(obj.statusDesc);\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(162);\n WakuMessageKeyValue.codec().encode(value, w);\n }\n }\n if (obj.paginationCursor != null) {\n w.uint32(410);\n w.bytes(obj.paginationCursor);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n requestId: '',\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.requestId = reader.string();\n break;\n }\n case 10: {\n obj.statusCode = reader.uint32();\n break;\n }\n case 11: {\n obj.statusDesc = reader.string();\n break;\n }\n case 20: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new MaxLengthError('Decode error - map field \"messages\" had too many elements');\n }\n obj.messages.push(WakuMessageKeyValue.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.messages$\n }));\n break;\n }\n case 51: {\n obj.paginationCursor = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n StoreQueryResponse.encode = (obj) => {\n return encodeMessage(obj, StoreQueryResponse.codec());\n };\n StoreQueryResponse.decode = (buf, opts) => {\n return decodeMessage(buf, StoreQueryResponse.codec(), opts);\n };\n})(StoreQueryResponse || (StoreQueryResponse = {}));\nexport var RateLimitProof;\n(function (RateLimitProof) {\n let _codec;\n RateLimitProof.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.proof != null && obj.proof.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.proof);\n }\n if ((obj.merkleRoot != null && obj.merkleRoot.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.merkleRoot);\n }\n if ((obj.epoch != null && obj.epoch.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.epoch);\n }\n if ((obj.shareX != null && obj.shareX.byteLength > 0)) {\n w.uint32(34);\n w.bytes(obj.shareX);\n }\n if ((obj.shareY != null && obj.shareY.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.shareY);\n }\n if ((obj.nullifier != null && obj.nullifier.byteLength > 0)) {\n w.uint32(50);\n w.bytes(obj.nullifier);\n }\n if ((obj.rlnIdentifier != null && obj.rlnIdentifier.byteLength > 0)) {\n w.uint32(58);\n w.bytes(obj.rlnIdentifier);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n proof: uint8ArrayAlloc(0),\n merkleRoot: uint8ArrayAlloc(0),\n epoch: uint8ArrayAlloc(0),\n shareX: uint8ArrayAlloc(0),\n shareY: uint8ArrayAlloc(0),\n nullifier: uint8ArrayAlloc(0),\n rlnIdentifier: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.proof = reader.bytes();\n break;\n }\n case 2: {\n obj.merkleRoot = reader.bytes();\n break;\n }\n case 3: {\n obj.epoch = reader.bytes();\n break;\n }\n case 4: {\n obj.shareX = reader.bytes();\n break;\n }\n case 5: {\n obj.shareY = reader.bytes();\n break;\n }\n case 6: {\n obj.nullifier = reader.bytes();\n break;\n }\n case 7: {\n obj.rlnIdentifier = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RateLimitProof.encode = (obj) => {\n return encodeMessage(obj, RateLimitProof.codec());\n };\n RateLimitProof.decode = (buf, opts) => {\n return decodeMessage(buf, RateLimitProof.codec(), opts);\n };\n})(RateLimitProof || (RateLimitProof = {}));\nexport var WakuMessage;\n(function (WakuMessage) {\n let _codec;\n WakuMessage.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.payload);\n }\n if ((obj.contentTopic != null && obj.contentTopic !== '')) {\n w.uint32(18);\n w.string(obj.contentTopic);\n }\n if (obj.version != null) {\n w.uint32(24);\n w.uint32(obj.version);\n }\n if (obj.timestamp != null) {\n w.uint32(80);\n w.sint64(obj.timestamp);\n }\n if (obj.meta != null) {\n w.uint32(90);\n w.bytes(obj.meta);\n }\n if (obj.rateLimitProof != null) {\n w.uint32(170);\n RateLimitProof.codec().encode(obj.rateLimitProof, w);\n }\n if (obj.ephemeral != null) {\n w.uint32(248);\n w.bool(obj.ephemeral);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n payload: uint8ArrayAlloc(0),\n contentTopic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.payload = reader.bytes();\n break;\n }\n case 2: {\n obj.contentTopic = reader.string();\n break;\n }\n case 3: {\n obj.version = reader.uint32();\n break;\n }\n case 10: {\n obj.timestamp = reader.sint64();\n break;\n }\n case 11: {\n obj.meta = reader.bytes();\n break;\n }\n case 21: {\n obj.rateLimitProof = RateLimitProof.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.rateLimitProof\n });\n break;\n }\n case 31: {\n obj.ephemeral = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMessage.encode = (obj) => {\n return encodeMessage(obj, WakuMessage.codec());\n };\n WakuMessage.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMessage.codec(), opts);\n };\n})(WakuMessage || (WakuMessage = {}));\n//# sourceMappingURL=store_v3.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nexport var PeerInfo;\n(function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.enr != null) {\n w.uint32(10);\n w.bytes(obj.enr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.enr = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return encodeMessage(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return decodeMessage(buf, PeerInfo.codec(), opts);\n };\n})(PeerInfo || (PeerInfo = {}));\nexport var PeerExchangeQuery;\n(function (PeerExchangeQuery) {\n let _codec;\n PeerExchangeQuery.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.numPeers != null) {\n w.uint32(8);\n w.uint64(obj.numPeers);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.numPeers = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeQuery.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeQuery.codec());\n };\n PeerExchangeQuery.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeQuery.codec(), opts);\n };\n})(PeerExchangeQuery || (PeerExchangeQuery = {}));\nexport var PeerExchangeResponse;\n(function (PeerExchangeResponse) {\n let _codec;\n PeerExchangeResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerInfos != null) {\n for (const value of obj.peerInfos) {\n w.uint32(10);\n PeerInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peerInfos: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.peerInfos != null && obj.peerInfos.length === opts.limits.peerInfos) {\n throw new MaxLengthError('Decode error - map field \"peerInfos\" had too many elements');\n }\n obj.peerInfos.push(PeerInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.peerInfos$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeResponse.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeResponse.codec());\n };\n PeerExchangeResponse.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeResponse.codec(), opts);\n };\n})(PeerExchangeResponse || (PeerExchangeResponse = {}));\nexport var PeerExchangeRPC;\n(function (PeerExchangeRPC) {\n let _codec;\n PeerExchangeRPC.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.query != null) {\n w.uint32(10);\n PeerExchangeQuery.codec().encode(obj.query, w);\n }\n if (obj.response != null) {\n w.uint32(18);\n PeerExchangeResponse.codec().encode(obj.response, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.query = PeerExchangeQuery.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.query\n });\n break;\n }\n case 2: {\n obj.response = PeerExchangeResponse.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.response\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerExchangeRPC.encode = (obj) => {\n return encodeMessage(obj, PeerExchangeRPC.codec());\n };\n PeerExchangeRPC.decode = (buf, opts) => {\n return decodeMessage(buf, PeerExchangeRPC.codec(), opts);\n };\n})(PeerExchangeRPC || (PeerExchangeRPC = {}));\n//# sourceMappingURL=peer_exchange.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nexport var WakuMetadataRequest;\n(function (WakuMetadataRequest) {\n let _codec;\n WakuMetadataRequest.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new MaxLengthError('Decode error - map field \"shards\" had too many elements');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataRequest.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataRequest.codec());\n };\n WakuMetadataRequest.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataRequest.codec(), opts);\n };\n})(WakuMetadataRequest || (WakuMetadataRequest = {}));\nexport var WakuMetadataResponse;\n(function (WakuMetadataResponse) {\n let _codec;\n WakuMetadataResponse.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.clusterId != null) {\n w.uint32(8);\n w.uint32(obj.clusterId);\n }\n if (obj.shards != null) {\n for (const value of obj.shards) {\n w.uint32(16);\n w.uint32(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n shards: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.clusterId = reader.uint32();\n break;\n }\n case 2: {\n if (opts.limits?.shards != null && obj.shards.length === opts.limits.shards) {\n throw new MaxLengthError('Decode error - map field \"shards\" had too many elements');\n }\n obj.shards.push(reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n WakuMetadataResponse.encode = (obj) => {\n return encodeMessage(obj, WakuMetadataResponse.codec());\n };\n WakuMetadataResponse.decode = (buf, opts) => {\n return decodeMessage(buf, WakuMetadataResponse.codec(), opts);\n };\n})(WakuMetadataResponse || (WakuMetadataResponse = {}));\n//# sourceMappingURL=metadata.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function enumeration(v) {\n function findValue(val) {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value');\n }\n return v[val];\n }\n const encode = function enumEncode(val, writer) {\n const enumValue = findValue(val);\n writer.int32(enumValue);\n };\n const decode = function enumDecode(reader) {\n const val = reader.int32();\n return findValue(val);\n };\n // @ts-expect-error yeah yeah\n return createCodec('enum', CODEC_TYPES.VARINT, encode, decode);\n}\n//# sourceMappingURL=enum.js.map","import { createCodec, CODEC_TYPES } from '../codec.js';\nexport function message(encode, decode) {\n return createCodec('message', CODEC_TYPES.LENGTH_DELIMITED, encode, decode);\n}\n//# sourceMappingURL=message.js.map","/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\nexport { decodeMessage } from './decode.js';\nexport { encodeMessage } from './encode.js';\nexport { enumeration } from './codecs/enum.js';\nexport { message } from './codecs/message.js';\nexport { createReader as reader } from './utils/reader.js';\nexport { createWriter as writer } from './utils/writer.js';\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * Thrown when a repeated field has too many elements\n */\nexport class MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_LENGTH';\n name = 'MaxLengthError';\n}\n/**\n * Thrown when a map has too many elements\n */\nexport class MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_SIZE';\n name = 'MaxSizeError';\n}\nexport class ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_PARSE_ERROR';\n name = 'ParseError';\n}\nexport class NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_NO_MESSAGES_FOUND';\n name = 'NoMessagesFoundError';\n}\n//# sourceMappingURL=index.js.map","export function isDefined(value) {\n return Boolean(value);\n}\n//# sourceMappingURL=is_defined.js.map","export function groupByContentTopic(values) {\n const groupedDecoders = new Map();\n values.forEach((value) => {\n let decs = groupedDecoders.get(value.contentTopic);\n if (!decs) {\n groupedDecoders.set(value.contentTopic, []);\n decs = groupedDecoders.get(value.contentTopic);\n }\n decs.push(value);\n });\n return groupedDecoders;\n}\n//# sourceMappingURL=group_by.js.map","const FRAME_RATE = 60;\n/**\n * Function that transforms IReceiver subscription to iterable stream of data.\n * @param receiver - object that allows to be subscribed to;\n * @param decoder - parameter to be passed to receiver for subscription;\n * @param options - options for receiver for subscription;\n * @param iteratorOptions - optional configuration for iterator;\n * @returns iterator and stop function to terminate it.\n */\nexport async function toAsyncIterator(receiver, decoder, iteratorOptions) {\n const iteratorDelay = iteratorOptions?.iteratorDelay ?? FRAME_RATE;\n const messages = [];\n let unsubscribe;\n unsubscribe = await receiver.subscribeWithUnsubscribe(decoder, (message) => {\n messages.push(message);\n });\n const isWithTimeout = Number.isInteger(iteratorOptions?.timeoutMs);\n const timeoutMs = iteratorOptions?.timeoutMs ?? 0;\n const startTime = Date.now();\n async function* iterator() {\n while (true) {\n if (isWithTimeout && Date.now() - startTime >= timeoutMs) {\n return;\n }\n await wait(iteratorDelay);\n const message = messages.shift();\n if (!unsubscribe && messages.length === 0) {\n return message;\n }\n if (!message && unsubscribe) {\n continue;\n }\n yield message;\n }\n }\n return {\n iterator: iterator(),\n async stop() {\n if (unsubscribe) {\n await unsubscribe();\n unsubscribe = undefined;\n }\n }\n };\n}\nfunction wait(ms) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n//# sourceMappingURL=to_async_iterator.js.map","/**\n * Internal assertion helpers.\n * @module\n */\n/** Asserts something is positive integer. */\nfunction anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Is number an Uint8Array? Copied from utils for perf. */\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\nexport { anumber, abytes, ahash, aexists, aoutput };\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n// Cast array to different type\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n// Cast array to view\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const byteSwapIfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Convert JS string to byte array.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { aexists, aoutput } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map","/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/** SHA2-256 hash function */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\n/** SHA2-224 hash function */\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","export var Protocols;\n(function (Protocols) {\n Protocols[\"Relay\"] = \"relay\";\n Protocols[\"Store\"] = \"store\";\n Protocols[\"LightPush\"] = \"lightpush\";\n Protocols[\"Filter\"] = \"filter\";\n})(Protocols || (Protocols = {}));\nexport var ProtocolError;\n(function (ProtocolError) {\n /** Could not determine the origin of the fault. Best to check connectivity and try again */\n ProtocolError[\"GENERIC_FAIL\"] = \"Generic error\";\n /**\n * Failure to protobuf encode the message. This is not recoverable and needs\n * further investigation.\n */\n ProtocolError[\"ENCODE_FAILED\"] = \"Failed to encode\";\n /**\n * Failure to protobuf decode the message. May be due to a remote peer issue,\n * ensuring that messages are sent via several peer enable mitigation of this error.\n */\n ProtocolError[\"DECODE_FAILED\"] = \"Failed to decode\";\n /**\n * The message payload is empty, making the message invalid. Ensure that a non-empty\n * payload is set on the outgoing message.\n */\n ProtocolError[\"EMPTY_PAYLOAD\"] = \"Payload is empty\";\n /**\n * The message size is above the maximum message size allowed on the Waku Network.\n * Compressing the message or using an alternative strategy for large messages is recommended.\n */\n ProtocolError[\"SIZE_TOO_BIG\"] = \"Size is too big\";\n /**\n * The PubsubTopic passed to the send function is not configured on the Waku node.\n * Please ensure that the PubsubTopic is used when initializing the Waku node.\n */\n ProtocolError[\"TOPIC_NOT_CONFIGURED\"] = \"Topic not configured\";\n /**\n * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.\n * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.\n */\n ProtocolError[\"TOPIC_DECODER_MISMATCH\"] = \"Topic decoder mismatch\";\n /**\n * The topics passed in the decoders do not match each other, or don't exist at all.\n * Ensure that all the pubsub topics used in the decoders are valid and match each other.\n */\n ProtocolError[\"INVALID_DECODER_TOPICS\"] = \"Invalid decoder topics\";\n /**\n * Failure to find a peer with suitable protocols. This may due to a connection issue.\n * Mitigation can be: retrying after a given time period, display connectivity issue\n * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`\n * on the connection manager before retrying.\n */\n ProtocolError[\"NO_PEER_AVAILABLE\"] = \"No peer available\";\n /**\n * Failure to find a stream to the peer. This may be because the connection with the peer is not still alive.\n * Mitigation can be: retrying after a given time period, or mitigation for `NO_PEER_AVAILABLE` can be used.\n */\n ProtocolError[\"NO_STREAM_AVAILABLE\"] = \"No stream available\";\n /**\n * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"NO_RESPONSE\"] = \"No response received\";\n /**\n * The remote peer rejected the message. Information provided by the remote peer\n * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"REMOTE_PEER_REJECTED\"] = \"Remote peer rejected\";\n /**\n * The protocol request timed out without a response. This may be due to a connection issue.\n * Mitigation can be: retrying after a given time period\n */\n ProtocolError[\"REQUEST_TIMEOUT\"] = \"Request timeout\";\n /**\n * Missing credentials info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L186\n */\n ProtocolError[\"RLN_IDENTITY_MISSING\"] = \"Identity credentials are not set\";\n /**\n * Membership index missing info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L188\n */\n ProtocolError[\"RLN_MEMBERSHIP_INDEX\"] = \"Membership index is not set\";\n /**\n * Message limit is missing.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L190\n */\n ProtocolError[\"RLN_LIMIT_MISSING\"] = \"User message limit is not set\";\n /**\n * General proof generation error message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42\n */\n ProtocolError[\"RLN_PROOF_GENERATION\"] = \"Proof generation failed\";\n})(ProtocolError || (ProtocolError = {}));\n//# sourceMappingURL=protocols.js.map","export var Tags;\n(function (Tags) {\n Tags[\"BOOTSTRAP\"] = \"bootstrap\";\n Tags[\"PEER_EXCHANGE\"] = \"peer-exchange\";\n Tags[\"LOCAL\"] = \"local-peer-cache\";\n})(Tags || (Tags = {}));\nexport var EPeersByDiscoveryEvents;\n(function (EPeersByDiscoveryEvents) {\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_BOOTSTRAP\"] = \"peer:discovery:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_PEER_EXCHANGE\"] = \"peer:discovery:peer-exchange\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_BOOTSTRAP\"] = \"peer:connected:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_PEER_EXCHANGE\"] = \"peer:connected:peer-exchange\";\n})(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));\nexport var EConnectionStateEvents;\n(function (EConnectionStateEvents) {\n EConnectionStateEvents[\"CONNECTION_STATUS\"] = \"waku:connection\";\n})(EConnectionStateEvents || (EConnectionStateEvents = {}));\n//# sourceMappingURL=connection_manager.js.map","export const DNS_DISCOVERY_TAG = \"@waku/bootstrap\";\n//# sourceMappingURL=dns_discovery.js.map","/**\n * The default cluster ID for The Waku Network\n */\nexport const DEFAULT_CLUSTER_ID = 1;\n/**\n * DefaultShardInfo is default configuration for The Waku Network.\n */\nexport const DefaultShardInfo = {\n clusterId: DEFAULT_CLUSTER_ID,\n shards: [0, 1, 2, 3, 4, 5, 6, 7, 8]\n};\nexport const DefaultNetworkConfig = DefaultShardInfo;\n//# sourceMappingURL=constants.js.map","export var HealthStatus;\n(function (HealthStatus) {\n HealthStatus[\"Unhealthy\"] = \"Unhealthy\";\n HealthStatus[\"MinimallyHealthy\"] = \"MinimallyHealthy\";\n HealthStatus[\"SufficientlyHealthy\"] = \"SufficientlyHealthy\";\n})(HealthStatus || (HealthStatus = {}));\n//# sourceMappingURL=health_manager.js.map","import bases, {} from './util/bases.js';\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nexport function toString(array, encoding = 'utf8') {\n const base = bases[encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map","import { fromString } from \"uint8arrays/from-string\";\nimport { toString } from \"uint8arrays/to-string\";\n/**\n * Convert input to a byte array.\n *\n * Handles both `0x` prefixed and non-prefixed strings.\n */\nexport function hexToBytes(hex) {\n if (typeof hex === \"string\") {\n const _hex = hex.replace(/^0x/i, \"\");\n return fromString(_hex.toLowerCase(), \"base16\");\n }\n return hex;\n}\nexport function numberToBytes(value) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof value === \"number\") {\n view.setFloat64(0, value, false);\n }\n else {\n view.setBigInt64(0, value, false);\n }\n return new Uint8Array(buffer);\n}\n/**\n * Convert byte array to hex string (no `0x` prefix).\n */\nexport const bytesToHex = (bytes) => toString(bytes, \"base16\");\n/**\n * Decode byte array to utf-8 string.\n */\nexport const bytesToUtf8 = (b) => toString(b, \"utf8\");\n/**\n * Encode utf-8 string to byte array.\n */\nexport const utf8ToBytes = (s) => fromString(s, \"utf8\");\n/**\n * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`\n */\nexport function concat(byteArrays, totalLength) {\n const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);\n const res = new Uint8Array(len);\n let offset = 0;\n for (const bytes of byteArrays) {\n res.set(bytes, offset);\n offset += bytes.length;\n }\n return res;\n}\n//# sourceMappingURL=index.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { DEFAULT_CLUSTER_ID } from \"@waku/interfaces\";\nimport { concat, utf8ToBytes } from \"../../bytes/index.js\";\nimport { isAutoSharding, isStaticSharding } from \"./type_guards.js\";\nexport * from \"./type_guards.js\";\nexport function derivePubsubTopicsFromNetworkConfig(networkConfig) {\n if (isStaticSharding(networkConfig)) {\n if (networkConfig.shards.length === 0) {\n throw new Error(\"Invalid shards configuration: please provide at least one shard\");\n }\n return shardInfoToPubsubTopics(networkConfig);\n }\n else if (isAutoSharding(networkConfig)) {\n if (networkConfig.contentTopics.length === 0) {\n throw new Error(\"Invalid content topics configuration: please provide at least one content topic\");\n }\n return networkConfig.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, networkConfig.clusterId));\n }\n else {\n throw new Error(\"Unknown shard config. Please use ShardInfo or ContentTopicInfo\");\n }\n}\nexport const singleShardInfoToPubsubTopic = (shardInfo) => {\n if (shardInfo.shard === undefined)\n throw new Error(\"Invalid shard\");\n return `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${shardInfo.shard}`;\n};\nexport const singleShardInfosToShardInfo = (singleShardInfos) => {\n if (singleShardInfos.length === 0)\n throw new Error(\"Invalid shard\");\n const clusterIds = singleShardInfos.map((shardInfo) => shardInfo.clusterId);\n if (new Set(clusterIds).size !== 1) {\n throw new Error(\"Passed shard infos have different clusterIds\");\n }\n const shards = singleShardInfos\n .map((shardInfo) => shardInfo.shard)\n .filter((shard) => shard !== undefined);\n return {\n clusterId: singleShardInfos[0].clusterId,\n shards\n };\n};\nexport const shardInfoToPubsubTopics = (shardInfo) => {\n if (\"contentTopics\" in shardInfo && shardInfo.contentTopics) {\n // Autosharding: explicitly defined content topics\n return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));\n }\n else if (\"shards\" in shardInfo) {\n // Static sharding\n if (shardInfo.shards === undefined)\n throw new Error(\"Invalid shard\");\n return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? DEFAULT_CLUSTER_ID}/${index}`)));\n }\n else if (\"application\" in shardInfo && \"version\" in shardInfo) {\n // Autosharding: single shard from application and version\n return [\n contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`, shardInfo.clusterId)\n ];\n }\n else {\n throw new Error(\"Missing required configuration in shard parameters\");\n }\n};\nexport const pubsubTopicToSingleShardInfo = (pubsubTopics) => {\n const parts = pubsubTopics.split(\"/\");\n if (parts.length != 6 ||\n parts[1] !== \"waku\" ||\n parts[2] !== \"2\" ||\n parts[3] !== \"rs\")\n throw new Error(\"Invalid pubsub topic\");\n const clusterId = parseInt(parts[4]);\n const shard = parseInt(parts[5]);\n if (isNaN(clusterId) || isNaN(shard))\n throw new Error(\"Invalid clusterId or shard\");\n return {\n clusterId,\n shard\n };\n};\nexport const pubsubTopicsToShardInfo = (pubsubTopics) => {\n const shardInfoSet = new Set();\n const clusterIds = new Set();\n for (const topic of pubsubTopics) {\n const { clusterId, shard } = pubsubTopicToSingleShardInfo(topic);\n shardInfoSet.add(`${clusterId}:${shard}`);\n clusterIds.add(clusterId);\n }\n if (shardInfoSet.size === 0) {\n throw new Error(\"No valid pubsub topics provided\");\n }\n if (clusterIds.size > 1) {\n throw new Error(\"Pubsub topics from multiple cluster IDs are not supported\");\n }\n const clusterId = clusterIds.values().next().value;\n const shards = Array.from(shardInfoSet).map((info) => parseInt(info.split(\":\")[1]));\n return {\n clusterId,\n shards\n };\n};\n//TODO: move part of BaseProtocol instead of utils\n// return `ProtocolError.TOPIC_NOT_CONFIGURED` instead of throwing\nexport function ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {\n if (!configuredTopics.includes(pubsubTopic)) {\n throw new Error(`Pubsub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);\n }\n}\n/**\n * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/\n * @param contentTopic String to validate\n * @returns Object with each content topic field as an attribute\n */\nexport function ensureValidContentTopic(contentTopic) {\n const parts = contentTopic.split(\"/\");\n if (parts.length < 5 || parts.length > 6) {\n throw Error(\"Content topic format is invalid\");\n }\n // Validate generation field if present\n let generation = 0;\n if (parts.length == 6) {\n generation = parseInt(parts[1]);\n if (isNaN(generation)) {\n throw new Error(\"Invalid generation field in content topic\");\n }\n if (generation > 0) {\n throw new Error(\"Generation greater than 0 is not supported\");\n }\n }\n // Validate remaining fields\n const fields = parts.splice(-4);\n // Validate application field\n if (fields[0].length == 0) {\n throw new Error(\"Application field cannot be empty\");\n }\n // Validate version field\n if (fields[1].length == 0) {\n throw new Error(\"Version field cannot be empty\");\n }\n // Validate topic name field\n if (fields[2].length == 0) {\n throw new Error(\"Topic name field cannot be empty\");\n }\n // Validate encoding field\n if (fields[3].length == 0) {\n throw new Error(\"Encoding field cannot be empty\");\n }\n return {\n generation,\n application: fields[0],\n version: fields[1],\n topicName: fields[2],\n encoding: fields[3]\n };\n}\n/**\n * Given a string, determines which autoshard index to use for its pubsub topic.\n * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm\n */\nexport function contentTopicToShardIndex(contentTopic, networkShards = 8) {\n const { application, version } = ensureValidContentTopic(contentTopic);\n const digest = sha256(concat([utf8ToBytes(application), utf8ToBytes(version)]));\n const dataview = new DataView(digest.buffer.slice(-8));\n return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));\n}\nexport function contentTopicToPubsubTopic(contentTopic, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n if (!contentTopic) {\n throw Error(\"Content topic must be specified\");\n }\n const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);\n return `/waku/2/rs/${clusterId}/${shardIndex}`;\n}\n/**\n * Given an array of content topics, groups them together by their Pubsub topic as derived using the algorithm for autosharding.\n * If any of the content topics are not properly formatted, the function will throw an error.\n */\nexport function contentTopicsByPubsubTopic(contentTopics, clusterId = DEFAULT_CLUSTER_ID, networkShards = 8) {\n const groupedContentTopics = new Map();\n for (const contentTopic of contentTopics) {\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic, clusterId, networkShards);\n let topics = groupedContentTopics.get(pubsubTopic);\n if (!topics) {\n groupedContentTopics.set(pubsubTopic, []);\n topics = groupedContentTopics.get(pubsubTopic);\n }\n topics.push(contentTopic);\n }\n return groupedContentTopics;\n}\n/**\n * Used when creating encoders/decoders to determine which pubsub topic to use\n */\nexport function determinePubsubTopic(contentTopic, \n// TODO: make it accept ShardInfo https://github.com/waku-org/js-waku/issues/2086\npubsubTopicShardInfo) {\n if (typeof pubsubTopicShardInfo == \"string\") {\n return pubsubTopicShardInfo;\n }\n return pubsubTopicShardInfo?.shard !== undefined\n ? singleShardInfoToPubsubTopic(pubsubTopicShardInfo)\n : contentTopicToPubsubTopic(contentTopic, pubsubTopicShardInfo?.clusterId ?? DEFAULT_CLUSTER_ID);\n}\n/**\n * Validates sharding configuration and sets defaults where possible.\n * @returns Validated sharding parameters, with any missing values set to defaults\n */\nexport const ensureShardingConfigured = (networkConfig) => {\n const clusterId = networkConfig.clusterId ?? DEFAULT_CLUSTER_ID;\n const shards = \"shards\" in networkConfig ? networkConfig.shards : [];\n const contentTopics = \"contentTopics\" in networkConfig ? networkConfig.contentTopics : [];\n const isShardsConfigured = shards && shards.length > 0;\n const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;\n if (isShardsConfigured) {\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })\n };\n }\n if (isContentTopicsConfigured) {\n const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));\n const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics\n };\n }\n throw new Error(\"Missing minimum required configuration options for static sharding or autosharding.\");\n};\n//# sourceMappingURL=index.js.map","export const decodeRelayShard = (bytes) => {\n // explicitly converting to Uint8Array to avoid Buffer\n // https://github.com/libp2p/js-libp2p/issues/2146\n bytes = new Uint8Array(bytes);\n if (bytes.length < 3)\n throw new Error(\"Insufficient data\");\n const view = new DataView(bytes.buffer);\n const clusterId = view.getUint16(0);\n const shards = [];\n if (bytes.length === 130) {\n // rsv format (Bit Vector)\n for (let i = 0; i < 1024; i++) {\n const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (i % 8);\n if (view.getUint8(byteIndex) & (1 << bitIndex)) {\n shards.push(i);\n }\n }\n }\n else {\n // rs format (Index List)\n const numIndices = view.getUint8(2);\n for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {\n if (offset + 1 >= bytes.length)\n throw new Error(\"Unexpected end of data\");\n shards.push(view.getUint16(offset));\n }\n }\n return { clusterId, shards };\n};\nexport const encodeRelayShard = (shardInfo) => {\n const { clusterId, shards } = shardInfo;\n const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;\n const buffer = new ArrayBuffer(totalLength);\n const view = new DataView(buffer);\n view.setUint16(0, clusterId);\n if (shards.length >= 64) {\n // rsv format (Bit Vector)\n for (const index of shards) {\n const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (index % 8);\n view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));\n }\n }\n else {\n // rs format (Index List)\n view.setUint8(2, shards.length);\n for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {\n view.setUint16(offset, shards[i]);\n }\n }\n return new Uint8Array(buffer);\n};\n//# sourceMappingURL=relay_shard_codec.js.map","import debug from \"debug\";\nconst APP_NAME = \"waku\";\nexport class Logger {\n _info;\n _warn;\n _error;\n static createDebugNamespace(level, prefix) {\n return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;\n }\n constructor(prefix) {\n this._info = debug(Logger.createDebugNamespace(\"info\", prefix));\n this._warn = debug(Logger.createDebugNamespace(\"warn\", prefix));\n this._error = debug(Logger.createDebugNamespace(\"error\", prefix));\n }\n get info() {\n return this._info;\n }\n get warn() {\n return this._warn;\n }\n get error() {\n return this._error;\n }\n log(level, ...args) {\n const logger = this[level];\n logger(...args);\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_message as proto } from \"@waku/proto\";\nimport { determinePubsubTopic, Logger } from \"@waku/utils\";\nconst log = new Logger(\"message:version-0\");\nconst OneMillion = BigInt(1_000_000);\nexport const Version = 0;\nexport { proto };\nexport class DecodedMessage {\n pubsubTopic;\n proto;\n constructor(pubsubTopic, proto) {\n this.pubsubTopic = pubsubTopic;\n this.proto = proto;\n }\n get ephemeral() {\n return Boolean(this.proto.ephemeral);\n }\n get payload() {\n return this.proto.payload;\n }\n get contentTopic() {\n return this.proto.contentTopic;\n }\n get _rawTimestamp() {\n return this.proto.timestamp;\n }\n get timestamp() {\n // In the case we receive a value that is bigger than JS's max number,\n // we catch the error and return undefined.\n try {\n if (this.proto.timestamp) {\n // nanoseconds 10^-9 to milliseconds 10^-3\n const timestamp = this.proto.timestamp / OneMillion;\n return new Date(Number(timestamp));\n }\n return;\n }\n catch (e) {\n return;\n }\n }\n get meta() {\n return this.proto.meta;\n }\n get version() {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n return this.proto.version ?? 0;\n }\n get rateLimitProof() {\n return this.proto.rateLimitProof;\n }\n}\nexport class Encoder {\n contentTopic;\n ephemeral;\n pubsubTopic;\n metaSetter;\n constructor(contentTopic, ephemeral = false, pubsubTopic, metaSetter) {\n this.contentTopic = contentTopic;\n this.ephemeral = ephemeral;\n this.pubsubTopic = pubsubTopic;\n this.metaSetter = metaSetter;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n async toWire(message) {\n return proto.WakuMessage.encode(await this.toProtoObj(message));\n }\n async toProtoObj(message) {\n const timestamp = message.timestamp ?? new Date();\n const protoMessage = {\n payload: message.payload,\n version: Version,\n contentTopic: this.contentTopic,\n timestamp: BigInt(timestamp.valueOf()) * OneMillion,\n meta: undefined,\n rateLimitProof: message.rateLimitProof,\n ephemeral: this.ephemeral\n };\n if (this.metaSetter) {\n const meta = this.metaSetter(protoMessage);\n return { ...protoMessage, meta };\n }\n return protoMessage;\n }\n}\n/**\n * Creates an encoder that encode messages without Waku level encryption or signature.\n *\n * An encoder is used to encode messages in the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format to be sent over the Waku network. The resulting encoder can then be\n * pass to { @link @waku/interfaces!ISender.send } to automatically encode outgoing\n * messages.\n */\nexport function createEncoder({ pubsubTopic, pubsubTopicShardInfo, contentTopic, ephemeral, metaSetter }) {\n return new Encoder(contentTopic, ephemeral, determinePubsubTopic(contentTopic, pubsubTopic ?? pubsubTopicShardInfo), metaSetter);\n}\nexport class Decoder {\n pubsubTopic;\n contentTopic;\n constructor(pubsubTopic, contentTopic) {\n this.pubsubTopic = pubsubTopic;\n this.contentTopic = contentTopic;\n if (!contentTopic || contentTopic === \"\") {\n throw new Error(\"Content topic must be specified\");\n }\n }\n fromWireToProtoObj(bytes) {\n const protoMessage = proto.WakuMessage.decode(bytes);\n return Promise.resolve({\n payload: protoMessage.payload,\n contentTopic: protoMessage.contentTopic,\n version: protoMessage.version ?? undefined,\n timestamp: protoMessage.timestamp ?? undefined,\n meta: protoMessage.meta ?? undefined,\n rateLimitProof: protoMessage.rateLimitProof ?? undefined,\n ephemeral: protoMessage.ephemeral ?? false\n });\n }\n async fromProtoObj(pubsubTopic, proto) {\n // https://rfc.vac.dev/spec/14/\n // > If omitted, the value SHOULD be interpreted as version 0.\n if (proto.version ?? 0 !== Version) {\n log.error(\"Failed to decode due to incorrect version, expected:\", Version, \", actual:\", proto.version);\n return Promise.resolve(undefined);\n }\n return new DecodedMessage(pubsubTopic, proto);\n }\n}\n/**\n * Creates a decoder that decode messages without Waku level encryption.\n *\n * A decoder is used to decode messages from the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)\n * format when received from the Waku network. The resulting decoder can then be\n * pass to { @link @waku/interfaces!IReceiver.subscribe } to automatically decode incoming\n * messages.\n *\n * @param contentTopic The resulting decoder will only decode messages with this content topic.\n */\nexport function createDecoder(contentTopic, pubsubTopicShardInfo) {\n return new Decoder(determinePubsubTopic(contentTopic, pubsubTopicShardInfo), contentTopic);\n}\n//# sourceMappingURL=version_0.js.map","/**\n * @packageDocumentation\n *\n * For when you need a one-liner to collect iterable values.\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n *\n * // This can also be an iterator, etc\n * const values = function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = all(values)\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(values())\n *\n * console.info(arr) // 0, 1, 2, 3, 4\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction all(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n const arr = [];\n for await (const entry of source) {\n arr.push(entry);\n }\n return arr;\n })();\n }\n const arr = [];\n for (const entry of source) {\n arr.push(entry);\n }\n return arr;\n}\nexport default all;\n//# sourceMappingURL=index.js.map","import { allocUnsafe } from '#alloc';\nimport { asUint8Array } from '#util/as-uint8array';\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nexport function concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = allocUnsafe(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return asUint8Array(output);\n}\n//# sourceMappingURL=concat.js.map","/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nexport function equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map","/**\n * @packageDocumentation\n *\n * A class that lets you do operations over a list of Uint8Arrays without\n * copying them.\n *\n * ```js\n * import { Uint8ArrayList } from 'uint8arraylist'\n *\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray()\n * // -> Uint8Array([0, 1, 2, 3, 4, 5])\n *\n * list.consume(3)\n * list.subarray()\n * // -> Uint8Array([3, 4, 5])\n *\n * // you can also iterate over the list\n * for (const buf of list) {\n * // ..do something with `buf`\n * }\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ## Converting Uint8ArrayLists to Uint8Arrays\n *\n * There are two ways to turn a `Uint8ArrayList` into a `Uint8Array` - `.slice` and `.subarray` and one way to turn a `Uint8ArrayList` into a `Uint8ArrayList` with different contents - `.sublist`.\n *\n * ### slice\n *\n * Slice follows the same semantics as [Uint8Array.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice) in that it creates a new `Uint8Array` and copies bytes into it using an optional offset & length.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.slice(0, 1)\n * // -> Uint8Array([0])\n * ```\n *\n * ### subarray\n *\n * Subarray attempts to follow the same semantics as [Uint8Array.subarray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray) with one important different - this is a no-copy operation, unless the requested bytes span two internal buffers in which case it is a copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.subarray(0, 1)\n * // -> Uint8Array([0]) - no-copy\n *\n * list.subarray(2, 5)\n * // -> Uint8Array([2, 3, 4]) - copy\n * ```\n *\n * ### sublist\n *\n * Sublist creates and returns a new `Uint8ArrayList` that shares the underlying buffers with the original so is always a no-copy operation.\n *\n * ```js\n * const list = new Uint8ArrayList()\n * list.append(Uint8Array.from([0, 1, 2]))\n * list.append(Uint8Array.from([3, 4, 5]))\n *\n * list.sublist(0, 1)\n * // -> Uint8ArrayList([0]) - no-copy\n *\n * list.sublist(2, 5)\n * // -> Uint8ArrayList([2], [3, 4]) - no-copy\n * ```\n *\n * ## Inspiration\n *\n * Borrows liberally from [bl](https://www.npmjs.com/package/bl) but only uses native JS types.\n */\nimport { allocUnsafe, alloc } from 'uint8arrays/alloc';\nimport { concat } from 'uint8arrays/concat';\nimport { equals } from 'uint8arrays/equals';\nconst symbol = Symbol.for('@achingbrain/uint8arraylist');\nfunction findBufAndOffset(bufs, index) {\n if (index == null || index < 0) {\n throw new RangeError('index is out of bounds');\n }\n let offset = 0;\n for (const buf of bufs) {\n const bufEnd = offset + buf.byteLength;\n if (index < bufEnd) {\n return {\n buf,\n index: index - offset\n };\n }\n offset = bufEnd;\n }\n throw new RangeError('index is out of bounds');\n}\n/**\n * Check if object is a CID instance\n *\n * @example\n *\n * ```js\n * import { isUint8ArrayList, Uint8ArrayList } from 'uint8arraylist'\n *\n * isUint8ArrayList(true) // false\n * isUint8ArrayList([]) // false\n * isUint8ArrayList(new Uint8ArrayList()) // true\n * ```\n */\nexport function isUint8ArrayList(value) {\n return Boolean(value?.[symbol]);\n}\nexport class Uint8ArrayList {\n bufs;\n length;\n [symbol] = true;\n constructor(...data) {\n this.bufs = [];\n this.length = 0;\n if (data.length > 0) {\n this.appendAll(data);\n }\n }\n *[Symbol.iterator]() {\n yield* this.bufs;\n }\n get byteLength() {\n return this.length;\n }\n /**\n * Add one or more `bufs` to the end of this Uint8ArrayList\n */\n append(...bufs) {\n this.appendAll(bufs);\n }\n /**\n * Add all `bufs` to the end of this Uint8ArrayList\n */\n appendAll(bufs) {\n let length = 0;\n for (const buf of bufs) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.push(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.push(...buf.bufs);\n }\n else {\n throw new Error('Could not append value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Add one or more `bufs` to the start of this Uint8ArrayList\n */\n prepend(...bufs) {\n this.prependAll(bufs);\n }\n /**\n * Add all `bufs` to the start of this Uint8ArrayList\n */\n prependAll(bufs) {\n let length = 0;\n for (const buf of bufs.reverse()) {\n if (buf instanceof Uint8Array) {\n length += buf.byteLength;\n this.bufs.unshift(buf);\n }\n else if (isUint8ArrayList(buf)) {\n length += buf.byteLength;\n this.bufs.unshift(...buf.bufs);\n }\n else {\n throw new Error('Could not prepend value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n this.length += length;\n }\n /**\n * Read the value at `index`\n */\n get(index) {\n const res = findBufAndOffset(this.bufs, index);\n return res.buf[res.index];\n }\n /**\n * Set the value at `index` to `value`\n */\n set(index, value) {\n const res = findBufAndOffset(this.bufs, index);\n res.buf[res.index] = value;\n }\n /**\n * Copy bytes from `buf` to the index specified by `offset`\n */\n write(buf, offset = 0) {\n if (buf instanceof Uint8Array) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf[i]);\n }\n }\n else if (isUint8ArrayList(buf)) {\n for (let i = 0; i < buf.length; i++) {\n this.set(offset + i, buf.get(i));\n }\n }\n else {\n throw new Error('Could not write value, must be an Uint8Array or a Uint8ArrayList');\n }\n }\n /**\n * Remove bytes from the front of the pool\n */\n consume(bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes);\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) {\n return;\n }\n // if consuming all bytes, skip iterating\n if (bytes === this.byteLength) {\n this.bufs = [];\n this.length = 0;\n return;\n }\n while (this.bufs.length > 0) {\n if (bytes >= this.bufs[0].byteLength) {\n bytes -= this.bufs[0].byteLength;\n this.length -= this.bufs[0].byteLength;\n this.bufs.shift();\n }\n else {\n this.bufs[0] = this.bufs[0].subarray(bytes);\n this.length -= bytes;\n break;\n }\n }\n }\n /**\n * Extracts a section of an array and returns a new array.\n *\n * This is a copy operation as it is with Uint8Arrays and Arrays\n * - note this is different to the behaviour of Node Buffers.\n */\n slice(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n return concat(bufs, length);\n }\n /**\n * Returns a alloc from the given start and end element index.\n *\n * In the best case where the data extracted comes from a single Uint8Array\n * internally this is a no-copy operation otherwise it is a copy operation.\n */\n subarray(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n if (bufs.length === 1) {\n return bufs[0];\n }\n return concat(bufs, length);\n }\n /**\n * Returns a allocList from the given start and end element index.\n *\n * This is a no-copy operation.\n */\n sublist(beginInclusive, endExclusive) {\n const { bufs, length } = this._subList(beginInclusive, endExclusive);\n const list = new Uint8ArrayList();\n list.length = length;\n // don't loop, just set the bufs\n list.bufs = [...bufs];\n return list;\n }\n _subList(beginInclusive, endExclusive) {\n beginInclusive = beginInclusive ?? 0;\n endExclusive = endExclusive ?? this.length;\n if (beginInclusive < 0) {\n beginInclusive = this.length + beginInclusive;\n }\n if (endExclusive < 0) {\n endExclusive = this.length + endExclusive;\n }\n if (beginInclusive < 0 || endExclusive > this.length) {\n throw new RangeError('index is out of bounds');\n }\n if (beginInclusive === endExclusive) {\n return { bufs: [], length: 0 };\n }\n if (beginInclusive === 0 && endExclusive === this.length) {\n return { bufs: this.bufs, length: this.length };\n }\n const bufs = [];\n let offset = 0;\n for (let i = 0; i < this.bufs.length; i++) {\n const buf = this.bufs[i];\n const bufStart = offset;\n const bufEnd = bufStart + buf.byteLength;\n // for next loop\n offset = bufEnd;\n if (beginInclusive >= bufEnd) {\n // start after this buf\n continue;\n }\n const sliceStartInBuf = beginInclusive >= bufStart && beginInclusive < bufEnd;\n const sliceEndsInBuf = endExclusive > bufStart && endExclusive <= bufEnd;\n if (sliceStartInBuf && sliceEndsInBuf) {\n // slice is wholly contained within this buffer\n if (beginInclusive === bufStart && endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n const start = beginInclusive - bufStart;\n bufs.push(buf.subarray(start, start + (endExclusive - beginInclusive)));\n break;\n }\n if (sliceStartInBuf) {\n // slice starts in this buffer\n if (beginInclusive === 0) {\n // requested whole buffer\n bufs.push(buf);\n continue;\n }\n // requested part of buffer\n bufs.push(buf.subarray(beginInclusive - bufStart));\n continue;\n }\n if (sliceEndsInBuf) {\n if (endExclusive === bufEnd) {\n // requested whole buffer\n bufs.push(buf);\n break;\n }\n // requested part of buffer\n bufs.push(buf.subarray(0, endExclusive - bufStart));\n break;\n }\n // slice started before this buffer and ends after it\n bufs.push(buf);\n }\n return { bufs, length: endExclusive - beginInclusive };\n }\n indexOf(search, offset = 0) {\n if (!isUint8ArrayList(search) && !(search instanceof Uint8Array)) {\n throw new TypeError('The \"value\" argument must be a Uint8ArrayList or Uint8Array');\n }\n const needle = search instanceof Uint8Array ? search : search.subarray();\n offset = Number(offset ?? 0);\n if (isNaN(offset)) {\n offset = 0;\n }\n if (offset < 0) {\n offset = this.length + offset;\n }\n if (offset < 0) {\n offset = 0;\n }\n if (search.length === 0) {\n return offset > this.length ? this.length : offset;\n }\n // https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\n const M = needle.byteLength;\n if (M === 0) {\n throw new TypeError('search must be at least 1 byte long');\n }\n // radix\n const radix = 256;\n const rightmostPositions = new Int32Array(radix);\n // position of the rightmost occurrence of the byte c in the pattern\n for (let c = 0; c < radix; c++) {\n // -1 for bytes not in pattern\n rightmostPositions[c] = -1;\n }\n for (let j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmostPositions[needle[j]] = j;\n }\n // Return offset of first match, -1 if no match\n const right = rightmostPositions;\n const lastIndex = this.byteLength - needle.byteLength;\n const lastPatIndex = needle.byteLength - 1;\n let skip;\n for (let i = offset; i <= lastIndex; i += skip) {\n skip = 0;\n for (let j = lastPatIndex; j >= 0; j--) {\n const char = this.get(i + j);\n if (needle[j] !== char) {\n skip = Math.max(1, j - right[char]);\n break;\n }\n }\n if (skip === 0) {\n return i;\n }\n }\n return -1;\n }\n getInt8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt8(0);\n }\n setInt8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt8(0, value);\n this.write(buf, byteOffset);\n }\n getInt16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt16(0, littleEndian);\n }\n setInt16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getInt32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getInt32(0, littleEndian);\n }\n setInt32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setInt32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigInt64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigInt64(0, littleEndian);\n }\n setBigInt64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigInt64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint8(byteOffset) {\n const buf = this.subarray(byteOffset, byteOffset + 1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint8(0);\n }\n setUint8(byteOffset, value) {\n const buf = allocUnsafe(1);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint8(0, value);\n this.write(buf, byteOffset);\n }\n getUint16(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint16(0, littleEndian);\n }\n setUint16(byteOffset, value, littleEndian) {\n const buf = alloc(2);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint16(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getUint32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getUint32(0, littleEndian);\n }\n setUint32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setUint32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getBigUint64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getBigUint64(0, littleEndian);\n }\n setBigUint64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setBigUint64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat32(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat32(0, littleEndian);\n }\n setFloat32(byteOffset, value, littleEndian) {\n const buf = alloc(4);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat32(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n getFloat64(byteOffset, littleEndian) {\n const buf = this.subarray(byteOffset, byteOffset + 8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n return view.getFloat64(0, littleEndian);\n }\n setFloat64(byteOffset, value, littleEndian) {\n const buf = alloc(8);\n const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n view.setFloat64(0, value, littleEndian);\n this.write(buf, byteOffset);\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (!(other instanceof Uint8ArrayList)) {\n return false;\n }\n if (other.bufs.length !== this.bufs.length) {\n return false;\n }\n for (let i = 0; i < this.bufs.length; i++) {\n if (!equals(this.bufs[i], other.bufs[i])) {\n return false;\n }\n }\n return true;\n }\n /**\n * Create a Uint8ArrayList from a pre-existing list of Uint8Arrays. Use this\n * method if you know the total size of all the Uint8Arrays ahead of time.\n */\n static fromUint8Arrays(bufs, length) {\n const list = new Uint8ArrayList();\n list.bufs = bufs;\n if (length == null) {\n length = bufs.reduce((acc, curr) => acc + curr.byteLength, 0);\n }\n list.length = length;\n return list;\n }\n}\n/*\nfunction indexOf (needle: Uint8Array, haystack: Uint8Array, offset = 0) {\n for (let i = offset; i < haystack.byteLength; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) {\n break\n }\n\n if (j === needle.byteLength -1) {\n return i\n }\n }\n\n if (haystack.byteLength - i < needle.byteLength) {\n break\n }\n }\n\n return -1\n}\n*/\n//# sourceMappingURL=index.js.map","export function isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\n//# sourceMappingURL=utils.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { isAsyncIterable } from './utils.js';\nconst defaultEncoder = (length) => {\n const lengthLength = varint.encodingLength(length);\n const lengthBuf = allocUnsafe(lengthLength);\n varint.encode(length, lengthBuf);\n defaultEncoder.bytes = lengthLength;\n return lengthBuf;\n};\ndefaultEncoder.bytes = 0;\nexport function encode(source, options) {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n function* maybeYield(chunk) {\n // length + data\n const length = encodeLength(chunk.byteLength);\n // yield only Uint8Arrays\n if (length instanceof Uint8Array) {\n yield length;\n }\n else {\n yield* length;\n }\n // yield only Uint8Arrays\n if (chunk instanceof Uint8Array) {\n yield chunk;\n }\n else {\n yield* chunk;\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n }\n return (function* () {\n for (const chunk of source) {\n yield* maybeYield(chunk);\n }\n })();\n}\nencode.single = (chunk, options) => {\n options = options ?? {};\n const encodeLength = options.lengthEncoder ?? defaultEncoder;\n return new Uint8ArrayList(encodeLength(chunk.byteLength), chunk);\n};\n//# sourceMappingURL=encode.js.map","/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map","/* eslint max-depth: [\"error\", 6] */\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError, UnexpectedEOFError } from './errors.js';\nimport { isAsyncIterable } from './utils.js';\n// Maximum length of the length section of the message\nexport const MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nexport const MAX_DATA_LENGTH = 1024 * 1024 * 4;\nvar ReadMode;\n(function (ReadMode) {\n ReadMode[ReadMode[\"LENGTH\"] = 0] = \"LENGTH\";\n ReadMode[ReadMode[\"DATA\"] = 1] = \"DATA\";\n})(ReadMode || (ReadMode = {}));\nconst defaultDecoder = (buf) => {\n const length = varint.decode(buf);\n defaultDecoder.bytes = varint.encodingLength(length);\n return length;\n};\ndefaultDecoder.bytes = 0;\nexport function decode(source, options) {\n const buffer = new Uint8ArrayList();\n let mode = ReadMode.LENGTH;\n let dataLength = -1;\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;\n function* maybeYield() {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer);\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n if (dataLength > maxDataLength) {\n throw new InvalidDataLengthError('Message length too long');\n }\n const dataLengthLength = lengthDecoder.bytes;\n buffer.consume(dataLengthLength);\n if (options?.onLength != null) {\n options.onLength(dataLength);\n }\n mode = ReadMode.DATA;\n }\n catch (err) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new InvalidDataLengthLengthError('Message length length too long');\n }\n break;\n }\n throw err;\n }\n }\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break;\n }\n const data = buffer.sublist(0, dataLength);\n buffer.consume(dataLength);\n if (options?.onData != null) {\n options.onData(data);\n }\n yield data;\n mode = ReadMode.LENGTH;\n }\n }\n }\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input');\n }\n })();\n }\n return (function* () {\n for (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new UnexpectedEOFError('Unexpected end of input');\n }\n })();\n}\ndecode.fromReader = (reader, options) => {\n let byteLength = 1; // Read single byte chunks until the length is known\n const varByteSource = (async function* () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength);\n if (done === true) {\n return;\n }\n if (value != null) {\n yield value;\n }\n }\n catch (err) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null };\n }\n throw err;\n }\n finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1;\n }\n }\n }());\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l) => { byteLength = l; };\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n });\n};\n//# sourceMappingURL=decode.js.map","export default function pDefer() {\n\tconst deferred = {};\n\n\tdeferred.promise = new Promise((resolve, reject) => {\n\t\tdeferred.resolve = resolve;\n\t\tdeferred.reject = reject;\n\t});\n\n\treturn deferred;\n}\n","// ported from https://www.npmjs.com/package/fast-fifo\nclass FixedFIFO {\n buffer;\n mask;\n top;\n btm;\n next;\n constructor(hwm) {\n if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) {\n throw new Error('Max size for a FixedFIFO should be a power of two');\n }\n this.buffer = new Array(hwm);\n this.mask = hwm - 1;\n this.top = 0;\n this.btm = 0;\n this.next = null;\n }\n push(data) {\n if (this.buffer[this.top] !== undefined) {\n return false;\n }\n this.buffer[this.top] = data;\n this.top = (this.top + 1) & this.mask;\n return true;\n }\n shift() {\n const last = this.buffer[this.btm];\n if (last === undefined) {\n return undefined;\n }\n this.buffer[this.btm] = undefined;\n this.btm = (this.btm + 1) & this.mask;\n return last;\n }\n isEmpty() {\n return this.buffer[this.btm] === undefined;\n }\n}\nexport class FIFO {\n size;\n hwm;\n head;\n tail;\n constructor(options = {}) {\n this.hwm = options.splitLimit ?? 16;\n this.head = new FixedFIFO(this.hwm);\n this.tail = this.head;\n this.size = 0;\n }\n calculateSize(obj) {\n if (obj?.byteLength != null) {\n return obj.byteLength;\n }\n return 1;\n }\n push(val) {\n if (val?.value != null) {\n this.size += this.calculateSize(val.value);\n }\n if (!this.head.push(val)) {\n const prev = this.head;\n this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length);\n this.head.push(val);\n }\n }\n shift() {\n let val = this.tail.shift();\n if (val === undefined && (this.tail.next != null)) {\n const next = this.tail.next;\n this.tail.next = null;\n this.tail = next;\n val = this.tail.shift();\n }\n if (val?.value != null) {\n this.size -= this.calculateSize(val.value);\n }\n return val;\n }\n isEmpty() {\n return this.head.isEmpty();\n }\n}\n//# sourceMappingURL=fifo.js.map","/**\n * @packageDocumentation\n *\n * An iterable that you can push values into.\n *\n * @example\n *\n * ```js\n * import { pushable } from 'it-pushable'\n *\n * const source = pushable()\n *\n * setTimeout(() => source.push('hello'), 100)\n * setTimeout(() => source.push('world'), 200)\n * setTimeout(() => source.end(), 300)\n *\n * const start = Date.now()\n *\n * for await (const value of source) {\n * console.log(`got \"${value}\" after ${Date.now() - start}ms`)\n * }\n * console.log(`done after ${Date.now() - start}ms`)\n *\n * // Output:\n * // got \"hello\" after 105ms\n * // got \"world\" after 207ms\n * // done after 309ms\n * ```\n *\n * @example\n *\n * ```js\n * import { pushableV } from 'it-pushable'\n * import all from 'it-all'\n *\n * const source = pushableV()\n *\n * source.push(1)\n * source.push(2)\n * source.push(3)\n * source.end()\n *\n * console.info(await all(source))\n *\n * // Output:\n * // [ [1, 2, 3] ]\n * ```\n */\nimport deferred from 'p-defer';\nimport { FIFO } from './fifo.js';\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.code = code ?? 'ABORT_ERR';\n }\n}\nexport function pushable(options = {}) {\n const getNext = (buffer) => {\n const next = buffer.shift();\n if (next == null) {\n return { done: true };\n }\n if (next.error != null) {\n throw next.error;\n }\n return {\n done: next.done === true,\n // @ts-expect-error if done is false, value will be present\n value: next.value\n };\n };\n return _pushable(getNext, options);\n}\nexport function pushableV(options = {}) {\n const getNext = (buffer) => {\n let next;\n const values = [];\n while (!buffer.isEmpty()) {\n next = buffer.shift();\n if (next == null) {\n break;\n }\n if (next.error != null) {\n throw next.error;\n }\n if (next.done === false) {\n // @ts-expect-error if done is false value should be pushed\n values.push(next.value);\n }\n }\n if (next == null) {\n return { done: true };\n }\n return {\n done: next.done === true,\n value: values\n };\n };\n return _pushable(getNext, options);\n}\nfunction _pushable(getNext, options) {\n options = options ?? {};\n let onEnd = options.onEnd;\n let buffer = new FIFO();\n let pushable;\n let onNext;\n let ended;\n let drain = deferred();\n const waitNext = async () => {\n try {\n if (!buffer.isEmpty()) {\n return getNext(buffer);\n }\n if (ended) {\n return { done: true };\n }\n return await new Promise((resolve, reject) => {\n onNext = (next) => {\n onNext = null;\n buffer.push(next);\n try {\n resolve(getNext(buffer));\n }\n catch (err) {\n reject(err);\n }\n return pushable;\n };\n });\n }\n finally {\n if (buffer.isEmpty()) {\n // settle promise in the microtask queue to give consumers a chance to\n // await after calling .push\n queueMicrotask(() => {\n drain.resolve();\n drain = deferred();\n });\n }\n }\n };\n const bufferNext = (next) => {\n if (onNext != null) {\n return onNext(next);\n }\n buffer.push(next);\n return pushable;\n };\n const bufferError = (err) => {\n buffer = new FIFO();\n if (onNext != null) {\n return onNext({ error: err });\n }\n buffer.push({ error: err });\n return pushable;\n };\n const push = (value) => {\n if (ended) {\n return pushable;\n }\n // @ts-expect-error `byteLength` is not declared on PushType\n if (options?.objectMode !== true && value?.byteLength == null) {\n throw new Error('objectMode was not true but tried to push non-Uint8Array value');\n }\n return bufferNext({ done: false, value });\n };\n const end = (err) => {\n if (ended)\n return pushable;\n ended = true;\n return (err != null) ? bufferError(err) : bufferNext({ done: true });\n };\n const _return = () => {\n buffer = new FIFO();\n end();\n return { done: true };\n };\n const _throw = (err) => {\n end(err);\n return { done: true };\n };\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next: waitNext,\n return: _return,\n throw: _throw,\n push,\n end,\n get readableLength() {\n return buffer.size;\n },\n onEmpty: async (options) => {\n const signal = options?.signal;\n signal?.throwIfAborted();\n if (buffer.isEmpty()) {\n return;\n }\n let cancel;\n let listener;\n if (signal != null) {\n cancel = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError());\n };\n signal.addEventListener('abort', listener);\n });\n }\n try {\n await Promise.race([\n drain.promise,\n cancel\n ]);\n }\n finally {\n if (listener != null && signal != null) {\n signal?.removeEventListener('abort', listener);\n }\n }\n }\n };\n if (onEnd == null) {\n return pushable;\n }\n const _pushable = pushable;\n pushable = {\n [Symbol.asyncIterator]() { return this; },\n next() {\n return _pushable.next();\n },\n throw(err) {\n _pushable.throw(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return { done: true };\n },\n return() {\n _pushable.return();\n if (onEnd != null) {\n onEnd();\n onEnd = undefined;\n }\n return { done: true };\n },\n push,\n end(err) {\n _pushable.end(err);\n if (onEnd != null) {\n onEnd(err);\n onEnd = undefined;\n }\n return pushable;\n },\n get readableLength() {\n return _pushable.readableLength;\n },\n onEmpty: (opts) => {\n return _pushable.onEmpty(opts);\n }\n };\n return pushable;\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Merge several (async)iterables into one, yield values as they arrive.\n *\n * Nb. sources are iterated over in parallel so the order of emitted items is not guaranteed.\n *\n * @example\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values1 = [0, 1, 2, 3, 4]\n * const values2 = [5, 6, 7, 8, 9]\n *\n * const arr = all(merge(values1, values2))\n *\n * console.info(arr) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import merge from 'it-merge'\n * import all from 'it-all'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const values1 = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n * const values2 = async function * () {\n * yield * [5, 6, 7, 8, 9]\n * }\n *\n * const arr = await all(merge(values1(), values2()))\n *\n * console.info(arr) // 0, 1, 5, 6, 2, 3, 4, 7, 8, 9 <- nb. order is not guaranteed\n * ```\n */\nimport { pushable } from 'it-pushable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction merge(...sources) {\n const syncSources = [];\n for (const source of sources) {\n if (!isAsyncIterable(source)) {\n syncSources.push(source);\n }\n }\n if (syncSources.length === sources.length) {\n // all sources are synchronous\n return (function* () {\n for (const source of syncSources) {\n yield* source;\n }\n })();\n }\n return (async function* () {\n const output = pushable({\n objectMode: true\n });\n void Promise.resolve().then(async () => {\n try {\n await Promise.all(sources.map(async (source) => {\n for await (const item of source) {\n output.push(item);\n }\n }));\n output.end();\n }\n catch (err) {\n output.end(err);\n }\n });\n yield* output;\n })();\n}\nexport default merge;\n//# sourceMappingURL=index.js.map","import { pushable } from 'it-pushable';\nimport merge from 'it-merge';\nexport function pipe(first, ...rest) {\n if (first == null) {\n throw new Error('Empty pipeline');\n }\n // Duplex at start: wrap in function and return duplex source\n if (isDuplex(first)) {\n const duplex = first;\n first = () => duplex.source;\n // Iterable at start: wrap in function\n }\n else if (isIterable(first) || isAsyncIterable(first)) {\n const source = first;\n first = () => source;\n }\n const fns = [first, ...rest];\n if (fns.length > 1) {\n // Duplex at end: use duplex sink\n if (isDuplex(fns[fns.length - 1])) {\n fns[fns.length - 1] = fns[fns.length - 1].sink;\n }\n }\n if (fns.length > 2) {\n // Duplex in the middle, consume source with duplex sink and return duplex source\n for (let i = 1; i < fns.length - 1; i++) {\n if (isDuplex(fns[i])) {\n fns[i] = duplexPipelineFn(fns[i]);\n }\n }\n }\n return rawPipe(...fns);\n}\nexport const rawPipe = (...fns) => {\n let res;\n while (fns.length > 0) {\n res = fns.shift()(res);\n }\n return res;\n};\nconst isAsyncIterable = (obj) => {\n return obj?.[Symbol.asyncIterator] != null;\n};\nconst isIterable = (obj) => {\n return obj?.[Symbol.iterator] != null;\n};\nconst isDuplex = (obj) => {\n if (obj == null) {\n return false;\n }\n return obj.sink != null && obj.source != null;\n};\nconst duplexPipelineFn = (duplex) => {\n return (source) => {\n const p = duplex.sink(source);\n if (p?.then != null) {\n const stream = pushable({\n objectMode: true\n });\n p.then(() => {\n stream.end();\n }, (err) => {\n stream.end(err);\n });\n let sourceWrap;\n const source = duplex.source;\n if (isAsyncIterable(source)) {\n sourceWrap = async function* () {\n yield* source;\n stream.end();\n };\n }\n else if (isIterable(source)) {\n sourceWrap = function* () {\n yield* source;\n stream.end();\n };\n }\n else {\n throw new Error('Unknown duplex source type - must be Iterable or AsyncIterable');\n }\n return merge(stream, sourceWrap());\n }\n return duplex.source;\n };\n};\n//# sourceMappingURL=index.js.map","export function selectOpenConnection(connections) {\n return connections\n .filter((c) => c.status === \"open\")\n .sort((left, right) => right.timeline.open - left.timeline.open)\n .at(0);\n}\n//# sourceMappingURL=utils.js.map","import { Logger } from \"@waku/utils\";\nimport { selectOpenConnection } from \"./utils.js\";\nconst STREAM_LOCK_KEY = \"consumed\";\nexport class StreamManager {\n multicodec;\n getConnections;\n addEventListener;\n log;\n ongoingCreation = new Set();\n streamPool = new Map();\n constructor(multicodec, getConnections, addEventListener) {\n this.multicodec = multicodec;\n this.getConnections = getConnections;\n this.addEventListener = addEventListener;\n this.log = new Logger(`stream-manager:${multicodec}`);\n this.addEventListener(\"peer:update\", this.handlePeerUpdateStreamPool);\n }\n async getStream(peer) {\n const peerId = peer.id.toString();\n const scheduledStream = this.streamPool.get(peerId);\n if (scheduledStream) {\n this.streamPool.delete(peerId);\n await scheduledStream;\n }\n let stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n stream = await this.createStream(peer);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n async createStream(peer, retries = 0) {\n const connections = this.getConnections(peer.id);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n }\n let lastError;\n let stream;\n for (let i = 0; i < retries + 1; i++) {\n try {\n this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n stream = await connection.newStream(this.multicodec);\n this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n break;\n }\n catch (error) {\n lastError = error;\n }\n }\n if (!stream) {\n throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +\n lastError);\n }\n return stream;\n }\n async createStreamWithLock(peer) {\n const peerId = peer.id.toString();\n if (this.ongoingCreation.has(peerId)) {\n this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);\n return;\n }\n try {\n this.ongoingCreation.add(peerId);\n await this.createStream(peer);\n }\n catch (error) {\n this.log.error(`Failed to createStreamWithLock:`, error);\n }\n finally {\n this.ongoingCreation.delete(peerId);\n }\n return;\n }\n handlePeerUpdateStreamPool = (evt) => {\n const { peer } = evt.detail;\n if (!peer.protocols.includes(this.multicodec)) {\n return;\n }\n const stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n return;\n }\n this.scheduleNewStream(peer);\n };\n scheduleNewStream(peer) {\n this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n // abandon previous attempt\n if (this.streamPool.has(peer.id.toString())) {\n this.streamPool.delete(peer.id.toString());\n }\n this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));\n }\n getOpenStreamForCodec(peerId) {\n const connections = this.getConnections(peerId);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n return;\n }\n const stream = connection.streams.find((s) => s.protocol === this.multicodec);\n if (!stream) {\n return;\n }\n const isStreamUnusable = [\"done\", \"closed\", \"closing\"].includes(stream.writeStatus || \"\");\n if (isStreamUnusable || this.isStreamLocked(stream)) {\n return;\n }\n return stream;\n }\n lockStream(peerId, stream) {\n this.log.info(`Locking stream for peerId:${peerId}\\tstreamId:${stream.id}`);\n stream.metadata[STREAM_LOCK_KEY] = true;\n }\n isStreamLocked(stream) {\n return !!stream.metadata[STREAM_LOCK_KEY];\n }\n}\n//# sourceMappingURL=stream_manager.js.map","import { StreamManager } from \"./stream_manager/index.js\";\n/**\n * A class with predefined helpers, to be used as a base to implement Waku\n * Protocols.\n */\nexport class BaseProtocol {\n multicodec;\n components;\n pubsubTopics;\n addLibp2pEventListener;\n removeLibp2pEventListener;\n streamManager;\n constructor(multicodec, components, pubsubTopics) {\n this.multicodec = multicodec;\n this.components = components;\n this.pubsubTopics = pubsubTopics;\n this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);\n this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);\n this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);\n }\n async getStream(peer) {\n return this.streamManager.getStream(peer);\n }\n}\n//# sourceMappingURL=base_protocol.js.map","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","import { proto_filter_v2 as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n/**\n * FilterPushRPC represents a message conforming to the Waku FilterPush protocol.\n * Protocol documentation: https://rfc.vac.dev/spec/12/\n */\nexport class FilterPushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.MessagePush.decode(bytes);\n return new FilterPushRpc(res);\n }\n encode() {\n return proto.MessagePush.encode(this.proto);\n }\n get wakuMessage() {\n return this.proto.wakuMessage;\n }\n /**\n * Get the pubsub topic from the FilterPushRpc object.\n * @returns string\n */\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n}\nexport class FilterSubscribeRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createSubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeRequest(pubsubTopic, contentTopics) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE,\n pubsubTopic,\n contentTopics\n });\n }\n static createUnsubscribeAllRequest(pubsubTopic) {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.UNSUBSCRIBE_ALL,\n pubsubTopic,\n contentTopics: []\n });\n }\n static createSubscriberPingRequest() {\n return new FilterSubscribeRpc({\n requestId: uuid(),\n filterSubscribeType: proto.FilterSubscribeRequest.FilterSubscribeType.SUBSCRIBER_PING,\n pubsubTopic: \"\",\n contentTopics: []\n });\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeRequest.decode(bytes);\n return new FilterSubscribeRpc(res);\n }\n encode() {\n return proto.FilterSubscribeRequest.encode(this.proto);\n }\n get filterSubscribeType() {\n return this.proto.filterSubscribeType;\n }\n get requestId() {\n return this.proto.requestId;\n }\n get pubsubTopic() {\n return this.proto.pubsubTopic;\n }\n get contentTopics() {\n return this.proto.contentTopics;\n }\n}\nexport class FilterSubscribeResponse {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.FilterSubscribeResponse.decode(bytes);\n return new FilterSubscribeResponse(res);\n }\n encode() {\n return proto.FilterSubscribeResponse.encode(this.proto);\n }\n get statusCode() {\n return this.proto.statusCode;\n }\n get statusDesc() {\n return this.proto.statusDesc;\n }\n get requestId() {\n return this.proto.requestId;\n }\n}\n//# sourceMappingURL=filter_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { FilterPushRpc, FilterSubscribeResponse, FilterSubscribeRpc } from \"./filter_rpc.js\";\nconst log = new Logger(\"filter:v2\");\nexport const FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\nexport class FilterCore extends BaseProtocol {\n handleIncomingMessage;\n pubsubTopics;\n constructor(handleIncomingMessage, pubsubTopics, libp2p) {\n super(FilterCodecs.SUBSCRIBE, libp2p.components, pubsubTopics);\n this.handleIncomingMessage = handleIncomingMessage;\n this.pubsubTopics = pubsubTopics;\n libp2p\n .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {\n maxInboundStreams: 100\n })\n .catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n }\n async subscribe(pubsubTopic, peer, contentTopics) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createSubscribeRequest(pubsubTopic, contentTopics);\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send subscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async unsubscribe(pubsubTopic, peer, contentTopics) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n const unsubscribeRequest = FilterSubscribeRpc.createUnsubscribeRequest(pubsubTopic, contentTopics);\n try {\n await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);\n }\n catch (error) {\n log.error(\"Failed to send unsubscribe request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n async unsubscribeAll(pubsubTopic, peer) {\n const stream = await this.getStream(peer);\n const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);\n const res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n if (!res || !res.length) {\n return {\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n },\n success: null\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n },\n success: null\n };\n }\n return {\n failure: null,\n success: peer.id\n };\n }\n async ping(peer) {\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(`Failed to get a stream for remote peer${peer.id.toString()}`, error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n const request = FilterSubscribeRpc.createSubscriberPingRequest();\n let res;\n try {\n res = await pipe([request.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (error) {\n log.error(\"Failed to send ping request\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n if (!res || !res.length) {\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n }\n };\n }\n const { statusCode, requestId, statusDesc } = FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n log.error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return {\n success: peer.id,\n failure: null\n };\n }\n onRequest(streamData) {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n pipe(stream, lp.decode, async (source) => {\n for await (const bytes of source) {\n const response = FilterPushRpc.decode(bytes.slice());\n const { pubsubTopic, wakuMessage } = response;\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n await this.handleIncomingMessage(pubsubTopic, wakuMessage, connection.remotePeer.toString());\n }\n }).then(() => {\n log.info(\"Receiving pipe closed.\");\n }, async (e) => {\n log.error(`Error with receiving pipe on peer:${connection.remotePeer.toString()} -- stream:${stream.id} -- protocol:${stream.protocol}: `, e);\n });\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { proto_lightpush as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\nexport class PushRpc {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(message, pubsubTopic) {\n return new PushRpc({\n requestId: uuid(),\n request: {\n message: message,\n pubsubTopic: pubsubTopic\n },\n response: undefined\n });\n }\n static decode(bytes) {\n const res = proto.PushRpc.decode(bytes);\n return new PushRpc(res);\n }\n encode() {\n return proto.PushRpc.encode(this.proto);\n }\n get query() {\n return this.proto.request;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=push_rpc.js.map","import { ProtocolError } from \"@waku/interfaces\";\n// should match nwaku\n// https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/rln_relay.nim#L309\n// https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/tests/waku_rln_relay/rln/waku_rln_relay_utils.nim#L20\nconst RLN_GENERATION_PREFIX_ERROR = \"could not generate rln-v2 proof\";\nexport const isRLNResponseError = (info) => {\n if (!info) {\n return false;\n }\n return info.includes(RLN_GENERATION_PREFIX_ERROR);\n};\nexport const matchRLNErrorMessage = (info) => {\n const rlnErrorMap = {\n [ProtocolError.RLN_IDENTITY_MISSING]: ProtocolError.RLN_IDENTITY_MISSING,\n [ProtocolError.RLN_MEMBERSHIP_INDEX]: ProtocolError.RLN_MEMBERSHIP_INDEX,\n [ProtocolError.RLN_LIMIT_MISSING]: ProtocolError.RLN_LIMIT_MISSING\n };\n const infoLowerCase = info.toLowerCase();\n for (const errorKey in rlnErrorMap) {\n if (infoLowerCase.includes(errorKey.toLowerCase())) {\n return rlnErrorMap[errorKey];\n }\n }\n return ProtocolError.RLN_PROOF_GENERATION;\n};\n//# sourceMappingURL=utils.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { PushResponse } from \"@waku/proto\";\nimport { isMessageSizeUnderCap } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { PushRpc } from \"./push_rpc.js\";\nimport { isRLNResponseError, matchRLNErrorMessage } from \"./utils.js\";\nconst log = new Logger(\"light-push\");\nexport const LightPushCodec = \"/vac/waku/lightpush/2.0.0-beta1\";\nexport { PushResponse };\n/**\n * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).\n */\nexport class LightPushCore extends BaseProtocol {\n pubsubTopics;\n constructor(pubsubTopics, libp2p) {\n super(LightPushCodec, libp2p.components, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n }\n async preparePushMessage(encoder, message) {\n try {\n if (!message.payload || message.payload.length === 0) {\n log.error(\"Failed to send waku light push: payload is empty\");\n return { query: null, error: ProtocolError.EMPTY_PAYLOAD };\n }\n if (!(await isMessageSizeUnderCap(encoder, message))) {\n log.error(\"Failed to send waku light push: message is bigger than 1MB\");\n return { query: null, error: ProtocolError.SIZE_TOO_BIG };\n }\n const protoMessage = await encoder.toProtoObj(message);\n if (!protoMessage) {\n log.error(\"Failed to encode to protoMessage, aborting push\");\n return {\n query: null,\n error: ProtocolError.ENCODE_FAILED\n };\n }\n const query = PushRpc.createRequest(protoMessage, encoder.pubsubTopic);\n return { query, error: null };\n }\n catch (error) {\n log.error(\"Failed to prepare push message\", error);\n return {\n query: null,\n error: ProtocolError.GENERIC_FAIL\n };\n }\n }\n // TODO(weboko): use peer.id as parameter instead\n async send(encoder, message, peer) {\n const { query, error: preparationError } = await this.preparePushMessage(encoder, message);\n if (preparationError || !query) {\n return {\n success: null,\n failure: {\n error: preparationError,\n peerId: peer.id\n }\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_STREAM_AVAILABLE,\n peerId: peer.id\n }\n };\n }\n let res;\n try {\n res = await pipe([query.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n }\n catch (err) {\n log.error(\"Failed to send waku light push request\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.GENERIC_FAIL,\n peerId: peer.id\n }\n };\n }\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n let response;\n try {\n response = PushRpc.decode(bytes).response;\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n success: null,\n failure: {\n error: ProtocolError.DECODE_FAILED,\n peerId: peer.id\n }\n };\n }\n if (!response) {\n log.error(\"Remote peer fault: No response in PushRPC\");\n return {\n success: null,\n failure: {\n error: ProtocolError.NO_RESPONSE,\n peerId: peer.id\n }\n };\n }\n if (isRLNResponseError(response.info)) {\n const rlnErrorCase = matchRLNErrorMessage(response.info);\n log.error(\"Remote peer rejected the message: \", rlnErrorCase);\n return {\n success: null,\n failure: {\n error: rlnErrorCase,\n peerId: peer.id\n }\n };\n }\n if (!response.isSuccess) {\n log.error(\"Remote peer rejected the message: \", response.info);\n return {\n success: null,\n failure: {\n error: ProtocolError.REMOTE_PEER_REJECTED,\n peerId: peer.id\n }\n };\n }\n return { success: peer.id, failure: null };\n }\n}\n//# sourceMappingURL=index.js.map","const MB = 1024 ** 2;\nconst SIZE_CAP_IN_MB = 1;\n/**\n * Return whether the size of the message is under the upper limit for the network.\n * This performs a protobuf encoding! If you have access to the fully encoded message,\n * use {@link isSizeUnderCapBuf} instead.\n * @param message\n * @param encoder\n */\nexport async function isMessageSizeUnderCap(encoder, message) {\n const buf = await encoder.toWire(message);\n if (!buf)\n return false;\n return isWireSizeUnderCap(buf);\n}\nexport const isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;\n//# sourceMappingURL=is_size_valid.js.map","const EmptyMessage = {\n payload: new Uint8Array(),\n contentTopic: \"\",\n version: undefined,\n timestamp: undefined,\n meta: undefined,\n rateLimitProof: undefined,\n ephemeral: undefined\n};\nexport function toProtoMessage(wire) {\n return { ...EmptyMessage, ...wire };\n}\n//# sourceMappingURL=to_proto_message.js.map","import { proto_store as proto } from \"@waku/proto\";\nimport { v4 as uuid } from \"uuid\";\n// https://github.com/waku-org/nwaku/blob/7205f95cff9f49ca0bb762e8fd0bf56a6a7f3b3b/waku/waku_store/common.nim#L12\nexport const DEFAULT_PAGE_SIZE = 20;\nexport const MAX_PAGE_SIZE = 100;\nconst ONE_MILLION = 1_000000;\nexport class StoreQueryRequest {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static create(params) {\n const request = new StoreQueryRequest({\n ...params,\n requestId: uuid(),\n timeStart: params.timeStart\n ? BigInt(params.timeStart.getTime() * ONE_MILLION)\n : undefined,\n timeEnd: params.timeEnd\n ? BigInt(params.timeEnd.getTime() * ONE_MILLION)\n : undefined,\n messageHashes: params.messageHashes || [],\n paginationLimit: params.paginationLimit\n ? BigInt(params.paginationLimit)\n : undefined\n });\n // Validate request parameters based on RFC\n if ((params.pubsubTopic && !params.contentTopics) ||\n (!params.pubsubTopic && params.contentTopics)) {\n throw new Error(\"Both pubsubTopic and contentTopics must be set or unset\");\n }\n if (params.messageHashes &&\n (params.pubsubTopic ||\n params.contentTopics ||\n params.timeStart ||\n params.timeEnd)) {\n throw new Error(\"Message hash lookup queries cannot include content filter criteria\");\n }\n return request;\n }\n static decode(bytes) {\n const res = proto.StoreQueryRequest.decode(bytes);\n return new StoreQueryRequest(res);\n }\n encode() {\n return proto.StoreQueryRequest.encode(this.proto);\n }\n}\nexport class StoreQueryResponse {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static decode(bytes) {\n const res = proto.StoreQueryResponse.decode(bytes);\n return new StoreQueryResponse(res);\n }\n encode() {\n return proto.StoreQueryResponse.encode(this.proto);\n }\n get statusCode() {\n return this.proto.statusCode;\n }\n get statusDesc() {\n return this.proto.statusDesc;\n }\n get messages() {\n return this.proto.messages;\n }\n get paginationCursor() {\n return this.proto.paginationCursor;\n }\n}\n//# sourceMappingURL=rpc.js.map","import { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nimport { toProtoMessage } from \"../to_proto_message.js\";\nimport { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, StoreQueryRequest, StoreQueryResponse } from \"./rpc.js\";\nconst log = new Logger(\"store\");\nexport const StoreCodec = \"/vac/waku/store-query/3.0.0\";\nexport class StoreCore extends BaseProtocol {\n pubsubTopics;\n constructor(pubsubTopics, libp2p) {\n super(StoreCodec, libp2p.components, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n }\n async *queryPerPage(queryOpts, decoders, peer) {\n if (queryOpts.contentTopics.toString() !==\n Array.from(decoders.keys()).toString()) {\n throw new Error(\"Internal error, the decoders should match the query's content topics\");\n }\n let currentCursor = queryOpts.paginationCursor;\n while (true) {\n const storeQueryRequest = StoreQueryRequest.create({\n ...queryOpts,\n paginationCursor: currentCursor\n });\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (e) {\n log.error(\"Failed to get stream\", e);\n break;\n }\n const res = await pipe([storeQueryRequest.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const storeQueryResponse = StoreQueryResponse.decode(bytes);\n if (!storeQueryResponse.statusCode ||\n storeQueryResponse.statusCode >= 300) {\n const errorMessage = `Store query failed with status code: ${storeQueryResponse.statusCode}, description: ${storeQueryResponse.statusDesc}`;\n log.error(errorMessage);\n throw new Error(errorMessage);\n }\n if (!storeQueryResponse.messages || !storeQueryResponse.messages.length) {\n log.warn(\"Stopping pagination due to empty messages in response\");\n break;\n }\n log.info(`${storeQueryResponse.messages.length} messages retrieved from store`);\n const decodedMessages = storeQueryResponse.messages.map((protoMsg) => {\n if (!protoMsg.message) {\n return Promise.resolve(undefined);\n }\n const contentTopic = protoMsg.message.contentTopic;\n if (contentTopic) {\n const decoder = decoders.get(contentTopic);\n if (decoder) {\n return decoder.fromProtoObj(protoMsg.pubsubTopic || \"\", toProtoMessage(protoMsg.message));\n }\n }\n return Promise.resolve(undefined);\n });\n yield decodedMessages;\n if (queryOpts.paginationForward) {\n currentCursor =\n storeQueryResponse.messages[storeQueryResponse.messages.length - 1]\n .messageHash;\n }\n else {\n currentCursor = storeQueryResponse.messages[0].messageHash;\n }\n if (storeQueryResponse.messages.length > MAX_PAGE_SIZE &&\n storeQueryResponse.messages.length <\n (queryOpts.paginationLimit || DEFAULT_PAGE_SIZE)) {\n break;\n }\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { setMaxListeners } from './events.js';\n/**\n * An implementation of a typed event target\n * etc\n */\nexport class TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n setMaxListeners(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\n//# sourceMappingURL=event-target.js.map","import { Logger, pubsubTopicToSingleShardInfo } from \"@waku/utils\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport { createEncoder } from \"../message/version_0.js\";\nconst RelayPingContentTopic = \"/relay-ping/1/ping/null\";\nconst log = new Logger(\"keep-alive\");\nexport class KeepAliveManager {\n relay;\n libp2p;\n options;\n pingKeepAliveTimers = new Map();\n relayKeepAliveTimers = new Map();\n constructor({ options, relay, libp2p }) {\n this.options = options;\n this.relay = relay;\n this.libp2p = libp2p;\n }\n start(peerId) {\n // Just in case a timer already exists for this peer\n this.stop(peerId);\n const { pingKeepAlive: pingPeriodSecs, relayKeepAlive: relayPeriodSecs } = this.options;\n const peerIdStr = peerId.toString();\n // Ping the peer every pingPeriodSecs seconds\n // if pingPeriodSecs is 0, don't ping the peer\n if (pingPeriodSecs !== 0) {\n const interval = setInterval(() => {\n void (async () => {\n let ping;\n try {\n // ping the peer for keep alive\n // also update the peer store with the latency\n try {\n ping = await this.libp2p.services.ping.ping(peerId);\n log.info(`Ping succeeded (${peerIdStr})`, ping);\n }\n catch (error) {\n log.error(`Ping failed for peer (${peerIdStr}).\n Next ping will be attempted in ${pingPeriodSecs} seconds.\n `);\n return;\n }\n try {\n await this.libp2p.peerStore.merge(peerId, {\n metadata: {\n ping: utf8ToBytes(ping.toString())\n }\n });\n }\n catch (e) {\n log.error(\"Failed to update ping\", e);\n }\n }\n catch (e) {\n log.error(`Ping failed (${peerIdStr})`, e);\n }\n })();\n }, pingPeriodSecs * 1000);\n this.pingKeepAliveTimers.set(peerIdStr, interval);\n }\n const relay = this.relay;\n if (relay && relayPeriodSecs !== 0) {\n const intervals = this.scheduleRelayPings(relay, relayPeriodSecs, peerId.toString());\n this.relayKeepAliveTimers.set(peerId, intervals);\n }\n }\n stop(peerId) {\n const peerIdStr = peerId.toString();\n if (this.pingKeepAliveTimers.has(peerIdStr)) {\n clearInterval(this.pingKeepAliveTimers.get(peerIdStr));\n this.pingKeepAliveTimers.delete(peerIdStr);\n }\n if (this.relayKeepAliveTimers.has(peerId)) {\n this.relayKeepAliveTimers.get(peerId)?.map(clearInterval);\n this.relayKeepAliveTimers.delete(peerId);\n }\n }\n stopAll() {\n for (const timer of [\n ...Object.values(this.pingKeepAliveTimers),\n ...Object.values(this.relayKeepAliveTimers)\n ]) {\n clearInterval(timer);\n }\n this.pingKeepAliveTimers.clear();\n this.relayKeepAliveTimers.clear();\n }\n connectionsExist() {\n return (this.pingKeepAliveTimers.size > 0 || this.relayKeepAliveTimers.size > 0);\n }\n scheduleRelayPings(relay, relayPeriodSecs, peerIdStr) {\n // send a ping message to each PubsubTopic the peer is part of\n const intervals = [];\n for (const topic of relay.pubsubTopics) {\n const meshPeers = relay.getMeshPeers(topic);\n if (!meshPeers.includes(peerIdStr))\n continue;\n const encoder = createEncoder({\n pubsubTopicShardInfo: pubsubTopicToSingleShardInfo(topic),\n contentTopic: RelayPingContentTopic,\n ephemeral: true\n });\n const interval = setInterval(() => {\n log.info(\"Sending Waku Relay ping message\");\n relay\n .send(encoder, { payload: new Uint8Array([1]) })\n .catch((e) => log.error(\"Failed to send relay ping\", e));\n }, relayPeriodSecs * 1000);\n intervals.push(interval);\n }\n return intervals;\n }\n}\n//# sourceMappingURL=keep_alive_manager.js.map","import { bytesToUtf8 } from \"@waku/utils/bytes\";\n/**\n * Reads peer's metadata and retrieves ping value.\n * @param peer Peer or null\n * @returns -1 if no ping attached, otherwise returns ping value\n */\nexport const getPeerPing = (peer) => {\n if (!peer) {\n return -1;\n }\n try {\n const bytes = peer.metadata.get(\"ping\");\n if (!bytes) {\n return -1;\n }\n return Number(bytesToUtf8(bytes));\n }\n catch (e) {\n return -1;\n }\n};\n//# sourceMappingURL=utils.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { DNS_DISCOVERY_TAG, EConnectionStateEvents, EPeersByDiscoveryEvents } from \"@waku/interfaces\";\nimport { Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, shardInfoToPubsubTopics } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport { KeepAliveManager } from \"./keep_alive_manager.js\";\nimport { getPeerPing } from \"./utils.js\";\nconst log = new Logger(\"connection-manager\");\nconst DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED = 1;\nconst DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER = 3;\nconst DEFAULT_MAX_PARALLEL_DIALS = 3;\nconst DEFAULT_PING_KEEP_ALIVE_SEC = 5 * 60;\nconst DEFAULT_RELAY_KEEP_ALIVE_SEC = 5 * 60;\nexport class ConnectionManager extends TypedEventEmitter {\n // TODO(weboko): make it private\n pubsubTopics;\n keepAliveManager;\n options;\n libp2p;\n dialAttemptsForPeer = new Map();\n dialErrorsForPeer = new Map();\n currentActiveParallelDialCount = 0;\n pendingPeerDialQueue = [];\n isP2PNetworkConnected = false;\n isConnected() {\n if (globalThis?.navigator && !globalThis?.navigator?.onLine) {\n return false;\n }\n return this.isP2PNetworkConnected;\n }\n stop() {\n this.keepAliveManager.stopAll();\n this.libp2p.removeEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n this.libp2p.removeEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n this.libp2p.removeEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n this.stopNetworkStatusListener();\n }\n async dropConnection(peerId) {\n try {\n this.keepAliveManager.stop(peerId);\n await this.libp2p.hangUp(peerId);\n log.info(`Dropped connection with peer ${peerId.toString()}`);\n }\n catch (error) {\n log.error(`Error dropping connection with peer ${peerId.toString()} - ${error}`);\n }\n }\n async getPeersByDiscovery() {\n const peersDiscovered = await this.libp2p.peerStore.all();\n const peersConnected = this.libp2p\n .getConnections()\n .map((conn) => conn.remotePeer);\n const peersDiscoveredByBootstrap = [];\n const peersDiscoveredByPeerExchange = [];\n const peersDiscoveredByLocal = [];\n const peersConnectedByBootstrap = [];\n const peersConnectedByPeerExchange = [];\n const peersConnectedByLocal = [];\n for (const peer of peersDiscovered) {\n const tags = await this.getTagNamesForPeer(peer.id);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersDiscoveredByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersDiscoveredByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersDiscoveredByLocal.push(peer);\n }\n }\n for (const peerId of peersConnected) {\n const peer = await this.libp2p.peerStore.get(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n if (tags.includes(Tags.BOOTSTRAP)) {\n peersConnectedByBootstrap.push(peer);\n }\n else if (tags.includes(Tags.PEER_EXCHANGE)) {\n peersConnectedByPeerExchange.push(peer);\n }\n else if (tags.includes(Tags.LOCAL)) {\n peersConnectedByLocal.push(peer);\n }\n }\n return {\n DISCOVERED: {\n [Tags.BOOTSTRAP]: peersDiscoveredByBootstrap,\n [Tags.PEER_EXCHANGE]: peersDiscoveredByPeerExchange,\n [Tags.LOCAL]: peersDiscoveredByLocal\n },\n CONNECTED: {\n [Tags.BOOTSTRAP]: peersConnectedByBootstrap,\n [Tags.PEER_EXCHANGE]: peersConnectedByPeerExchange,\n [Tags.LOCAL]: peersConnectedByLocal\n }\n };\n }\n constructor(options) {\n super();\n this.libp2p = options.libp2p;\n this.pubsubTopics = options.pubsubTopics;\n this.options = {\n maxDialAttemptsForPeer: DEFAULT_MAX_DIAL_ATTEMPTS_FOR_PEER,\n maxBootstrapPeersAllowed: DEFAULT_MAX_BOOTSTRAP_PEERS_ALLOWED,\n maxParallelDials: DEFAULT_MAX_PARALLEL_DIALS,\n pingKeepAlive: DEFAULT_PING_KEEP_ALIVE_SEC,\n relayKeepAlive: DEFAULT_RELAY_KEEP_ALIVE_SEC,\n ...options.config\n };\n this.keepAliveManager = new KeepAliveManager({\n relay: options.relay,\n libp2p: options.libp2p,\n options: {\n pingKeepAlive: this.options.pingKeepAlive,\n relayKeepAlive: this.options.relayKeepAlive\n }\n });\n this.startEventListeners()\n .then(() => log.info(`Connection Manager is now running`))\n .catch((error) => log.error(`Unexpected error while running service`, error));\n // libp2p emits `peer:discovery` events during its initialization\n // which means that before the ConnectionManager is initialized, some peers may have been discovered\n // we will dial the peers in peerStore ONCE before we start to listen to the `peer:discovery` events within the ConnectionManager\n this.dialPeerStorePeers().catch((error) => log.error(`Unexpected error while dialing peer store peers`, error));\n }\n async getConnectedPeers(codec) {\n const peerIDs = this.libp2p.getPeers();\n if (peerIDs.length === 0) {\n return [];\n }\n const peers = await Promise.all(peerIDs.map(async (id) => {\n try {\n return await this.libp2p.peerStore.get(id);\n }\n catch (e) {\n return null;\n }\n }));\n return peers\n .filter((p) => !!p)\n .filter((p) => (codec ? p.protocols.includes(codec) : true))\n .sort((left, right) => getPeerPing(left) - getPeerPing(right));\n }\n async dialPeerStorePeers() {\n const peerInfos = await this.libp2p.peerStore.all();\n const dialPromises = [];\n for (const peerInfo of peerInfos) {\n if (this.libp2p.getConnections().find((c) => c.remotePeer === peerInfo.id))\n continue;\n dialPromises.push(this.attemptDial(peerInfo.id));\n }\n try {\n await Promise.all(dialPromises);\n }\n catch (error) {\n log.error(`Unexpected error while dialing peer store peers`, error);\n }\n }\n async startEventListeners() {\n this.startPeerDiscoveryListener();\n this.startPeerConnectionListener();\n this.startPeerDisconnectionListener();\n this.startNetworkStatusListener();\n }\n async dialPeer(peerId) {\n this.currentActiveParallelDialCount += 1;\n let dialAttempt = 0;\n while (dialAttempt < this.options.maxDialAttemptsForPeer) {\n try {\n log.info(`Dialing peer ${peerId.toString()} on attempt ${dialAttempt + 1}`);\n await this.libp2p.dial(peerId);\n const tags = await this.getTagNamesForPeer(peerId);\n // add tag to connection describing discovery mechanism\n // don't add duplicate tags\n this.libp2p.getConnections(peerId).forEach((conn) => {\n conn.tags = Array.from(new Set([...conn.tags, ...tags]));\n });\n // instead of deleting the peer from the peer store, we set the dial attempt to -1\n // this helps us keep track of peers that have been dialed before\n this.dialAttemptsForPeer.set(peerId.toString(), -1);\n // Dialing succeeded, break the loop\n this.keepAliveManager.start(peerId);\n break;\n }\n catch (error) {\n if (error instanceof AggregateError) {\n // Handle AggregateError\n log.error(`Error dialing peer ${peerId.toString()} - ${error.errors}`);\n }\n else {\n // Handle generic error\n log.error(`Error dialing peer ${peerId.toString()} - ${error.message}`);\n }\n this.dialErrorsForPeer.set(peerId.toString(), error);\n dialAttempt++;\n this.dialAttemptsForPeer.set(peerId.toString(), dialAttempt);\n }\n }\n // Always decrease the active dial count and process the dial queue\n this.currentActiveParallelDialCount--;\n this.processDialQueue();\n // If max dial attempts reached and dialing failed, delete the peer\n if (dialAttempt === this.options.maxDialAttemptsForPeer) {\n try {\n const error = this.dialErrorsForPeer.get(peerId.toString());\n if (error) {\n let errorMessage;\n if (error instanceof AggregateError) {\n if (!error.errors) {\n log.warn(`No errors array found for AggregateError`);\n }\n else if (error.errors.length === 0) {\n log.warn(`Errors array is empty for AggregateError`);\n }\n else {\n errorMessage = JSON.stringify(error.errors[0]);\n }\n }\n else {\n errorMessage = error.message;\n }\n log.info(`Deleting undialable peer ${peerId.toString()} from peer store. Reason: ${errorMessage}`);\n }\n this.dialErrorsForPeer.delete(peerId.toString());\n await this.libp2p.peerStore.delete(peerId);\n // if it was last available peer - attempt DNS discovery\n await this.attemptDnsDiscovery();\n }\n catch (error) {\n throw new Error(`Error deleting undialable peer ${peerId.toString()} from peer store - ${error}`);\n }\n }\n }\n async attemptDnsDiscovery() {\n if (this.libp2p.getConnections().length > 0)\n return;\n if ((await this.libp2p.peerStore.all()).length > 0)\n return;\n log.info(\"Attempting to trigger DNS discovery.\");\n const dnsDiscovery = Object.values(this.libp2p.components.components).find((v) => {\n if (v && v.toString) {\n return v.toString().includes(DNS_DISCOVERY_TAG);\n }\n return false;\n });\n if (!dnsDiscovery)\n return;\n await dnsDiscovery.findPeers();\n }\n processDialQueue() {\n if (this.pendingPeerDialQueue.length > 0 &&\n this.currentActiveParallelDialCount < this.options.maxParallelDials) {\n const peerId = this.pendingPeerDialQueue.shift();\n if (!peerId)\n return;\n this.attemptDial(peerId).catch((error) => {\n log.error(error);\n });\n }\n }\n startPeerDiscoveryListener() {\n this.libp2p.addEventListener(\"peer:discovery\", this.onEventHandlers[\"peer:discovery\"]);\n }\n startPeerConnectionListener() {\n this.libp2p.addEventListener(\"peer:connect\", this.onEventHandlers[\"peer:connect\"]);\n }\n startPeerDisconnectionListener() {\n // TODO: ensure that these following issues are updated and confirmed\n /**\n * NOTE: Event is not being emitted on closing nor losing a connection.\n * @see https://github.com/libp2p/js-libp2p/issues/939\n * @see https://github.com/status-im/js-waku/issues/252\n *\n * >This event will be triggered anytime we are disconnected from another peer,\n * >regardless of the circumstances of that disconnection.\n * >If we happen to have multiple connections to a peer,\n * >this event will **only** be triggered when the last connection is closed.\n * @see https://github.com/libp2p/js-libp2p/blob/bad9e8c0ff58d60a78314077720c82ae331cc55b/doc/API.md?plain=1#L2100\n */\n this.libp2p.addEventListener(\"peer:disconnect\", this.onEventHandlers[\"peer:disconnect\"]);\n }\n async attemptDial(peerId) {\n if (!(await this.shouldDialPeer(peerId)))\n return;\n if (this.currentActiveParallelDialCount >= this.options.maxParallelDials) {\n this.pendingPeerDialQueue.push(peerId);\n return;\n }\n await this.dialPeer(peerId);\n }\n onEventHandlers = {\n \"peer:discovery\": (evt) => {\n void (async () => {\n const { id: peerId } = evt.detail;\n await this.dispatchDiscoveryEvent(peerId);\n try {\n await this.attemptDial(peerId);\n }\n catch (error) {\n log.error(`Error dialing peer ${peerId.toString()} : ${error}`);\n }\n })();\n },\n \"peer:connect\": (evt) => {\n void (async () => {\n log.info(`Connected to peer ${evt.detail.toString()}`);\n const peerId = evt.detail;\n this.keepAliveManager.start(peerId);\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n if (isBootstrap) {\n const bootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => conn.tags.includes(Tags.BOOTSTRAP));\n // If we have too many bootstrap connections, drop one\n if (bootstrapConnections.length > this.options.maxBootstrapPeersAllowed) {\n await this.dropConnection(peerId);\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_BOOTSTRAP, {\n detail: peerId\n }));\n }\n }\n else {\n this.dispatchEvent(new CustomEvent(EPeersByDiscoveryEvents.PEER_CONNECT_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n this.setP2PNetworkConnected();\n })();\n },\n \"peer:disconnect\": (evt) => {\n void (async () => {\n this.keepAliveManager.stop(evt.detail);\n this.setP2PNetworkDisconnected();\n })();\n },\n \"browser:network\": () => {\n this.dispatchWakuConnectionEvent();\n }\n };\n /**\n * Checks if the peer should be dialed based on the following conditions:\n * 1. If the peer is already connected, don't dial\n * 2. If the peer is not part of any of the configured pubsub topics, don't dial\n * 3. If the peer is not dialable based on bootstrap status, don't dial\n * 4. If the peer is already has an active dial attempt, or has been dialed before, don't dial it\n * @returns true if the peer should be dialed, false otherwise\n */\n async shouldDialPeer(peerId) {\n const isConnected = this.libp2p.getConnections(peerId).length > 0;\n if (isConnected) {\n log.warn(`Already connected to peer ${peerId.toString()}. Not dialing.`);\n return false;\n }\n const isSameShard = await this.isPeerTopicConfigured(peerId);\n if (!isSameShard) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n log.warn(`Discovered peer ${peerId.toString()} with ShardInfo ${shardInfo} is not part of any of the configured pubsub topics (${this.pubsubTopics}).\n Not dialing.`);\n return false;\n }\n const isPreferredBasedOnBootstrap = await this.isPeerDialableBasedOnBootstrapStatus(peerId);\n if (!isPreferredBasedOnBootstrap) {\n log.warn(`Peer ${peerId.toString()} is not dialable based on bootstrap status. Not dialing.`);\n return false;\n }\n const hasBeenDialed = this.dialAttemptsForPeer.has(peerId.toString());\n if (hasBeenDialed) {\n log.warn(`Peer ${peerId.toString()} has already been attempted dial before, or already has a dial attempt in progress, skipping dial`);\n return false;\n }\n return true;\n }\n /**\n * Checks if the peer is dialable based on the following conditions:\n * 1. If the peer is a bootstrap peer, it is only dialable if the number of current bootstrap connections is less than the max allowed.\n * 2. If the peer is not a bootstrap peer\n */\n async isPeerDialableBasedOnBootstrapStatus(peerId) {\n const tagNames = await this.getTagNamesForPeer(peerId);\n const isBootstrap = tagNames.some((tagName) => tagName === Tags.BOOTSTRAP);\n if (!isBootstrap) {\n return true;\n }\n const currentBootstrapConnections = this.libp2p\n .getConnections()\n .filter((conn) => {\n return conn.tags.find((name) => name === Tags.BOOTSTRAP);\n }).length;\n return currentBootstrapConnections < this.options.maxBootstrapPeersAllowed;\n }\n async dispatchDiscoveryEvent(peerId) {\n const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes(Tags.BOOTSTRAP);\n this.dispatchEvent(new CustomEvent(isBootstrap\n ? EPeersByDiscoveryEvents.PEER_DISCOVERY_BOOTSTRAP\n : EPeersByDiscoveryEvents.PEER_DISCOVERY_PEER_EXCHANGE, {\n detail: peerId\n }));\n }\n /**\n * Fetches the tag names for a given peer\n */\n async getTagNamesForPeer(peerId) {\n try {\n const peer = await this.libp2p.peerStore.get(peerId);\n return Array.from(peer.tags.keys());\n }\n catch (error) {\n log.error(`Failed to get peer ${peerId}, error: ${error}`);\n return [];\n }\n }\n async isPeerTopicConfigured(peerId) {\n const shardInfo = await this.getPeerShardInfo(peerId, this.libp2p.peerStore);\n // If there's no shard information, simply return true\n if (!shardInfo)\n return true;\n const pubsubTopics = shardInfoToPubsubTopics(shardInfo);\n const isTopicConfigured = pubsubTopics.some((topic) => this.pubsubTopics.includes(topic));\n return isTopicConfigured;\n }\n async getPeerShardInfo(peerId, peerStore) {\n const peer = await peerStore.get(peerId);\n const shardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (!shardInfoBytes)\n return undefined;\n return decodeRelayShard(shardInfoBytes);\n }\n startNetworkStatusListener() {\n try {\n globalThis.addEventListener(\"online\", this.onEventHandlers[\"browser:network\"]);\n globalThis.addEventListener(\"offline\", this.onEventHandlers[\"browser:network\"]);\n }\n catch (err) {\n log.error(`Failed to start network listener: ${err}`);\n }\n }\n stopNetworkStatusListener() {\n try {\n globalThis.removeEventListener(\"online\", this.onEventHandlers[\"browser:network\"]);\n globalThis.removeEventListener(\"offline\", this.onEventHandlers[\"browser:network\"]);\n }\n catch (err) {\n log.error(`Failed to stop network listener: ${err}`);\n }\n }\n setP2PNetworkConnected() {\n if (!this.isP2PNetworkConnected) {\n this.isP2PNetworkConnected = true;\n this.dispatchWakuConnectionEvent();\n }\n }\n setP2PNetworkDisconnected() {\n if (this.isP2PNetworkConnected &&\n this.libp2p.getConnections().length === 0) {\n this.isP2PNetworkConnected = false;\n this.dispatchWakuConnectionEvent();\n }\n }\n dispatchWakuConnectionEvent() {\n this.dispatchEvent(new CustomEvent(EConnectionStateEvents.CONNECTION_STATUS, {\n detail: this.isConnected()\n }));\n }\n}\n//# sourceMappingURL=connection_manager.js.map","import { HealthStatus, Protocols } from \"@waku/interfaces\";\nclass HealthManager {\n static instance;\n health;\n constructor() {\n this.health = {\n overallStatus: HealthStatus.Unhealthy,\n protocolStatuses: new Map()\n };\n }\n static getInstance() {\n if (!HealthManager.instance) {\n HealthManager.instance = new HealthManager();\n }\n return HealthManager.instance;\n }\n getHealthStatus() {\n return this.health.overallStatus;\n }\n getProtocolStatus(protocol) {\n return this.health.protocolStatuses.get(protocol);\n }\n updateProtocolHealth(multicodec, connectedPeers) {\n const protocol = this.getNameFromMulticodec(multicodec);\n let status = HealthStatus.Unhealthy;\n if (connectedPeers == 1) {\n status = HealthStatus.MinimallyHealthy;\n }\n else if (connectedPeers >= 2) {\n status = HealthStatus.SufficientlyHealthy;\n }\n this.health.protocolStatuses.set(protocol, {\n name: protocol,\n status: status,\n lastUpdate: new Date()\n });\n this.updateOverallHealth();\n }\n getNameFromMulticodec(multicodec) {\n let name;\n if (multicodec.includes(\"filter\")) {\n name = Protocols.Filter;\n }\n else if (multicodec.includes(\"lightpush\")) {\n name = Protocols.LightPush;\n }\n else if (multicodec.includes(\"store\")) {\n name = Protocols.Store;\n }\n else {\n throw new Error(`Unknown protocol: ${multicodec}`);\n }\n return name;\n }\n updateOverallHealth() {\n const relevantProtocols = [Protocols.LightPush, Protocols.Filter];\n const statuses = relevantProtocols.map((p) => this.getProtocolStatus(p)?.status);\n if (statuses.some((status) => status === HealthStatus.Unhealthy)) {\n this.health.overallStatus = HealthStatus.Unhealthy;\n }\n else if (statuses.some((status) => status === HealthStatus.MinimallyHealthy)) {\n this.health.overallStatus = HealthStatus.MinimallyHealthy;\n }\n else {\n this.health.overallStatus = HealthStatus.SufficientlyHealthy;\n }\n }\n}\nexport const getHealthManager = () => HealthManager.getInstance();\n//# sourceMappingURL=health_manager.js.map","import { ProtocolError } from \"@waku/interfaces\";\nimport { proto_metadata } from \"@waku/proto\";\nimport { encodeRelayShard, Logger, pubsubTopicsToShardInfo } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { BaseProtocol } from \"../base_protocol.js\";\nconst log = new Logger(\"metadata\");\nexport const MetadataCodec = \"/vac/waku/metadata/1.0.0\";\nclass Metadata extends BaseProtocol {\n pubsubTopics;\n libp2pComponents;\n handshakesConfirmed = new Map();\n constructor(pubsubTopics, libp2p) {\n super(MetadataCodec, libp2p.components, pubsubTopics);\n this.pubsubTopics = pubsubTopics;\n this.libp2pComponents = libp2p;\n void libp2p.registrar.handle(MetadataCodec, (streamData) => {\n void this.onRequest(streamData);\n });\n }\n /**\n * Make a metadata query to a peer\n */\n async query(peerId) {\n const request = proto_metadata.WakuMetadataRequest.encode(pubsubTopicsToShardInfo(this.pubsubTopics));\n const peer = await this.libp2pComponents.peerStore.get(peerId);\n if (!peer) {\n return {\n shardInfo: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (error) {\n log.error(\"Failed to get stream\", error);\n return {\n shardInfo: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const encodedResponse = await pipe([request], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return {\n shardInfo: null,\n error\n };\n }\n await this.savePeerShardInfo(peerId, shardInfo);\n return {\n shardInfo,\n error: null\n };\n }\n async confirmOrAttemptHandshake(peerId) {\n const shardInfo = this.handshakesConfirmed.get(peerId.toString());\n if (shardInfo) {\n return {\n shardInfo,\n error: null\n };\n }\n return await this.query(peerId);\n }\n /**\n * Handle an incoming metadata request\n */\n async onRequest(streamData) {\n try {\n const { stream, connection } = streamData;\n const encodedShardInfo = proto_metadata.WakuMetadataResponse.encode(pubsubTopicsToShardInfo(this.pubsubTopics));\n const encodedResponse = await pipe([encodedShardInfo], lp.encode, stream, lp.decode, async (source) => await all(source));\n const { error, shardInfo } = this.decodeMetadataResponse(encodedResponse);\n if (error) {\n return;\n }\n await this.savePeerShardInfo(connection.remotePeer, shardInfo);\n }\n catch (error) {\n log.error(\"Error handling metadata request\", error);\n }\n }\n decodeMetadataResponse(encodedResponse) {\n const bytes = new Uint8ArrayList();\n encodedResponse.forEach((chunk) => {\n bytes.append(chunk);\n });\n const response = proto_metadata.WakuMetadataResponse.decode(bytes);\n if (!response) {\n log.error(\"Error decoding metadata response\");\n return {\n shardInfo: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n return {\n shardInfo: response,\n error: null\n };\n }\n async savePeerShardInfo(peerId, shardInfo) {\n // add or update the shardInfo to peer store\n await this.libp2pComponents.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n this.handshakesConfirmed.set(peerId.toString(), shardInfo);\n }\n}\nexport function wakuMetadata(pubsubTopics) {\n return (components) => new Metadata(pubsubTopics, components);\n}\n//# sourceMappingURL=index.js.map","/**\n * All PeerId implementations must use this symbol as the name of a property\n * with a boolean `true` value\n */\nexport const peerIdSymbol = Symbol.for('@libp2p/peer-id');\n/**\n * Returns true if the passed argument is a PeerId implementation\n */\nexport function isPeerId(other) {\n return Boolean(other?.[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map","import { Parser } from \"./parser.js\";\n// See https://stackoverflow.com/questions/166132/maximum-length-of-the-textual-representation-of-an-ipv6-address\nconst MAX_IPV6_LENGTH = 45;\nconst MAX_IPV4_LENGTH = 15;\nconst parser = new Parser();\n/** Parse `input` into IPv4 bytes. */\nexport function parseIPv4(input) {\n if (input.length > MAX_IPV4_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv4Addr());\n}\n/** Parse `input` into IPv6 bytes. */\nexport function parseIPv6(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPv6Addr());\n}\n/** Parse `input` into IPv4 or IPv6 bytes. */\nexport function parseIP(input) {\n // strip zone index if it is present\n if (input.includes(\"%\")) {\n input = input.split(\"%\")[0];\n }\n if (input.length > MAX_IPV6_LENGTH) {\n return undefined;\n }\n return parser.new(input).parseWith(() => parser.readIPAddr());\n}\n//# sourceMappingURL=parse.js.map","/* eslint-disable @typescript-eslint/no-unsafe-return */\nexport class Parser {\n index = 0;\n input = \"\";\n new(input) {\n this.index = 0;\n this.input = input;\n return this;\n }\n /** Run a parser, and restore the pre-parse state if it fails. */\n readAtomically(fn) {\n const index = this.index;\n const result = fn();\n if (result === undefined) {\n this.index = index;\n }\n return result;\n }\n /** Run a parser, but fail if the entire input wasn't consumed. Doesn't run atomically. */\n parseWith(fn) {\n const result = fn();\n if (this.index !== this.input.length) {\n return undefined;\n }\n return result;\n }\n /** Peek the next character from the input */\n peekChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index];\n }\n /** Read the next character from the input */\n readChar() {\n if (this.index >= this.input.length) {\n return undefined;\n }\n return this.input[this.index++];\n }\n /** Read the next character from the input if it matches the target. */\n readGivenChar(target) {\n return this.readAtomically(() => {\n const char = this.readChar();\n if (char !== target) {\n return undefined;\n }\n return char;\n });\n }\n /**\n * Helper for reading separators in an indexed loop. Reads the separator\n * character iff index > 0, then runs the parser. When used in a loop,\n * the separator character will only be read on index > 0 (see\n * readIPv4Addr for an example)\n */\n readSeparator(sep, index, inner) {\n return this.readAtomically(() => {\n if (index > 0) {\n if (this.readGivenChar(sep) === undefined) {\n return undefined;\n }\n }\n return inner();\n });\n }\n /**\n * Read a number off the front of the input in the given radix, stopping\n * at the first non-digit character or eof. Fails if the number has more\n * digits than max_digits or if there is no number.\n */\n readNumber(radix, maxDigits, allowZeroPrefix, maxBytes) {\n return this.readAtomically(() => {\n let result = 0;\n let digitCount = 0;\n const leadingChar = this.peekChar();\n if (leadingChar === undefined) {\n return undefined;\n }\n const hasLeadingZero = leadingChar === \"0\";\n const maxValue = 2 ** (8 * maxBytes) - 1;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const digit = this.readAtomically(() => {\n const char = this.readChar();\n if (char === undefined) {\n return undefined;\n }\n const num = Number.parseInt(char, radix);\n if (Number.isNaN(num)) {\n return undefined;\n }\n return num;\n });\n if (digit === undefined) {\n break;\n }\n result *= radix;\n result += digit;\n if (result > maxValue) {\n return undefined;\n }\n digitCount += 1;\n if (maxDigits !== undefined) {\n if (digitCount > maxDigits) {\n return undefined;\n }\n }\n }\n if (digitCount === 0) {\n return undefined;\n }\n else if (!allowZeroPrefix && hasLeadingZero && digitCount > 1) {\n return undefined;\n }\n else {\n return result;\n }\n });\n }\n /** Read an IPv4 address. */\n readIPv4Addr() {\n return this.readAtomically(() => {\n const out = new Uint8Array(4);\n for (let i = 0; i < out.length; i++) {\n const ix = this.readSeparator(\".\", i, () => this.readNumber(10, 3, false, 1));\n if (ix === undefined) {\n return undefined;\n }\n out[i] = ix;\n }\n return out;\n });\n }\n /** Read an IPv6 Address. */\n readIPv6Addr() {\n /**\n * Read a chunk of an IPv6 address into `groups`. Returns the number\n * of groups read, along with a bool indicating if an embedded\n * trailing IPv4 address was read. Specifically, read a series of\n * colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional\n * trailing embedded IPv4 address.\n */\n const readGroups = (groups) => {\n for (let i = 0; i < groups.length / 2; i++) {\n const ix = i * 2;\n // Try to read a trailing embedded IPv4 address. There must be at least 4 groups left.\n if (i < groups.length - 3) {\n const ipv4 = this.readSeparator(\":\", i, () => this.readIPv4Addr());\n if (ipv4 !== undefined) {\n groups[ix] = ipv4[0];\n groups[ix + 1] = ipv4[1];\n groups[ix + 2] = ipv4[2];\n groups[ix + 3] = ipv4[3];\n return [ix + 4, true];\n }\n }\n const group = this.readSeparator(\":\", i, () => this.readNumber(16, 4, true, 2));\n if (group === undefined) {\n return [ix, false];\n }\n groups[ix] = group >> 8;\n groups[ix + 1] = group & 255;\n }\n return [groups.length, false];\n };\n return this.readAtomically(() => {\n // Read the front part of the address; either the whole thing, or up to the first ::\n const head = new Uint8Array(16);\n const [headSize, headIp4] = readGroups(head);\n if (headSize === 16) {\n return head;\n }\n // IPv4 part is not allowed before `::`\n if (headIp4) {\n return undefined;\n }\n // Read `::` if previous code parsed less than 8 groups.\n // `::` indicates one or more groups of 16 bits of zeros.\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n if (this.readGivenChar(\":\") === undefined) {\n return undefined;\n }\n // Read the back part of the address. The :: must contain at least one\n // set of zeroes, so our max length is 7.\n const tail = new Uint8Array(14);\n const limit = 16 - (headSize + 2);\n const [tailSize] = readGroups(tail.subarray(0, limit));\n // Concat the head and tail of the IP address\n head.set(tail.subarray(0, tailSize), 16 - tailSize);\n return head;\n });\n }\n /** Read an IP Address, either IPv4 or IPv6. */\n readIPAddr() {\n return this.readIPv4Addr() ?? this.readIPv6Addr();\n }\n}\n//# sourceMappingURL=parser.js.map","import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { allFF, deepEqual } from \"./util.js\";\nexport const IPv4Len = 4;\nexport const IPv6Len = 16;\nexport const maxIPv6Octet = parseInt(\"0xFFFF\", 16);\nexport const ipv4Prefix = new Uint8Array([\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255,\n]);\nexport function maskIp(ip, mask) {\n if (mask.length === IPv6Len && ip.length === IPv4Len && allFF(mask, 0, 11)) {\n mask = mask.slice(12);\n }\n if (mask.length === IPv4Len &&\n ip.length === IPv6Len &&\n deepEqual(ip, ipv4Prefix, 0, 11)) {\n ip = ip.slice(12);\n }\n const n = ip.length;\n if (n != mask.length) {\n throw new Error(\"Failed to mask ip\");\n }\n const out = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n out[i] = ip[i] & mask[i];\n }\n return out;\n}\nexport function containsIp(net, ip) {\n if (typeof ip === \"string\") {\n ip = parseIP(ip);\n }\n if (ip == null)\n throw new Error(\"Invalid ip\");\n if (ip.length !== net.network.length) {\n return false;\n }\n for (let i = 0; i < ip.length; i++) {\n if ((net.network[i] & net.mask[i]) !== (ip[i] & net.mask[i])) {\n return false;\n }\n }\n return true;\n}\nexport function iPv4FromIPv6(ip) {\n if (!isIPv4mappedIPv6(ip)) {\n throw new Error(\"Must have 0xffff prefix\");\n }\n return ip.slice(12);\n}\nexport function isIPv4mappedIPv6(ip) {\n return deepEqual(ip, ipv4Prefix, 0, 11);\n}\n//# sourceMappingURL=ip.js.map","import { IPv4Len, IPv6Len } from \"./ip.js\";\nexport function allFF(a, from, to) {\n let i = 0;\n for (const e of a) {\n if (i < from)\n continue;\n if (i > to)\n break;\n if (e !== 0xff)\n return false;\n i++;\n }\n return true;\n}\nexport function deepEqual(a, b, from, to) {\n let i = 0;\n for (const e of a) {\n if (i < from)\n continue;\n if (i > to)\n break;\n if (e !== b[i])\n return false;\n i++;\n }\n return true;\n}\n/***\n * Returns long ip format\n */\nexport function ipToString(ip) {\n switch (ip.length) {\n case IPv4Len: {\n return ip.join(\".\");\n }\n case IPv6Len: {\n const result = [];\n for (let i = 0; i < ip.length; i++) {\n if (i % 2 === 0) {\n result.push(ip[i].toString(16).padStart(2, \"0\") +\n ip[i + 1].toString(16).padStart(2, \"0\"));\n }\n }\n return result.join(\":\");\n }\n default: {\n throw new Error(\"Invalid ip length\");\n }\n }\n}\n/**\n * If mask is a sequence of 1 bits followed by 0 bits, return number of 1 bits else -1\n */\nexport function simpleMaskLength(mask) {\n let ones = 0;\n // eslint-disable-next-line prefer-const\n for (let [index, byte] of mask.entries()) {\n if (byte === 0xff) {\n ones += 8;\n continue;\n }\n while ((byte & 0x80) != 0) {\n ones++;\n byte = byte << 1;\n }\n if ((byte & 0x80) != 0) {\n return -1;\n }\n for (let i = index + 1; i < mask.length; i++) {\n if (mask[i] != 0) {\n return -1;\n }\n }\n break;\n }\n return ones;\n}\nexport function maskToHex(mask) {\n let hex = \"0x\";\n for (const byte of mask) {\n hex += (byte >> 4).toString(16) + (byte & 0x0f).toString(16);\n }\n return hex;\n}\n//# sourceMappingURL=util.js.map","import { parseIPv4, parseIPv6 } from \"@chainsafe/is-ip/parse\";\nimport { IPv4Len, IPv6Len, maskIp } from \"./ip.js\";\nexport function parseCidr(s) {\n const [address, maskString] = s.split(\"/\");\n if (!address || !maskString)\n throw new Error(\"Failed to parse given CIDR: \" + s);\n let ipLength = IPv4Len;\n let ip = parseIPv4(address);\n if (ip == null) {\n ipLength = IPv6Len;\n ip = parseIPv6(address);\n if (ip == null)\n throw new Error(\"Failed to parse given CIDR: \" + s);\n }\n const m = parseInt(maskString, 10);\n if (Number.isNaN(m) ||\n String(m).length !== maskString.length ||\n m < 0 ||\n m > ipLength * 8) {\n throw new Error(\"Failed to parse given CIDR: \" + s);\n }\n const mask = cidrMask(m, 8 * ipLength);\n return {\n network: maskIp(ip, mask),\n mask,\n };\n}\nexport function cidrMask(ones, bits) {\n if (bits !== 8 * IPv4Len && bits !== 8 * IPv6Len)\n throw new Error(\"Invalid CIDR mask\");\n if (ones < 0 || ones > bits)\n throw new Error(\"Invalid CIDR mask\");\n const l = bits / 8;\n const m = new Uint8Array(l);\n for (let i = 0; i < l; i++) {\n if (ones >= 8) {\n m[i] = 0xff;\n ones -= 8;\n continue;\n }\n m[i] = 255 - (0xff >> ones);\n ones = 0;\n }\n return m;\n}\n//# sourceMappingURL=cidr.js.map","import { parseIP } from \"@chainsafe/is-ip/parse\";\nimport { cidrMask, parseCidr } from \"./cidr.js\";\nimport { containsIp, maskIp } from \"./ip.js\";\nimport { ipToString, maskToHex, simpleMaskLength } from \"./util.js\";\nexport class IpNet {\n /**\n *\n * @param ipOrCidr either network ip or full cidr address\n * @param mask in case ipOrCidr is network this can be either mask in decimal format or as ip address\n */\n constructor(ipOrCidr, mask) {\n if (mask == null) {\n ({ network: this.network, mask: this.mask } = parseCidr(ipOrCidr));\n }\n else {\n const ipResult = parseIP(ipOrCidr);\n if (ipResult == null) {\n throw new Error(\"Failed to parse network\");\n }\n mask = String(mask);\n const m = parseInt(mask, 10);\n if (Number.isNaN(m) ||\n String(m).length !== mask.length ||\n m < 0 ||\n m > ipResult.length * 8) {\n const maskResult = parseIP(mask);\n if (maskResult == null) {\n throw new Error(\"Failed to parse mask\");\n }\n this.mask = maskResult;\n }\n else {\n this.mask = cidrMask(m, 8 * ipResult.length);\n }\n this.network = maskIp(ipResult, this.mask);\n }\n }\n /**\n * Checks if netmask contains ip address\n * @param ip\n * @returns\n */\n contains(ip) {\n return containsIp({ network: this.network, mask: this.mask }, ip);\n }\n /**Serializes back to string format */\n toString() {\n const l = simpleMaskLength(this.mask);\n const mask = l !== -1 ? String(l) : maskToHex(this.mask);\n return ipToString(this.network) + \"/\" + mask;\n }\n}\n//# sourceMappingURL=ipnet.js.map","import { parseIP, parseIPv4, parseIPv6 } from \"./parse.js\";\n/** Check if `input` is IPv4. */\nexport function isIPv4(input) {\n return Boolean(parseIPv4(input));\n}\n/** Check if `input` is IPv6. */\nexport function isIPv6(input) {\n return Boolean(parseIPv6(input));\n}\n/** Check if `input` is IPv4 or IPv6. */\nexport function isIP(input) {\n return Boolean(parseIP(input));\n}\n/**\n * @returns `6` if `input` is IPv6, `4` if `input` is IPv4, or `undefined` if `input` is neither.\n */\nexport function ipVersion(input) {\n if (isIPv4(input)) {\n return 4;\n }\n else if (isIPv6(input)) {\n return 6;\n }\n else {\n return undefined;\n }\n}\n//# sourceMappingURL=is-ip.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nexport { isIP } from '@chainsafe/is-ip';\nexport const isV4 = isIPv4;\nexport const isV6 = isIPv6;\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L7\n// but with buf/offset args removed because we don't use them\nexport const toBytes = function (ip) {\n let offset = 0;\n ip = ip.toString().trim();\n if (isV4(ip)) {\n const bytes = new Uint8Array(offset + 4);\n ip.split(/\\./g).forEach((byte) => {\n bytes[offset++] = parseInt(byte, 10) & 0xff;\n });\n return bytes;\n }\n if (isV6(ip)) {\n const sections = ip.split(':', 8);\n let i;\n for (i = 0; i < sections.length; i++) {\n const isv4 = isV4(sections[i]);\n let v4Buffer;\n if (isv4) {\n v4Buffer = toBytes(sections[i]);\n sections[i] = uint8ArrayToString(v4Buffer.slice(0, 2), 'base16');\n }\n if (v4Buffer != null && ++i < 8) {\n sections.splice(i, 0, uint8ArrayToString(v4Buffer.slice(2, 4), 'base16'));\n }\n }\n if (sections[0] === '') {\n while (sections.length < 8)\n sections.unshift('0');\n }\n else if (sections[sections.length - 1] === '') {\n while (sections.length < 8)\n sections.push('0');\n }\n else if (sections.length < 8) {\n for (i = 0; i < sections.length && sections[i] !== ''; i++)\n ;\n const argv = [i, 1];\n for (i = 9 - sections.length; i > 0; i--) {\n argv.push('0');\n }\n sections.splice.apply(sections, argv);\n }\n const bytes = new Uint8Array(offset + 16);\n for (i = 0; i < sections.length; i++) {\n const word = parseInt(sections[i], 16);\n bytes[offset++] = (word >> 8) & 0xff;\n bytes[offset++] = word & 0xff;\n }\n return bytes;\n }\n throw new Error('invalid ip address');\n};\n// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63\nexport const toString = function (buf, offset = 0, length) {\n offset = ~~offset;\n length = length ?? (buf.length - offset);\n const view = new DataView(buf.buffer);\n if (length === 4) {\n const result = [];\n // IPv4\n for (let i = 0; i < length; i++) {\n result.push(buf[offset + i]);\n }\n return result.join('.');\n }\n if (length === 16) {\n const result = [];\n // IPv6\n for (let i = 0; i < length; i += 2) {\n result.push(view.getUint16(offset + i).toString(16));\n }\n return result.join(':')\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::');\n }\n return '';\n};\n//# sourceMappingURL=ip.js.map","const V = -1;\nexport const names = {};\nexport const codes = {};\nexport const table = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [481, V, 'http-path'],\n [777, V, 'memory']\n];\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row);\n codes[proto.code] = proto;\n names[proto.name] = proto;\n});\nexport function createProtocol(code, size, name, resolvable, path) {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n };\n}\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nexport function getProtocol(proto) {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto];\n }\n throw new Error(`no protocol with code: ${proto}`);\n }\n else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto];\n }\n throw new Error(`no protocol with name: ${proto}`);\n }\n throw new Error(`invalid protocol id type: ${typeof proto}`);\n}\n//# sourceMappingURL=protocols-table.js.map","import { IpNet } from '@chainsafe/netmask';\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { bases } from 'multiformats/basics';\nimport { CID } from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport * as ip from './ip.js';\nimport { getProtocol } from './protocols-table.js';\nconst ip4Protocol = getProtocol('ip4');\nconst ip6Protocol = getProtocol('ip6');\nconst ipcidrProtocol = getProtocol('ipcidr');\nexport function convert(proto, a) {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a);\n }\n else {\n return convertToBytes(proto, a);\n }\n}\n/**\n * Convert [code,Uint8Array] to string\n */\n// eslint-disable-next-line complexity\nexport function convertToString(proto, buf) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf);\n case 42: // ipv6zone\n return bytes2str(buf);\n case 43: // ipcidr\n return uint8ArrayToString(buf, 'base10');\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString();\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf);\n case 421: // ipfs\n return bytes2mh(buf);\n case 444: // onion\n return bytes2onion(buf);\n case 445: // onion3\n return bytes2onion(buf);\n case 466: // certhash\n return bytes2mb(buf);\n case 481: // http-path\n return globalThis.encodeURIComponent(bytes2str(buf));\n default:\n return uint8ArrayToString(buf, 'base16'); // no clue. convert to hex\n }\n}\n// eslint-disable-next-line complexity\nexport function convertToBytes(proto, str) {\n const protocol = getProtocol(proto);\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str);\n case 41: // ipv6\n return ip2bytes(str);\n case 42: // ipv6zone\n return str2bytes(str);\n case 43: // ipcidr\n return uint8ArrayFromString(str, 'base10');\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10));\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str);\n case 421: // ipfs\n return mh2bytes(str);\n case 444: // onion\n return onion2bytes(str);\n case 445: // onion3\n return onion32bytes(str);\n case 466: // certhash\n return mb2bytes(str);\n case 481: // http-path\n return str2bytes(globalThis.decodeURIComponent(str));\n default:\n return uint8ArrayFromString(str, 'base16'); // no clue. convert from hex\n }\n}\nexport function convertToIpNet(multiaddr) {\n let mask;\n let addr;\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value;\n }\n if (code === ipcidrProtocol.code) {\n mask = value;\n }\n });\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr');\n }\n return new IpNet(addr, mask);\n}\nconst decoders = Object.values(bases).map((c) => c.decoder);\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1]);\n decoders.slice(2).forEach((d) => (acc = acc.or(d)));\n return acc;\n})();\nfunction ip2bytes(ipString) {\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ip.toBytes(ipString);\n}\nfunction bytes2ip(ipBuff) {\n const ipString = ip.toString(ipBuff, 0, ipBuff.length);\n if (ipString == null) {\n throw new Error('ipBuff is required');\n }\n if (!ip.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ipString;\n}\nfunction port2bytes(port) {\n const buf = new ArrayBuffer(2);\n const view = new DataView(buf);\n view.setUint16(0, port);\n return new Uint8Array(buf);\n}\nfunction bytes2port(buf) {\n const view = new DataView(buf.buffer);\n return view.getUint16(buf.byteOffset);\n}\nfunction str2bytes(str) {\n const buf = uint8ArrayFromString(str);\n const size = Uint8Array.from(varint.encode(buf.length));\n return uint8ArrayConcat([size, buf], size.length + buf.length);\n}\nfunction bytes2str(buf) {\n const size = varint.decode(buf);\n buf = buf.slice(varint.encodingLength(size));\n if (buf.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(buf);\n}\nfunction mh2bytes(hash) {\n let mh;\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = Digest.decode(base58btc.decode(`z${hash}`)).bytes;\n }\n else {\n mh = CID.parse(hash).multihash.bytes;\n }\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(varint.encode(mh.length));\n return uint8ArrayConcat([size, mh], size.length + mh.length);\n}\nfunction mb2bytes(mbstr) {\n const mb = anybaseDecoder.decode(mbstr);\n const size = Uint8Array.from(varint.encode(mb.length));\n return uint8ArrayConcat([size, mb], size.length + mb.length);\n}\nfunction bytes2mb(buf) {\n const size = varint.decode(buf);\n const hash = buf.slice(varint.encodingLength(size));\n if (hash.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return 'u' + uint8ArrayToString(hash, 'base64url');\n}\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh(buf) {\n const size = varint.decode(buf);\n const address = buf.slice(varint.encodingLength(size));\n if (address.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return uint8ArrayToString(address, 'base58btc');\n}\nfunction onion2bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode('b' + addr[0]);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction onion32bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = base32.decode(`b${addr[0]}`);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return uint8ArrayConcat([buf, portBuf], buf.length + portBuf.length);\n}\nfunction bytes2onion(buf) {\n const addrBytes = buf.slice(0, buf.length - 2);\n const portBytes = buf.slice(buf.length - 2);\n const addr = uint8ArrayToString(addrBytes, 'base32');\n const port = bytes2port(portBytes);\n return `${addr}:${port}`;\n}\n//# sourceMappingURL=convert.js.map","import * as varint from 'uint8-varint';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { convertToBytes, convertToString } from './convert.js';\nimport { getProtocol } from './protocols-table.js';\nexport function stringToMultiaddrParts(str) {\n str = cleanPath(str);\n const tuples = [];\n const stringTuples = [];\n let path = null;\n const parts = str.split('/').slice(1);\n if (parts.length === 1 && parts[0] === '') {\n return {\n bytes: new Uint8Array(),\n string: '/',\n tuples: [],\n stringTuples: [],\n path: null\n };\n }\n for (let p = 0; p < parts.length; p++) {\n const part = parts[p];\n const proto = getProtocol(part);\n if (proto.size === 0) {\n tuples.push([proto.code]);\n stringTuples.push([proto.code]);\n // eslint-disable-next-line no-continue\n continue;\n }\n p++; // advance addr part\n if (p >= parts.length) {\n throw ParseError('invalid address: ' + str);\n }\n // if it's a path proto, take the rest\n if (proto.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = cleanPath(parts.slice(p).join('/'));\n tuples.push([proto.code, convertToBytes(proto.code, path)]);\n stringTuples.push([proto.code, path]);\n break;\n }\n const bytes = convertToBytes(proto.code, parts[p]);\n tuples.push([proto.code, bytes]);\n stringTuples.push([proto.code, convertToString(proto.code, bytes)]);\n }\n return {\n string: stringTuplesToString(stringTuples),\n bytes: tuplesToBytes(tuples),\n tuples,\n stringTuples,\n path\n };\n}\nexport function bytesToMultiaddrParts(bytes) {\n const tuples = [];\n const stringTuples = [];\n let path = null;\n let i = 0;\n while (i < bytes.length) {\n const code = varint.decode(bytes, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, bytes.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n stringTuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = bytes.slice(i + n, i + n + size);\n i += (size + n);\n if (i > bytes.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(bytes, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n const stringAddr = convertToString(code, addr);\n stringTuples.push([code, stringAddr]);\n if (p.path === true) {\n // should we need to check each path part to see if it's a proto?\n // This would allow for other protocols to be added after a unix path,\n // however it would have issues if the path had a protocol name in the path\n path = stringAddr;\n break;\n }\n }\n return {\n bytes: Uint8Array.from(bytes),\n string: stringTuplesToString(stringTuples),\n tuples,\n stringTuples,\n path\n };\n}\n/**\n * [[str name, str addr]... ] -> string\n */\nfunction stringTuplesToString(tuples) {\n const parts = [];\n tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n parts.push(proto.name);\n if (tup.length > 1 && tup[1] != null) {\n parts.push(tup[1]);\n }\n return null;\n });\n return cleanPath(parts.join('/'));\n}\n/**\n * [[int code, Uint8Array ]... ] -> Uint8Array\n */\nexport function tuplesToBytes(tuples) {\n return uint8ArrayConcat(tuples.map((tup) => {\n const proto = getProtocol(tup[0]);\n let buf = Uint8Array.from(varint.encode(proto.code));\n if (tup.length > 1 && tup[1] != null) {\n buf = uint8ArrayConcat([buf, tup[1]]); // add address buffer\n }\n return buf;\n }));\n}\n/**\n * For the passed address, return the serialized size\n */\nfunction sizeForAddr(p, addr) {\n if (p.size > 0) {\n return p.size / 8;\n }\n else if (p.size === 0) {\n return 0;\n }\n else {\n const size = varint.decode(addr instanceof Uint8Array ? addr : Uint8Array.from(addr));\n return size + varint.encodingLength(size);\n }\n}\nexport function bytesToTuples(buf) {\n const tuples = [];\n let i = 0;\n while (i < buf.length) {\n const code = varint.decode(buf, i);\n const n = varint.encodingLength(code);\n const p = getProtocol(code);\n const size = sizeForAddr(p, buf.slice(i + n));\n if (size === 0) {\n tuples.push([code]);\n i += n;\n // eslint-disable-next-line no-continue\n continue;\n }\n const addr = buf.slice(i + n, i + n + size);\n i += (size + n);\n if (i > buf.length) { // did not end _exactly_ at buffer.length\n throw ParseError('Invalid address Uint8Array: ' + uint8ArrayToString(buf, 'base16'));\n }\n // ok, tuple seems good.\n tuples.push([code, addr]);\n }\n return tuples;\n}\nexport function cleanPath(str) {\n return '/' + str.trim().split('/').filter((a) => a).join('/');\n}\nexport function ParseError(str) {\n return new Error('Error parsing address: ' + str);\n}\n//# sourceMappingURL=codec.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { bytesToMultiaddrParts, stringToMultiaddrParts, tuplesToBytes } from './codec.js';\nimport { getProtocol, names } from './protocols-table.js';\nimport { isMultiaddr, multiaddr, resolvers } from './index.js';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nexport const symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');\nconst DNS_CODES = [\n getProtocol('dns').code,\n getProtocol('dns4').code,\n getProtocol('dns6').code,\n getProtocol('dnsaddr').code\n];\nclass NoAvailableResolverError extends Error {\n constructor(message = 'No available resolver') {\n super(message);\n this.name = 'NoAvailableResolverError';\n }\n}\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nexport class Multiaddr {\n bytes;\n #string;\n #tuples;\n #stringTuples;\n #path;\n [symbol] = true;\n constructor(addr) {\n // default\n if (addr == null) {\n addr = '';\n }\n let parts;\n if (addr instanceof Uint8Array) {\n parts = bytesToMultiaddrParts(addr);\n }\n else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`);\n }\n parts = stringToMultiaddrParts(addr);\n }\n else if (isMultiaddr(addr)) { // Multiaddr\n parts = bytesToMultiaddrParts(addr.bytes);\n }\n else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr');\n }\n this.bytes = parts.bytes;\n this.#string = parts.string;\n this.#tuples = parts.tuples;\n this.#stringTuples = parts.stringTuples;\n this.#path = parts.path;\n }\n toString() {\n return this.#string;\n }\n toJSON() {\n return this.toString();\n }\n toOptions() {\n let family;\n let transport;\n let host;\n let port;\n let zone = '';\n const tcp = getProtocol('tcp');\n const udp = getProtocol('udp');\n const ip4 = getProtocol('ip4');\n const ip6 = getProtocol('ip6');\n const dns6 = getProtocol('dns6');\n const ip6zone = getProtocol('ip6zone');\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`;\n }\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name;\n port = 443;\n host = `${value ?? ''}${zone}`;\n family = code === dns6.code ? 6 : 4;\n }\n if (code === tcp.code || code === udp.code) {\n transport = getProtocol(code).name;\n port = parseInt(value ?? '');\n }\n if (code === ip4.code || code === ip6.code) {\n transport = getProtocol(code).name;\n host = `${value ?? ''}${zone}`;\n family = code === ip6.code ? 6 : 4;\n }\n }\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".');\n }\n const opts = {\n family,\n host,\n transport,\n port\n };\n return opts;\n }\n protos() {\n return this.#tuples.map(([code]) => Object.assign({}, getProtocol(code)));\n }\n protoCodes() {\n return this.#tuples.map(([code]) => code);\n }\n protoNames() {\n return this.#tuples.map(([code]) => getProtocol(code).name);\n }\n tuples() {\n return this.#tuples.map(([code, value]) => {\n if (value == null) {\n return [code];\n }\n return [code, value];\n });\n }\n stringTuples() {\n return this.#stringTuples.map(([code, value]) => {\n if (value == null) {\n return [code];\n }\n return [code, value];\n });\n }\n encapsulate(addr) {\n addr = new Multiaddr(addr);\n return new Multiaddr(this.toString() + addr.toString());\n }\n decapsulate(addr) {\n const addrString = addr.toString();\n const s = this.toString();\n const i = s.lastIndexOf(addrString);\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);\n }\n return new Multiaddr(s.slice(0, i));\n }\n decapsulateCode(code) {\n const tuples = this.tuples();\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr(tuplesToBytes(tuples.slice(0, i)));\n }\n }\n return this;\n }\n getPeerId() {\n try {\n let tuples = [];\n this.stringTuples().forEach(([code, name]) => {\n if (code === names.p2p.code) {\n tuples.push([code, name]);\n }\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === names['p2p-circuit'].code) {\n tuples = [];\n }\n });\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop();\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1];\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return uint8ArrayToString(base58btc.decode(`z${peerIdStr}`), 'base58btc');\n }\n // try to parse peer id as CID\n return uint8ArrayToString(CID.parse(peerIdStr).multihash.bytes, 'base58btc');\n }\n return null;\n }\n catch (e) {\n return null;\n }\n }\n getPath() {\n return this.#path;\n }\n equals(addr) {\n return uint8ArrayEquals(this.bytes, addr.bytes);\n }\n async resolve(options) {\n const resolvableProto = this.protos().find((p) => p.resolvable);\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this];\n }\n const resolver = resolvers.get(resolvableProto.name);\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);\n }\n const result = await resolver(this, options);\n return result.map(str => multiaddr(str));\n }\n nodeAddress() {\n const options = this.toOptions();\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`);\n }\n return {\n family: options.family,\n address: options.host,\n port: options.port\n };\n }\n isThinWaistAddress(addr) {\n const protos = (addr ?? this).protos();\n if (protos.length !== 2) {\n return false;\n }\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false;\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false;\n }\n return true;\n }\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect]() {\n return `Multiaddr(${this.#string})`;\n }\n}\n//# sourceMappingURL=multiaddr.js.map","/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddrResolver)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * }\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\nimport { Multiaddr as MultiaddrClass, symbol } from './multiaddr.js';\nimport { getProtocol } from './protocols-table.js';\n/**\n * All configured {@link Resolver}s\n */\nexport const resolvers = new Map();\nexport { MultiaddrFilter } from './filter/multiaddr-filter.js';\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nexport function fromNodeAddress(addr, transport) {\n if (addr == null) {\n throw new Error('requires node address object');\n }\n if (transport == null) {\n throw new Error('requires transport protocol');\n }\n let ip;\n let host = addr.address;\n switch (addr.family) {\n case 4:\n ip = 'ip4';\n break;\n case 6:\n ip = 'ip6';\n if (host.includes('%')) {\n const parts = host.split('%');\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr');\n }\n host = parts[0];\n const zone = parts[1];\n ip = `/ip6zone/${zone}/ip6`;\n }\n break;\n default:\n throw Error('Invalid addr family, should be 4 or 6.');\n }\n return new MultiaddrClass('/' + [ip, host, transport, addr.port].join('/'));\n}\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nexport function isName(addr) {\n if (!isMultiaddr(addr)) {\n return false;\n }\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable);\n}\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nexport function isMultiaddr(value) {\n return Boolean(value?.[symbol]);\n}\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nexport function multiaddr(addr) {\n return new MultiaddrClass(addr);\n}\nexport { getProtocol as protocols };\n//# sourceMappingURL=index.js.map","import { sha256 } from \"@noble/hashes/sha256\";\nimport { isDefined } from \"@waku/utils\";\nimport { bytesToHex, concat, numberToBytes, utf8ToBytes } from \"@waku/utils/bytes\";\n/**\n * Deterministic Message Hashing as defined in\n * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)\n */\nexport function messageHash(pubsubTopic, message) {\n const pubsubTopicBytes = utf8ToBytes(pubsubTopic);\n const contentTopicBytes = utf8ToBytes(message.contentTopic);\n const timestampBytes = tryConvertTimestampToBytes(message.timestamp);\n const bytes = concat([\n pubsubTopicBytes,\n message.payload,\n contentTopicBytes,\n message.meta,\n timestampBytes\n ].filter(isDefined));\n return sha256(bytes);\n}\nfunction tryConvertTimestampToBytes(timestamp) {\n if (!timestamp) {\n return;\n }\n let bigIntTimestamp;\n if (typeof timestamp === \"bigint\") {\n bigIntTimestamp = timestamp;\n }\n else {\n bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;\n }\n return numberToBytes(bigIntTimestamp);\n}\nexport function messageHashStr(pubsubTopic, message) {\n const hash = messageHash(pubsubTopic, message);\n const hashStr = bytesToHex(hash);\n return hashStr;\n}\n//# sourceMappingURL=index.js.map","import { EConnectionStateEvents } from \"@waku/interfaces\";\nimport { messageHashStr } from \"@waku/message-hash\";\n// TODO(weboko): consider adding as config property or combine with maxAllowedPings\nconst MAX_SUBSCRIBE_ATTEMPTS = 3;\nexport class SubscriptionMonitor {\n /**\n * Cached peers that are in use by subscription.\n * Needed to understand if they disconnect later or not.\n */\n peers = [];\n isStarted = false;\n pubsubTopic;\n config;\n libp2p;\n filter;\n peerManager;\n connectionManager;\n activeSubscriptions;\n keepAliveIntervalId;\n pingFailedAttempts = new Map();\n receivedMessagesFormPeer = new Set();\n receivedMessages = new Set();\n verifiedPeers = new Set();\n constructor(options) {\n this.config = options.config;\n this.connectionManager = options.connectionManager;\n this.filter = options.filter;\n this.peerManager = options.peerManager;\n this.libp2p = options.libp2p;\n this.activeSubscriptions = options.activeSubscriptions;\n this.pubsubTopic = options.pubsubTopic;\n this.onConnectionChange = this.onConnectionChange.bind(this);\n this.onPeerConnected = this.onPeerConnected.bind(this);\n this.onPeerDisconnected = this.onPeerDisconnected.bind(this);\n }\n /**\n * @returns content topic used for Filter verification\n */\n get reservedContentTopic() {\n return `/js-waku-subscription-ping/1/${this.libp2p.peerId.toString()}/utf8`;\n }\n /**\n * Starts:\n * - recurring ping queries;\n * - connection event observers;\n */\n start() {\n if (this.isStarted) {\n return;\n }\n this.isStarted = true;\n this.startKeepAlive();\n this.startConnectionListener();\n this.startPeerConnectionListener();\n }\n /**\n * Stops all recurring queries, event listeners or timers.\n */\n stop() {\n if (!this.isStarted) {\n return;\n }\n this.isStarted = false;\n this.stopKeepAlive();\n this.stopConnectionListener();\n this.stopPeerConnectionListener();\n }\n /**\n * Method to get peers that are used by particular subscription or, if initially called, peers that can be used by subscription.\n * @returns array of peers\n */\n async getPeers() {\n if (!this.isStarted) {\n this.peers = await this.peerManager.getPeers();\n }\n return this.peers;\n }\n /**\n * Notifies monitor if message was received.\n *\n * @param peerId peer from which message is received\n * @param message received message\n *\n * @returns true if message was received from peer\n */\n notifyMessageReceived(peerId, message) {\n const hash = this.buildMessageHash(message);\n this.verifiedPeers.add(peerId);\n this.receivedMessagesFormPeer.add(`${peerId}-${hash}`);\n if (this.receivedMessages.has(hash)) {\n return true;\n }\n this.receivedMessages.add(hash);\n return false;\n }\n buildMessageHash(message) {\n return messageHashStr(this.pubsubTopic, message);\n }\n startConnectionListener() {\n this.connectionManager.addEventListener(EConnectionStateEvents.CONNECTION_STATUS, this.onConnectionChange);\n }\n stopConnectionListener() {\n this.connectionManager.removeEventListener(EConnectionStateEvents.CONNECTION_STATUS, this.onConnectionChange);\n }\n async onConnectionChange({ detail: isConnected }) {\n if (!isConnected) {\n this.stopKeepAlive();\n return;\n }\n await Promise.all(this.peers.map((peer) => this.ping(peer, true)));\n this.startKeepAlive();\n }\n startKeepAlive() {\n if (this.keepAliveIntervalId) {\n return;\n }\n this.keepAliveIntervalId = setInterval(() => {\n void this.peers.map((peer) => this.ping(peer));\n }, this.config.keepAliveIntervalMs);\n }\n stopKeepAlive() {\n if (!this.keepAliveIntervalId) {\n return;\n }\n clearInterval(this.keepAliveIntervalId);\n this.keepAliveIntervalId = undefined;\n }\n startPeerConnectionListener() {\n this.libp2p.addEventListener(\"peer:connect\", this.onPeerConnected);\n this.libp2p.addEventListener(\"peer:disconnect\", this.onPeerDisconnected);\n }\n stopPeerConnectionListener() {\n this.libp2p.removeEventListener(\"peer:connect\", this.onPeerConnected);\n this.libp2p.removeEventListener(\"peer:disconnect\", this.onPeerDisconnected);\n }\n async onPeerConnected(_event) {\n // TODO(weboko): use config.numOfUsedPeers here\n if (this.peers.length > 0) {\n return;\n }\n this.peers = await this.peerManager.getPeers();\n await Promise.all(this.peers.map((peer) => this.subscribe(peer)));\n }\n async onPeerDisconnected(event) {\n const hasNotBeenUsed = !this.peers.find((p) => p.id.equals(event.detail));\n if (hasNotBeenUsed) {\n return;\n }\n this.peers = await this.peerManager.getPeers();\n await Promise.all(this.peers.map((peer) => this.subscribe(peer)));\n }\n async subscribe(_peer) {\n let peer = _peer;\n for (let i = 0; i < MAX_SUBSCRIBE_ATTEMPTS; i++) {\n if (!peer) {\n return;\n }\n const response = await this.filter.subscribe(this.pubsubTopic, peer, Array.from(this.activeSubscriptions.keys()));\n if (response.success) {\n return;\n }\n peer = await this.peerManager.requestRenew(peer.id);\n }\n }\n async ping(peer, renewOnFirstFail = false) {\n const peerIdStr = peer.id.toString();\n const response = await this.filter.ping(peer);\n if (response.failure && renewOnFirstFail) {\n const newPeer = await this.peerManager.requestRenew(peer.id);\n await this.subscribe(newPeer);\n return;\n }\n if (response.failure) {\n const prev = this.pingFailedAttempts.get(peerIdStr) || 0;\n this.pingFailedAttempts.set(peerIdStr, prev + 1);\n }\n if (response.success) {\n this.pingFailedAttempts.set(peerIdStr, 0);\n }\n const madeAttempts = this.pingFailedAttempts.get(peerIdStr) || 0;\n if (madeAttempts >= this.config.pingsBeforePeerRenewed) {\n const newPeer = await this.peerManager.requestRenew(peer.id);\n await this.subscribe(newPeer);\n }\n }\n}\n//# sourceMappingURL=subscription_monitor.js.map","import { createDecoder } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { groupByContentTopic, Logger } from \"@waku/utils\";\nimport { SubscriptionMonitor } from \"./subscription_monitor.js\";\nconst log = new Logger(\"sdk:filter:subscription\");\nexport class Subscription {\n pubsubTopic;\n protocol;\n config;\n monitor;\n subscriptionCallbacks = new Map();\n constructor(pubsubTopic, protocol, connectionManager, peerManager, libp2p, config, lightPush) {\n this.pubsubTopic = pubsubTopic;\n this.protocol = protocol;\n this.config = config;\n this.pubsubTopic = pubsubTopic;\n this.monitor = new SubscriptionMonitor({\n pubsubTopic,\n config,\n libp2p,\n connectionManager,\n filter: protocol,\n peerManager,\n lightPush,\n activeSubscriptions: this.subscriptionCallbacks\n });\n }\n async subscribe(decoders, callback) {\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n // check that all decoders are configured for the same pubsub topic as this subscription\n for (const decoder of decodersArray) {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n return {\n failures: [\n {\n error: ProtocolError.TOPIC_DECODER_MISMATCH\n }\n ],\n successes: []\n };\n }\n }\n if (this.config.enableLightPushFilterCheck) {\n decodersArray.push(createDecoder(this.monitor.reservedContentTopic, this.pubsubTopic));\n }\n const decodersGroupedByCT = groupByContentTopic(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n const peers = await this.monitor.getPeers();\n const promises = peers.map(async (peer) => {\n return this.protocol.subscribe(this.pubsubTopic, peer, contentTopics);\n });\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"subscribe\");\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n };\n // don't handle case of internal content topic\n if (contentTopic === this.monitor.reservedContentTopic) {\n return;\n }\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n this.monitor.start();\n return finalResult;\n }\n async unsubscribe(contentTopics) {\n const peers = await this.monitor.getPeers();\n const promises = peers.map(async (peer) => {\n const response = await this.protocol.unsubscribe(this.pubsubTopic, peer, contentTopics);\n contentTopics.forEach((contentTopic) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n return response;\n });\n const results = await Promise.allSettled(promises);\n const finalResult = this.handleResult(results, \"unsubscribe\");\n if (this.subscriptionCallbacks.size === 0) {\n this.monitor.stop();\n }\n return finalResult;\n }\n async ping() {\n const peers = await this.monitor.getPeers();\n const promises = peers.map((peer) => this.protocol.ping(peer));\n const results = await Promise.allSettled(promises);\n return this.handleResult(results, \"ping\");\n }\n async unsubscribeAll() {\n const peers = await this.monitor.getPeers();\n const promises = peers.map(async (peer) => this.protocol.unsubscribeAll(this.pubsubTopic, peer));\n const results = await Promise.allSettled(promises);\n this.subscriptionCallbacks.clear();\n const finalResult = this.handleResult(results, \"unsubscribeAll\");\n this.monitor.stop();\n return finalResult;\n }\n async processIncomingMessage(message, peerIdStr) {\n const received = this.monitor.notifyMessageReceived(peerIdStr, message);\n if (received) {\n log.info(\"Message already received, skipping\");\n return;\n }\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\"Processing message with content topic \", contentTopic, \" on pubsub topic \", this.pubsubTopic);\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n handleResult(results, type) {\n const result = { failures: [], successes: [] };\n for (const promiseResult of results) {\n if (promiseResult.status === \"rejected\") {\n log.error(`Failed to resolve ${type} promise successfully: `, promiseResult.reason);\n result.failures.push({ error: ProtocolError.GENERIC_FAIL });\n }\n else {\n const coreResult = promiseResult.value;\n if (coreResult.failure) {\n result.failures.push(coreResult.failure);\n }\n else {\n result.successes.push(coreResult.success);\n }\n }\n }\n return result;\n }\n}\nasync function pushMessage(subscriptionCallback, pubsubTopic, message) {\n const { decoders, callback } = subscriptionCallback;\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n try {\n const decodePromises = decoders.map((dec) => dec\n .fromProtoObj(pubsubTopic, message)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\")));\n const decodedMessage = await Promise.any(decodePromises);\n await callback(decodedMessage);\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n//# sourceMappingURL=subscription.js.map","export const DEFAULT_KEEP_ALIVE = 60_000;\nexport const DEFAULT_MAX_PINGS = 3;\nexport const DEFAULT_LIGHT_PUSH_FILTER_CHECK = false;\n//# sourceMappingURL=constants.js.map","import { FilterCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, groupByContentTopic, Logger, shardInfoToPubsubTopics, toAsyncIterator } from \"@waku/utils\";\nimport { Subscription } from \"./subscription.js\";\nimport { buildConfig } from \"./utils.js\";\nconst log = new Logger(\"sdk:filter\");\nclass Filter {\n connectionManager;\n libp2p;\n peerManager;\n lightPush;\n protocol;\n config;\n activeSubscriptions = new Map();\n constructor(connectionManager, libp2p, peerManager, lightPush, config) {\n this.connectionManager = connectionManager;\n this.libp2p = libp2p;\n this.peerManager = peerManager;\n this.lightPush = lightPush;\n this.config = buildConfig(config);\n this.protocol = new FilterCore(async (pubsubTopic, wakuMessage, peerIdStr) => {\n const subscription = this.getActiveSubscription(pubsubTopic);\n if (!subscription) {\n log.error(`No subscription locally registered for topic ${pubsubTopic}`);\n return;\n }\n await subscription.processIncomingMessage(wakuMessage, peerIdStr);\n }, connectionManager.pubsubTopics, libp2p);\n this.activeSubscriptions = new Map();\n }\n /**\n * Opens a subscription with the Filter protocol using the provided decoders and callback.\n * This method combines the functionality of creating a subscription and subscribing to it.\n *\n * @param {IDecoder | IDecoder[]} decoders - A single decoder or an array of decoders to use for decoding messages.\n * @param {Callback} callback - The callback function to be invoked with decoded messages.\n *\n * @returns {Promise} A promise that resolves to an object containing:\n * - subscription: The created subscription object if successful, or null if failed.\n * - error: A ProtocolError if the subscription creation failed, or null if successful.\n * - results: An object containing arrays of failures and successes from the subscription process.\n * Only present if the subscription was created successfully.\n *\n * @throws {Error} If there's an unexpected error during the subscription process.\n *\n * @remarks\n * This method attempts to create a subscription using the pubsub topic derived from the provided decoders,\n * then tries to subscribe using the created subscription. The return value should be interpreted as follows:\n * - If `subscription` is null and `error` is non-null, a critical error occurred and the subscription failed completely.\n * - If `subscription` is non-null and `error` is null, the subscription was created successfully.\n * In this case, check the `results` field for detailed information about successes and failures during the subscription process.\n * - Even if the subscription was created successfully, there might be some failures in the results.\n *\n * @example\n * ```typescript\n * const {subscription, error, results} = await waku.filter.subscribe(decoders, callback);\n * if (!subscription || error) {\n * console.error(\"Failed to create subscription:\", error);\n * }\n * console.log(\"Subscription created successfully\");\n * if (results.failures.length > 0) {\n * console.warn(\"Some errors occurred during subscription:\", results.failures);\n * }\n * console.log(\"Successful subscriptions:\", results.successes);\n *\n * ```\n */\n async subscribe(decoders, callback) {\n const uniquePubsubTopics = this.getUniquePubsubTopics(decoders);\n if (uniquePubsubTopics.length !== 1) {\n return {\n subscription: null,\n error: ProtocolError.INVALID_DECODER_TOPICS,\n results: null\n };\n }\n const pubsubTopic = uniquePubsubTopics[0];\n const { subscription, error } = await this.createSubscription(pubsubTopic);\n if (error) {\n return {\n subscription: null,\n error: error,\n results: null\n };\n }\n const { failures, successes } = await subscription.subscribe(decoders, callback);\n return {\n subscription,\n error: null,\n results: {\n failures: failures,\n successes: successes\n }\n };\n }\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(pubsubTopicShardInfo) {\n const pubsubTopic = typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : shardInfoToPubsubTopics(pubsubTopicShardInfo)?.[0];\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n const peers = await this.peerManager.getPeers();\n if (peers.length === 0) {\n return {\n error: ProtocolError.NO_PEER_AVAILABLE,\n subscription: null\n };\n }\n log.info(`Creating filter subscription with ${peers.length} peers: `, peers.map((peer) => peer.id.toString()));\n const subscription = this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(pubsubTopic, new Subscription(pubsubTopic, this.protocol, this.connectionManager, this.peerManager, this.libp2p, this.config, this.lightPush));\n return {\n error: null,\n subscription\n };\n }\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribeWithUnsubscribe(decoders, callback) {\n const uniquePubsubTopics = this.getUniquePubsubTopics(decoders);\n if (uniquePubsubTopics.length === 0) {\n throw Error(\"Failed to subscribe: no pubsubTopic found on decoders provided.\");\n }\n if (uniquePubsubTopics.length > 1) {\n throw Error(\"Failed to subscribe: all decoders should have the same pubsub topic. Use createSubscription to be more agile.\");\n }\n const { subscription, error } = await this.createSubscription(uniquePubsubTopics[0]);\n if (error) {\n throw Error(`Failed to create subscription: ${error}`);\n }\n await subscription.subscribe(decoders, callback);\n const contentTopics = Array.from(groupByContentTopic(Array.isArray(decoders) ? decoders : [decoders]).keys());\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n toSubscriptionIterator(decoders) {\n return toAsyncIterator(this, decoders);\n }\n getActiveSubscription(pubsubTopic) {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n setActiveSubscription(pubsubTopic, subscription) {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n getUniquePubsubTopics(decoders) {\n if (!Array.isArray(decoders)) {\n return [decoders.pubsubTopic];\n }\n if (decoders.length === 0) {\n return [];\n }\n const pubsubTopics = new Set(decoders.map((d) => d.pubsubTopic));\n return [...pubsubTopics];\n }\n}\nexport function wakuFilter(connectionManager, peerManager, lightPush, config) {\n return (libp2p) => new Filter(connectionManager, libp2p, peerManager, lightPush, config);\n}\n//# sourceMappingURL=index.js.map","import * as C from \"./constants.js\";\nexport const buildConfig = (config) => {\n return {\n keepAliveIntervalMs: config?.keepAliveIntervalMs || C.DEFAULT_KEEP_ALIVE,\n pingsBeforePeerRenewed: config?.pingsBeforePeerRenewed || C.DEFAULT_MAX_PINGS,\n enableLightPushFilterCheck: config?.enableLightPushFilterCheck || C.DEFAULT_LIGHT_PUSH_FILTER_CHECK\n };\n};\n//# sourceMappingURL=utils.js.map","import { getHealthManager, LightPushCore } from \"@waku/core\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { ensurePubsubTopicIsConfigured, Logger } from \"@waku/utils\";\nconst log = new Logger(\"sdk:light-push\");\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_SEND_OPTIONS = {\n autoRetry: false,\n maxAttempts: DEFAULT_MAX_ATTEMPTS\n};\nexport class LightPush {\n peerManager;\n protocol;\n constructor(connectionManager, peerManager, libp2p) {\n this.peerManager = peerManager;\n this.protocol = new LightPushCore(connectionManager.pubsubTopics, libp2p);\n }\n async send(encoder, message, options = DEFAULT_SEND_OPTIONS) {\n const successes = [];\n const failures = [];\n const { pubsubTopic } = encoder;\n try {\n ensurePubsubTopicIsConfigured(pubsubTopic, this.protocol.pubsubTopics);\n }\n catch (error) {\n log.error(\"Failed to send waku light push: pubsub topic not configured\");\n return {\n successes,\n failures: [\n {\n error: ProtocolError.TOPIC_NOT_CONFIGURED\n }\n ]\n };\n }\n const peers = await this.peerManager.getPeers();\n if (peers.length === 0) {\n return {\n successes,\n failures: [\n {\n error: ProtocolError.NO_PEER_AVAILABLE\n }\n ]\n };\n }\n const results = await Promise.allSettled(peers.map((peer) => this.protocol.send(encoder, message, peer)));\n for (const result of results) {\n if (result.status !== \"fulfilled\") {\n log.error(\"Failed unexpectedly while sending:\", result.reason);\n failures.push({ error: ProtocolError.GENERIC_FAIL });\n continue;\n }\n const { failure, success } = result.value;\n if (success) {\n successes.push(success);\n continue;\n }\n if (failure) {\n failures.push(failure);\n if (options?.autoRetry) {\n void this.attemptRetries((peer) => this.protocol.send(encoder, message, peer), options.maxAttempts);\n }\n }\n }\n getHealthManager().updateProtocolHealth(this.protocol.multicodec, successes.length);\n return {\n successes,\n failures\n };\n }\n async attemptRetries(fn, maxAttempts) {\n maxAttempts = maxAttempts || DEFAULT_MAX_ATTEMPTS;\n const connectedPeers = await this.peerManager.getPeers();\n if (connectedPeers.length === 0) {\n log.warn(\"Cannot retry with no connected peers.\");\n return;\n }\n for (let i = 0; i < maxAttempts; i++) {\n const peer = connectedPeers[i % connectedPeers.length]; // always present as we checked for the length already\n const response = await fn(peer);\n if (response.success) {\n return;\n }\n log.info(`Attempted retry for peer:${peer.id} failed with:${response?.failure?.error}`);\n }\n }\n}\nexport function wakuLightPush(connectionManager, peerManager) {\n return (libp2p) => new LightPush(connectionManager, peerManager, libp2p);\n}\n//# sourceMappingURL=light_push.js.map","import { Logger } from \"@waku/utils\";\nconst log = new Logger(\"peer-manager\");\nconst DEFAULT_NUM_PEERS_TO_USE = 2;\nconst CONNECTION_LOCK_TAG = \"peer-manager-lock\";\nexport class PeerManager {\n numPeersToUse;\n libp2p;\n constructor(params) {\n this.onConnected = this.onConnected.bind(this);\n this.onDisconnected = this.onDisconnected.bind(this);\n this.numPeersToUse =\n params?.config?.numPeersToUse || DEFAULT_NUM_PEERS_TO_USE;\n this.libp2p = params.libp2p;\n this.startConnectionListener();\n }\n stop() {\n this.stopConnectionListener();\n }\n async getPeers() {\n return Promise.all(this.getLockedConnections().map((c) => this.mapConnectionToPeer(c)));\n }\n async requestRenew(peerId) {\n const lockedConnections = this.getLockedConnections();\n const neededPeers = this.numPeersToUse - lockedConnections.length;\n if (neededPeers === 0) {\n return;\n }\n const result = await Promise.all(this.getUnlockedConnections()\n .filter((c) => !c.remotePeer.equals(peerId))\n .slice(0, neededPeers)\n .map((c) => this.lockConnection(c))\n .map((c) => this.mapConnectionToPeer(c)));\n const newPeer = result[0];\n if (!newPeer) {\n log.warn(`requestRenew: Couldn't renew peer ${peerId.toString()}.`);\n return;\n }\n log.info(`requestRenew: Renewed peer ${peerId.toString()} to ${newPeer.id.toString()}`);\n return newPeer;\n }\n startConnectionListener() {\n this.libp2p.addEventListener(\"peer:connect\", this.onConnected);\n this.libp2p.addEventListener(\"peer:disconnect\", this.onDisconnected);\n }\n stopConnectionListener() {\n this.libp2p.removeEventListener(\"peer:connect\", this.onConnected);\n this.libp2p.removeEventListener(\"peer:disconnect\", this.onDisconnected);\n }\n onConnected(event) {\n const peerId = event.detail;\n void this.lockPeerIfNeeded(peerId);\n }\n onDisconnected(event) {\n const peerId = event.detail;\n void this.requestRenew(peerId);\n }\n async lockPeerIfNeeded(peerId) {\n const lockedConnections = this.getLockedConnections();\n const neededPeers = this.numPeersToUse - lockedConnections.length;\n if (neededPeers === 0) {\n return;\n }\n this.getUnlockedConnections()\n .filter((c) => c.remotePeer.equals(peerId))\n .map((c) => this.lockConnection(c));\n }\n getLockedConnections() {\n return this.libp2p\n .getConnections()\n .filter((c) => c.status === \"open\" && this.isConnectionLocked(c));\n }\n getUnlockedConnections() {\n return this.libp2p\n .getConnections()\n .filter((c) => c.status === \"open\" && !this.isConnectionLocked(c));\n }\n lockConnection(c) {\n log.info(`requestRenew: Locking connection for peerId=${c.remotePeer.toString()}`);\n c.tags.push(CONNECTION_LOCK_TAG);\n return c;\n }\n isConnectionLocked(c) {\n return c.tags.includes(CONNECTION_LOCK_TAG);\n }\n async mapConnectionToPeer(c) {\n const peerId = c.remotePeer;\n return this.libp2p.peerStore.get(peerId);\n }\n}\n//# sourceMappingURL=peer_manager.js.map","import { StoreCore } from \"@waku/core\";\nimport { messageHash } from \"@waku/message-hash\";\nimport { ensurePubsubTopicIsConfigured, isDefined, Logger } from \"@waku/utils\";\nconst log = new Logger(\"waku:store:sdk\");\n/**\n * StoreSDK is an implementation of the IStoreSDK interface.\n * It provides methods to interact with the Waku Store protocol.\n */\nexport class Store {\n peerManager;\n protocol;\n constructor(connectionManager, libp2p, peerManager) {\n this.peerManager = peerManager;\n this.protocol = new StoreCore(connectionManager.pubsubTopics, libp2p);\n }\n /**\n * Queries the Waku Store for historical messages using the provided decoders and options.\n * Returns an asynchronous generator that yields promises of decoded messages.\n *\n * @param decoders - An array of message decoders.\n * @param options - Optional query parameters.\n * @returns An asynchronous generator of promises of decoded messages.\n * @throws If no peers are available to query or if an error occurs during the query.\n */\n async *queryGenerator(decoders, options) {\n const { pubsubTopic, contentTopics, decodersAsMap } = this.validateDecodersAndPubsubTopic(decoders);\n const queryOpts = {\n pubsubTopic,\n contentTopics,\n includeData: true,\n paginationForward: true,\n ...options\n };\n const peers = await this.peerManager.getPeers();\n const peer = peers[0];\n if (!peer) {\n log.error(\"No peers available to query\");\n throw new Error(\"No peers available to query\");\n }\n log.info(`Querying store with options: ${JSON.stringify(options)}`);\n const responseGenerator = this.protocol.queryPerPage(queryOpts, decodersAsMap, peer);\n for await (const messages of responseGenerator) {\n yield messages;\n }\n }\n /**\n * Queries the Waku Store for historical messages and processes them with the provided callback in order.\n *\n * @param decoders - An array of message decoders.\n * @param callback - A callback function to process each decoded message.\n * @param options - Optional query parameters.\n * @returns A promise that resolves when the query and message processing are completed.\n */\n async queryWithOrderedCallback(decoders, callback, options) {\n log.info(\"Querying store with ordered callback\");\n for await (const promises of this.queryGenerator(decoders, options)) {\n if (await this.processMessages(promises, callback))\n break;\n }\n }\n /**\n * Queries the Waku Store for historical messages and processes them with the provided callback using promises.\n *\n * @param decoders - An array of message decoders.\n * @param callback - A callback function to process each promise of a decoded message.\n * @param options - Optional query parameters.\n * @returns A promise that resolves when the query and message processing are completed.\n */\n async queryWithPromiseCallback(decoders, callback, options) {\n log.info(\"Querying store with promise callback\");\n let abort = false;\n for await (const page of this.queryGenerator(decoders, options)) {\n const _promises = page.map(async (msgPromise) => {\n if (abort)\n return;\n abort = Boolean(await callback(msgPromise));\n });\n await Promise.all(_promises);\n if (abort)\n break;\n }\n }\n /**\n * Processes messages based on the provided callback and options.\n *\n * @param messages - An array of promises of decoded messages.\n * @param callback - A callback function to process each decoded message.\n * @returns A promise that resolves to a boolean indicating whether the processing should abort.\n * @private\n */\n async processMessages(messages, callback) {\n let abort = false;\n const messagesOrUndef = await Promise.all(messages);\n const processedMessages = messagesOrUndef.filter(isDefined);\n await Promise.all(processedMessages.map(async (msg) => {\n if (msg && !abort) {\n abort = Boolean(await callback(msg));\n }\n }));\n return abort;\n }\n /**\n * Creates a cursor based on the provided decoded message.\n *\n * @param message - The decoded message.\n * @returns A StoreCursor representing the message.\n */\n createCursor(message) {\n return messageHash(message.pubsubTopic, message);\n }\n /**\n * Validates the provided decoders and pubsub topic.\n *\n * @param decoders - An array of message decoders.\n * @returns An object containing the pubsub topic, content topics, and a map of decoders.\n * @throws If no decoders are provided, if multiple pubsub topics are provided, or if no decoders are found for the pubsub topic.\n * @private\n */\n validateDecodersAndPubsubTopic(decoders) {\n if (decoders.length === 0) {\n log.error(\"No decoders provided\");\n throw new Error(\"No decoders provided\");\n }\n const uniquePubsubTopicsInQuery = Array.from(new Set(decoders.map((decoder) => decoder.pubsubTopic)));\n if (uniquePubsubTopicsInQuery.length > 1) {\n log.error(\"API does not support querying multiple pubsub topics at once\");\n throw new Error(\"API does not support querying multiple pubsub topics at once\");\n }\n const pubsubTopicForQuery = uniquePubsubTopicsInQuery[0];\n ensurePubsubTopicIsConfigured(pubsubTopicForQuery, this.protocol.pubsubTopics);\n const decodersAsMap = new Map();\n decoders.forEach((dec) => {\n if (decodersAsMap.has(dec.contentTopic)) {\n log.error(\"API does not support different decoder per content topic\");\n throw new Error(\"API does not support different decoder per content topic\");\n }\n decodersAsMap.set(dec.contentTopic, dec);\n });\n const contentTopics = decoders\n .filter((decoder) => decoder.pubsubTopic === pubsubTopicForQuery)\n .map((dec) => dec.contentTopic);\n if (contentTopics.length === 0) {\n log.error(`No decoders found for topic ${pubsubTopicForQuery}`);\n throw new Error(\"No decoders found for topic \" + pubsubTopicForQuery);\n }\n return {\n pubsubTopic: pubsubTopicForQuery,\n contentTopics,\n decodersAsMap\n };\n }\n}\n/**\n * Factory function to create an instance of the StoreSDK.\n *\n * @param init - Partial options for protocol creation.\n * @returns A function that takes a Libp2p instance and returns a StoreSDK instance.\n */\nexport function wakuStore(connectionManager, peerManager) {\n return (libp2p) => {\n return new Store(connectionManager, libp2p, peerManager);\n };\n}\n//# sourceMappingURL=index.js.map","import { FilterCodecs, LightPushCodec, StoreCodec } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nconst log = new Logger(\"wait-for-remote-peer\");\n/**\n * @deprecated Since @waku/sdk 0.29.0. Will be removed from 0.31.0\n *\n * Wait for a remote peer to be ready given the passed protocols.\n * Must be used after attempting to connect to nodes, using\n * {@link @waku/sdk!WakuNode.dial} or a bootstrap method with\n * {@link @waku/sdk!createLightNode}.\n *\n * If the passed protocols is a GossipSub protocol, then it resolves only once\n * a peer is in a mesh, to help ensure that other peers will send and receive\n * message to us.\n *\n * @param waku The Waku Node\n * @param protocols The protocols that need to be enabled by remote peers.\n * @param timeoutMs A timeout value in milliseconds..\n *\n * @returns A promise that **resolves** if all desired protocols are fulfilled by\n * remote nodes, **rejects** if the timeoutMs is reached.\n * @throws If passing a protocol that is not mounted\n * @default Wait for remote peers with protocols enabled locally and no time out is applied.\n */\nexport async function waitForRemotePeer(waku, protocols, timeoutMs) {\n // if no protocols or empty array passed - try to derive from mounted\n protocols = protocols?.length ? protocols : getEnabledProtocols(waku);\n const connections = waku.libp2p.getConnections();\n if (!waku.isStarted()) {\n throw Error(\"Waku node is not started\");\n }\n if (connections.length > 0 && !protocols.includes(Protocols.Relay)) {\n const success = await waitForMetadata(waku, protocols);\n if (success) {\n return;\n }\n }\n const promises = [];\n if (protocols.includes(Protocols.Relay)) {\n if (!waku.relay) {\n throw Error(\"Cannot wait for Relay peer: protocol not mounted\");\n }\n promises.push(waku.relay.waitForPeers());\n }\n if (protocols.includes(Protocols.Store)) {\n if (!waku.store) {\n throw Error(\"Cannot wait for Store peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(StoreCodec, waku.libp2p));\n }\n if (protocols.includes(Protocols.LightPush)) {\n if (!waku.lightPush) {\n throw Error(\"Cannot wait for LightPush peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(LightPushCodec, waku.libp2p));\n }\n if (protocols.includes(Protocols.Filter)) {\n if (!waku.filter) {\n throw new Error(\"Cannot wait for Filter peer: protocol not mounted\");\n }\n promises.push(waitForConnectedPeer(FilterCodecs.SUBSCRIBE, waku.libp2p));\n }\n if (timeoutMs) {\n await rejectOnTimeout(Promise.all(promises), timeoutMs, \"Timed out waiting for a remote peer.\");\n }\n else {\n await Promise.all(promises);\n }\n}\n/**\n * Wait for a peer with the given protocol to be connected.\n * If sharding is enabled on the node, it will also wait for the peer to be confirmed by the metadata service.\n */\nasync function waitForConnectedPeer(codec, libp2p) {\n log.info(`Waiting for ${codec} peer.`);\n await new Promise((resolve) => {\n const cb = (async (evt) => {\n if (evt.detail?.protocols?.includes(codec)) {\n const metadataService = libp2p.services.metadata;\n if (!metadataService) {\n libp2p.removeEventListener(\"peer:identify\", cb);\n resolve();\n return;\n }\n try {\n await metadataService.confirmOrAttemptHandshake(evt.detail.peerId);\n libp2p.removeEventListener(\"peer:identify\", cb);\n resolve();\n }\n catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\") {\n log.error(\"Connection closed. Some peers can be on different shard.\");\n }\n log.error(`Error waiting for metadata: ${e}`);\n }\n }\n });\n libp2p.addEventListener(\"peer:identify\", cb);\n });\n}\n/**\n * Waits for the metadata from the remote peer.\n */\nasync function waitForMetadata(waku, protocols) {\n const connectedPeers = waku.libp2p.getPeers();\n const metadataService = waku.libp2p.services.metadata;\n const enabledCodes = mapProtocolsToCodecs(protocols);\n if (!connectedPeers.length || !metadataService) {\n log.info(`Skipping waitForMetadata due to missing connections:${connectedPeers.length} or metadataService:${!!metadataService}`);\n return false;\n }\n for (const peerId of connectedPeers) {\n try {\n const peer = await waku.libp2p.peerStore.get(peerId);\n const hasSomeCodes = peer.protocols.some((c) => enabledCodes.has(c));\n if (hasSomeCodes) {\n const response = await metadataService.confirmOrAttemptHandshake(peerId);\n if (!response.error) {\n peer.protocols.forEach((c) => {\n if (enabledCodes.has(c)) {\n enabledCodes.set(c, true);\n }\n });\n const confirmedAllCodecs = Array.from(enabledCodes.values()).every((v) => v);\n if (confirmedAllCodecs) {\n return true;\n }\n }\n }\n }\n catch (e) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (e.code === \"ERR_CONNECTION_BEING_CLOSED\") {\n log.error(\"Connection closed. Some peers can be on different shard.\");\n }\n log.error(`Error while iterating through peers: ${e}`);\n continue;\n }\n }\n return false;\n}\nconst awaitTimeout = (ms, rejectReason) => new Promise((_resolve, reject) => setTimeout(() => reject(Error(rejectReason)), ms));\nasync function rejectOnTimeout(promise, timeoutMs, rejectReason) {\n await Promise.race([promise, awaitTimeout(timeoutMs, rejectReason)]);\n}\nfunction getEnabledProtocols(waku) {\n const protocols = [];\n if (waku.relay) {\n protocols.push(Protocols.Relay);\n }\n if (waku.filter) {\n protocols.push(Protocols.Filter);\n }\n if (waku.store) {\n protocols.push(Protocols.Store);\n }\n if (waku.lightPush) {\n protocols.push(Protocols.LightPush);\n }\n return protocols;\n}\nfunction mapProtocolsToCodecs(protocols) {\n const codecs = new Map();\n const protocolToCodec = {\n [Protocols.Filter]: FilterCodecs.SUBSCRIBE,\n [Protocols.LightPush]: LightPushCodec,\n [Protocols.Store]: StoreCodec\n };\n for (const protocol of protocols) {\n if (protocolToCodec[protocol]) {\n codecs.set(protocolToCodec[protocol], false);\n }\n }\n return codecs;\n}\n//# sourceMappingURL=wait_for_remote_peer.js.map","import { isPeerId } from \"@libp2p/interface\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { ConnectionManager, getHealthManager } from \"@waku/core\";\nimport { Protocols } from \"@waku/interfaces\";\nimport { Logger } from \"@waku/utils\";\nimport { wakuFilter } from \"../protocols/filter/index.js\";\nimport { wakuLightPush } from \"../protocols/light_push/index.js\";\nimport { PeerManager } from \"../protocols/peer_manager.js\";\nimport { wakuStore } from \"../protocols/store/index.js\";\nimport { waitForRemotePeer } from \"./wait_for_remote_peer.js\";\nconst log = new Logger(\"waku\");\nexport class WakuNode {\n pubsubTopics;\n libp2p;\n relay;\n store;\n filter;\n lightPush;\n connectionManager;\n health;\n peerManager;\n constructor(pubsubTopics, options, libp2p, protocolsEnabled, relay) {\n this.pubsubTopics = pubsubTopics;\n this.relay = relay;\n this.libp2p = libp2p;\n protocolsEnabled = {\n filter: false,\n lightpush: false,\n store: false,\n ...protocolsEnabled\n };\n const peerId = this.libp2p.peerId.toString();\n this.connectionManager = new ConnectionManager({\n libp2p,\n relay: this.relay,\n pubsubTopics: this.pubsubTopics,\n config: options?.connectionManager\n });\n this.peerManager = new PeerManager({\n libp2p,\n config: {\n numPeersToUse: options.numPeersToUse\n }\n });\n this.health = getHealthManager();\n if (protocolsEnabled.store) {\n const store = wakuStore(this.connectionManager, this.peerManager);\n this.store = store(libp2p);\n }\n if (protocolsEnabled.lightpush) {\n const lightPush = wakuLightPush(this.connectionManager, this.peerManager);\n this.lightPush = lightPush(libp2p);\n }\n if (protocolsEnabled.filter) {\n const filter = wakuFilter(this.connectionManager, this.peerManager, this.lightPush, options.filter);\n this.filter = filter(libp2p);\n }\n log.info(\"Waku node created\", peerId, `relay: ${!!this.relay}, store: ${!!this.store}, light push: ${!!this\n .lightPush}, filter: ${!!this.filter}`);\n }\n get peerId() {\n return this.libp2p.peerId;\n }\n get protocols() {\n return this.libp2p.getProtocols();\n }\n async dial(peer, protocols) {\n const _protocols = protocols ?? [];\n const peerId = this.mapToPeerIdOrMultiaddr(peer);\n if (typeof protocols === \"undefined\") {\n this.relay && _protocols.push(Protocols.Relay);\n this.store && _protocols.push(Protocols.Store);\n this.filter && _protocols.push(Protocols.Filter);\n this.lightPush && _protocols.push(Protocols.LightPush);\n }\n const codecs = [];\n if (_protocols.includes(Protocols.Relay)) {\n if (this.relay) {\n this.relay.gossipSub.multicodecs.forEach((codec) => codecs.push(codec));\n }\n else {\n log.error(\"Relay codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Store)) {\n if (this.store) {\n codecs.push(this.store.protocol.multicodec);\n }\n else {\n log.error(\"Store codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.LightPush)) {\n if (this.lightPush) {\n codecs.push(this.lightPush.protocol.multicodec);\n }\n else {\n log.error(\"Light Push codec not included in dial codec: protocol not mounted locally\");\n }\n }\n if (_protocols.includes(Protocols.Filter)) {\n if (this.filter) {\n codecs.push(this.filter.protocol.multicodec);\n }\n else {\n log.error(\"Filter codec not included in dial codec: protocol not mounted locally\");\n }\n }\n log.info(`Dialing to ${peerId.toString()} with protocols ${_protocols}`);\n return this.libp2p.dialProtocol(peerId, codecs);\n }\n async start() {\n await this.libp2p.start();\n }\n async stop() {\n this.peerManager.stop();\n this.connectionManager.stop();\n await this.libp2p.stop();\n }\n async getPeers() {\n return this.connectionManager.getConnectedPeers();\n }\n async waitForPeers(protocols, timeoutMs) {\n return waitForRemotePeer(this, protocols, timeoutMs);\n }\n isStarted() {\n return this.libp2p.status == \"started\";\n }\n isConnected() {\n return this.connectionManager.isConnected();\n }\n mapToPeerIdOrMultiaddr(peerId) {\n return isPeerId(peerId) ? peerId : multiaddr(peerId);\n }\n}\n//# sourceMappingURL=waku.js.map","/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nexport class AbortError extends Error {\n static name = 'AbortError';\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n }\n}\n/**\n * Thrown when a remote Peer ID does not match the expected one\n */\nexport class UnexpectedPeerError extends Error {\n static name = 'UnexpectedPeerError';\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n }\n}\n/**\n * Thrown when a crypto exchange fails\n */\nexport class InvalidCryptoExchangeError extends Error {\n static name = 'InvalidCryptoExchangeError';\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n }\n}\n/**\n * Thrown when invalid parameters are passed to a function or method call\n */\nexport class InvalidParametersError extends Error {\n static name = 'InvalidParametersError';\n constructor(message = 'Invalid parameters') {\n super(message);\n this.name = 'InvalidParametersError';\n }\n}\n/**\n * Thrown when a public key is invalid\n */\nexport class InvalidPublicKeyError extends Error {\n static name = 'InvalidPublicKeyError';\n constructor(message = 'Invalid public key') {\n super(message);\n this.name = 'InvalidPublicKeyError';\n }\n}\n/**\n * Thrown when a private key is invalid\n */\nexport class InvalidPrivateKeyError extends Error {\n static name = 'InvalidPrivateKeyError';\n constructor(message = 'Invalid private key') {\n super(message);\n this.name = 'InvalidPrivateKeyError';\n }\n}\n/**\n * Thrown when a operation is unsupported\n */\nexport class UnsupportedOperationError extends Error {\n static name = 'UnsupportedOperationError';\n constructor(message = 'Unsupported operation') {\n super(message);\n this.name = 'UnsupportedOperationError';\n }\n}\n/**\n * Thrown when a connection is closing\n */\nexport class ConnectionClosingError extends Error {\n static name = 'ConnectionClosingError';\n constructor(message = 'The connection is closing') {\n super(message);\n this.name = 'ConnectionClosingError';\n }\n}\n/**\n * Thrown when a connection is closed\n */\nexport class ConnectionClosedError extends Error {\n static name = 'ConnectionClosedError';\n constructor(message = 'The connection is closed') {\n super(message);\n this.name = 'ConnectionClosedError';\n }\n}\n/**\n * Thrown when a connection fails\n */\nexport class ConnectionFailedError extends Error {\n static name = 'ConnectionFailedError';\n constructor(message = 'Connection failed') {\n super(message);\n this.name = 'ConnectionFailedError';\n }\n}\n/**\n * Thrown when the muxer is closed and an attempt to open a stream occurs\n */\nexport class MuxerClosedError extends Error {\n static name = 'MuxerClosedError';\n constructor(message = 'The muxer is closed') {\n super(message);\n this.name = 'MuxerClosedError';\n }\n}\n/**\n * Thrown when a protocol stream is reset by the remote muxer\n */\nexport class StreamResetError extends Error {\n static name = 'StreamResetError';\n constructor(message = 'The stream has been reset') {\n super(message);\n this.name = 'StreamResetError';\n }\n}\n/**\n * Thrown when a stream is in an invalid state\n */\nexport class StreamStateError extends Error {\n static name = 'StreamStateError';\n constructor(message = 'The stream is in an invalid state') {\n super(message);\n this.name = 'StreamStateError';\n }\n}\n/**\n * Thrown when a value could not be found\n */\nexport class NotFoundError extends Error {\n static name = 'NotFoundError';\n constructor(message = 'Not found') {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n/**\n * Thrown when an invalid peer ID is encountered\n */\nexport class InvalidPeerIdError extends Error {\n static name = 'InvalidPeerIdError';\n constructor(message = 'Invalid PeerID') {\n super(message);\n this.name = 'InvalidPeerIdError';\n }\n}\n/**\n * Thrown when an invalid multiaddr is encountered\n */\nexport class InvalidMultiaddrError extends Error {\n static name = 'InvalidMultiaddrError';\n constructor(message = 'Invalid multiaddr') {\n super(message);\n this.name = 'InvalidMultiaddrError';\n }\n}\n/**\n * Thrown when an invalid CID is encountered\n */\nexport class InvalidCIDError extends Error {\n static name = 'InvalidCIDError';\n constructor(message = 'Invalid CID') {\n super(message);\n this.name = 'InvalidCIDError';\n }\n}\n/**\n * Thrown when an invalid multihash is encountered\n */\nexport class InvalidMultihashError extends Error {\n static name = 'InvalidMultihashError';\n constructor(message = 'Invalid Multihash') {\n super(message);\n this.name = 'InvalidMultihashError';\n }\n}\n/**\n * Thrown when a protocol is not supported\n */\nexport class UnsupportedProtocolError extends Error {\n static name = 'UnsupportedProtocolError';\n constructor(message = 'Unsupported protocol error') {\n super(message);\n this.name = 'UnsupportedProtocolError';\n }\n}\n/**\n * An invalid or malformed message was encountered during a protocol exchange\n */\nexport class InvalidMessageError extends Error {\n static name = 'InvalidMessageError';\n constructor(message = 'Invalid message') {\n super(message);\n this.name = 'InvalidMessageError';\n }\n}\n/**\n * Thrown when a remote peer sends a structurally valid message that does not\n * comply with the protocol\n */\nexport class ProtocolError extends Error {\n static name = 'ProtocolError';\n constructor(message = 'Protocol error') {\n super(message);\n this.name = 'ProtocolError';\n }\n}\n/**\n * Throw when an operation times out\n */\nexport class TimeoutError extends Error {\n static name = 'TimeoutError';\n constructor(message = 'Timed out') {\n super(message);\n this.name = 'TimeoutError';\n }\n}\n/**\n * Thrown when a startable component is interacted with but it has not been\n * started yet\n */\nexport class NotStartedError extends Error {\n static name = 'NotStartedError';\n constructor(message = 'Not started') {\n super(message);\n this.name = 'NotStartedError';\n }\n}\n/**\n * Thrown when a component is started that has already been started\n */\nexport class AlreadyStartedError extends Error {\n static name = 'AlreadyStartedError';\n constructor(message = 'Already started') {\n super(message);\n this.name = 'AlreadyStartedError';\n }\n}\n/**\n * Thrown when dialing an address failed\n */\nexport class DialError extends Error {\n static name = 'DialError';\n constructor(message = 'Dial error') {\n super(message);\n this.name = 'DialError';\n }\n}\n/**\n * Thrown when listening on an address failed\n */\nexport class ListenError extends Error {\n static name = 'ListenError';\n constructor(message = 'Listen error') {\n super(message);\n this.name = 'ListenError';\n }\n}\n/**\n * This error is thrown when a limited connection is encountered, i.e. if the\n * user tried to open a stream on a connection for a protocol that is not\n * configured to run over limited connections.\n */\nexport class LimitedConnectionError extends Error {\n static name = 'LimitedConnectionError';\n constructor(message = 'Limited connection') {\n super(message);\n this.name = 'LimitedConnectionError';\n }\n}\n/**\n * This error is thrown where there are too many inbound protocols streams open\n */\nexport class TooManyInboundProtocolStreamsError extends Error {\n static name = 'TooManyInboundProtocolStreamsError';\n constructor(message = 'Too many inbound protocol streams') {\n super(message);\n this.name = 'TooManyInboundProtocolStreamsError';\n }\n}\n/**\n * This error is thrown where there are too many outbound protocols streams open\n */\nexport class TooManyOutboundProtocolStreamsError extends Error {\n static name = 'TooManyOutboundProtocolStreamsError';\n constructor(message = 'Too many outbound protocol streams') {\n super(message);\n this.name = 'TooManyOutboundProtocolStreamsError';\n }\n}\n/**\n * Thrown when and attempt to operate on an unsupported key was made\n */\nexport class UnsupportedKeyTypeError extends Error {\n static name = 'UnsupportedKeyTypeError';\n constructor(message = 'Unsupported key type') {\n super(message);\n this.name = 'UnsupportedKeyTypeError';\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n */\nimport { HashMD } from './_md.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexport class SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nexport class SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nexport class SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\n/** SHA2-512 hash function. */\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\n/** SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\n/** SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks. */\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\n/** SHA2-384 hash function. */\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nexport function abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @todo use field version && remove\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n)\n throw new Error('invalid modulus');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000)\n throw new Error('Cannot find square root: likely non-prime P');\n }\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n/**\n * Legendre symbol.\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nexport function FpLegendre(order) {\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { nLength, validateField } from './modular.js';\nimport { bitLen, validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, bits) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\nfunction getW(P) {\n return pointWindowSizes.get(P) || 1;\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF(c, bits) {\n return {\n constTimeNegate,\n hasPrecomputes(elm) {\n return getW(elm) !== 1;\n },\n // non-const time multiplication ladder\n unsafeLadder(elm, n, p = c.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n)\n break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0)\n continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0)\n curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n getPrecomputes(W, P, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n wNAFCached(P, n, transform) {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n wNAFCachedUnsafe(P, n, transform, prev) {\n const W = getW(P);\n if (W === 1)\n return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = BigInt((1 << windowSize) - 1);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { pippenger, validateBasic, wNAF, } from './curve.js';\nimport { Field, mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { abool, ensureBytes, memoized } from './utils.js';\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nexport function twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n abool('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n ut.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = memoized((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = memoized((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n ut.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n const n = scalar;\n ut.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.is0() || n === _1n)\n return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n abool('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n ut.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(ut.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = Fp.BYTES;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = ensureBytes('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n ut.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n publicKey = ensureBytes('publicKey', publicKey, len);\n if (zip215 !== undefined)\n abool('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { aInRange, bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject, } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n validateObject(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => pow(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n) {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen) {\n let valid = '' + montgomeryBytes + ' or ' + fieldLen;\n throw new Error('invalid scalar, expected ' + valid + ' bytes, got ' + len);\n }\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { pippenger } from './abstract/curve.js';\nimport { twistedEdwards } from './abstract/edwards.js';\nimport { createHasher, expand_message_xmd, } from './abstract/hash-to-curve.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { bytesToHex, bytesToNumberLE, ensureBytes, equalBytes, numberToBytesLE, } from './abstract/utils.js';\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = /* @__PURE__ */ (() => Field(ED25519_P, undefined, true))();\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nexport const ed25519 = /* @__PURE__ */ (() => twistedEdwards(ed25519Defaults))();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(utf8ToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nexport const ed25519ctx = /* @__PURE__ */ (() => twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n}))();\nexport const ed25519ph = /* @__PURE__ */ (() => twistedEdwards(Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: sha512,\n})))();\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nexport const x25519 = /* @__PURE__ */ (() => montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => createHasher(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n static msm(points, scalars) {\n const Fn = Field(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return pippenger(RistPoint, Fn, points, scalars);\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n toHex() {\n return bytesToHex(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map","import { ed25519 as ed } from '@noble/curves/ed25519';\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\nexport { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength };\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = ed.utils.randomPrivateKey();\n const publicKey = ed.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nexport function generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = ed.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nexport function hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return ed.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nexport function hashAndVerify(publicKey, sig, msg) {\n return ed.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=index.browser.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport {} from 'multiformats/hashes/digest';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { publicKeyToProtobuf } from '../index.js';\nimport { ensureEd25519Key } from './utils.js';\nimport * as crypto from './index.js';\nexport class Ed25519PublicKey {\n type = 'Ed25519';\n raw;\n constructor(key) {\n this.raw = ensureEd25519Key(key, crypto.publicKeyLength);\n }\n toMultihash() {\n return identity.digest(publicKeyToProtobuf(this));\n }\n toCID() {\n return CID.createV1(114, this.toMultihash());\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig) {\n return crypto.hashAndVerify(this.raw, sig, data);\n }\n}\nexport class Ed25519PrivateKey {\n type = 'Ed25519';\n raw;\n publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this.raw = ensureEd25519Key(key, crypto.privateKeyLength);\n this.publicKey = new Ed25519PublicKey(publicKey);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message) {\n return crypto.hashAndSign(this.raw, message);\n }\n}\n//# sourceMappingURL=ed25519.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { Ed25519PublicKey as Ed25519PublicKeyClass, Ed25519PrivateKey as Ed25519PrivateKeyClass } from './ed25519.js';\nimport * as crypto from './index.js';\nexport function unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > crypto.privateKeyLength) {\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength + crypto.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.privateKeyLength, bytes.length);\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureEd25519Key(bytes, crypto.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, crypto.privateKeyLength);\n const publicKeyBytes = bytes.subarray(crypto.publicKeyLength);\n return new Ed25519PrivateKeyClass(privateKeyBytes, publicKeyBytes);\n}\nexport function unmarshalEd25519PublicKey(bytes) {\n bytes = ensureEd25519Key(bytes, crypto.publicKeyLength);\n return new Ed25519PublicKeyClass(bytes);\n}\nexport async function generateEd25519KeyPair() {\n const { privateKey, publicKey } = crypto.generateKey();\n return new Ed25519PrivateKeyClass(privateKey, publicKey);\n}\nexport async function generateEd25519KeyPairFromSeed(seed) {\n const { privateKey, publicKey } = crypto.generateKeyFromSeed(seed);\n return new Ed25519PrivateKeyClass(privateKey, publicKey);\n}\nexport function ensureEd25519Key(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new InvalidParametersError(`Key must be a Uint8Array of length ${length}, got ${key.length}`);\n }\n return key;\n}\n//# sourceMappingURL=utils.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, enumeration, message } from 'protons-runtime';\nexport var KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"secp256k1\"] = \"secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"secp256k1\"] = 2] = \"secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return enumeration(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nexport var PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader);\n break;\n }\n case 2: {\n obj.Data = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return encodeMessage(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf, opts) => {\n return decodeMessage(buf, PublicKey.codec(), opts);\n };\n})(PublicKey || (PublicKey = {}));\nexport var PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.Type = KeyType.codec().decode(reader);\n break;\n }\n case 2: {\n obj.Data = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return encodeMessage(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf, opts) => {\n return decodeMessage(buf, PrivateKey.codec(), opts);\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map","/*!\n Copyright (c) Peculiar Ventures, LLC\n*/\n\nfunction getUTCDate(date) {\r\n return new Date(date.getTime() + (date.getTimezoneOffset() * 60000));\r\n}\r\nfunction getParametersValue(parameters, name, defaultValue) {\r\n var _a;\r\n if ((parameters instanceof Object) === false) {\r\n return defaultValue;\r\n }\r\n return (_a = parameters[name]) !== null && _a !== void 0 ? _a : defaultValue;\r\n}\r\nfunction bufferToHexCodes(inputBuffer, inputOffset = 0, inputLength = (inputBuffer.byteLength - inputOffset), insertSpace = false) {\r\n let result = \"\";\r\n for (const item of (new Uint8Array(inputBuffer, inputOffset, inputLength))) {\r\n const str = item.toString(16).toUpperCase();\r\n if (str.length === 1) {\r\n result += \"0\";\r\n }\r\n result += str;\r\n if (insertSpace) {\r\n result += \" \";\r\n }\r\n }\r\n return result.trim();\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof ArrayBuffer)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be \\\"ArrayBuffer\\\"\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\r\nfunction utilFromBase(inputBuffer, inputBase) {\r\n let result = 0;\r\n if (inputBuffer.length === 1) {\r\n return inputBuffer[0];\r\n }\r\n for (let i = (inputBuffer.length - 1); i >= 0; i--) {\r\n result += inputBuffer[(inputBuffer.length - 1) - i] * Math.pow(2, inputBase * i);\r\n }\r\n return result;\r\n}\r\nfunction utilToBase(value, base, reserved = (-1)) {\r\n const internalReserved = reserved;\r\n let internalValue = value;\r\n let result = 0;\r\n let biggest = Math.pow(2, base);\r\n for (let i = 1; i < 8; i++) {\r\n if (value < biggest) {\r\n let retBuf;\r\n if (internalReserved < 0) {\r\n retBuf = new ArrayBuffer(i);\r\n result = i;\r\n }\r\n else {\r\n if (internalReserved < i) {\r\n return (new ArrayBuffer(0));\r\n }\r\n retBuf = new ArrayBuffer(internalReserved);\r\n result = internalReserved;\r\n }\r\n const retView = new Uint8Array(retBuf);\r\n for (let j = (i - 1); j >= 0; j--) {\r\n const basis = Math.pow(2, j * base);\r\n retView[result - j - 1] = Math.floor(internalValue / basis);\r\n internalValue -= (retView[result - j - 1]) * basis;\r\n }\r\n return retBuf;\r\n }\r\n biggest *= Math.pow(2, base);\r\n }\r\n return new ArrayBuffer(0);\r\n}\r\nfunction utilConcatBuf(...buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const buffer of buffers) {\r\n outputLength += buffer.byteLength;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const buffer of buffers) {\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retBuf;\r\n}\r\nfunction utilConcatView(...views) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (const view of views) {\r\n outputLength += view.length;\r\n }\r\n const retBuf = new ArrayBuffer(outputLength);\r\n const retView = new Uint8Array(retBuf);\r\n for (const view of views) {\r\n retView.set(view, prevLength);\r\n prevLength += view.length;\r\n }\r\n return retView;\r\n}\r\nfunction utilDecodeTC() {\r\n const buf = new Uint8Array(this.valueHex);\r\n if (this.valueHex.byteLength >= 2) {\r\n const condition1 = (buf[0] === 0xFF) && (buf[1] & 0x80);\r\n const condition2 = (buf[0] === 0x00) && ((buf[1] & 0x80) === 0x00);\r\n if (condition1 || condition2) {\r\n this.warnings.push(\"Needlessly long format\");\r\n }\r\n }\r\n const bigIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const bigIntView = new Uint8Array(bigIntBuffer);\r\n for (let i = 0; i < this.valueHex.byteLength; i++) {\r\n bigIntView[i] = 0;\r\n }\r\n bigIntView[0] = (buf[0] & 0x80);\r\n const bigInt = utilFromBase(bigIntView, 8);\r\n const smallIntBuffer = new ArrayBuffer(this.valueHex.byteLength);\r\n const smallIntView = new Uint8Array(smallIntBuffer);\r\n for (let j = 0; j < this.valueHex.byteLength; j++) {\r\n smallIntView[j] = buf[j];\r\n }\r\n smallIntView[0] &= 0x7F;\r\n const smallInt = utilFromBase(smallIntView, 8);\r\n return (smallInt - bigInt);\r\n}\r\nfunction utilEncodeTC(value) {\r\n const modValue = (value < 0) ? (value * (-1)) : value;\r\n let bigInt = 128;\r\n for (let i = 1; i < 8; i++) {\r\n if (modValue <= bigInt) {\r\n if (value < 0) {\r\n const smallInt = bigInt - modValue;\r\n const retBuf = utilToBase(smallInt, 8, i);\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] |= 0x80;\r\n return retBuf;\r\n }\r\n let retBuf = utilToBase(modValue, 8, i);\r\n let retView = new Uint8Array(retBuf);\r\n if (retView[0] & 0x80) {\r\n const tempBuf = retBuf.slice(0);\r\n const tempView = new Uint8Array(tempBuf);\r\n retBuf = new ArrayBuffer(retBuf.byteLength + 1);\r\n retView = new Uint8Array(retBuf);\r\n for (let k = 0; k < tempBuf.byteLength; k++) {\r\n retView[k + 1] = tempView[k];\r\n }\r\n retView[0] = 0x00;\r\n }\r\n return retBuf;\r\n }\r\n bigInt *= Math.pow(2, 8);\r\n }\r\n return (new ArrayBuffer(0));\r\n}\r\nfunction isEqualBuffer(inputBuffer1, inputBuffer2) {\r\n if (inputBuffer1.byteLength !== inputBuffer2.byteLength) {\r\n return false;\r\n }\r\n const view1 = new Uint8Array(inputBuffer1);\r\n const view2 = new Uint8Array(inputBuffer2);\r\n for (let i = 0; i < view1.length; i++) {\r\n if (view1[i] !== view2[i]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\nfunction padNumber(inputNumber, fullLength) {\r\n const str = inputNumber.toString(10);\r\n if (fullLength < str.length) {\r\n return \"\";\r\n }\r\n const dif = fullLength - str.length;\r\n const padding = new Array(dif);\r\n for (let i = 0; i < dif; i++) {\r\n padding[i] = \"0\";\r\n }\r\n const paddingString = padding.join(\"\");\r\n return paddingString.concat(str);\r\n}\r\nconst base64Template = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\nconst base64UrlTemplate = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=\";\r\nfunction toBase64(input, useUrlTemplate = false, skipPadding = false, skipLeadingZeros = false) {\r\n let i = 0;\r\n let flag1 = 0;\r\n let flag2 = 0;\r\n let output = \"\";\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n if (skipLeadingZeros) {\r\n let nonZeroPosition = 0;\r\n for (let i = 0; i < input.length; i++) {\r\n if (input.charCodeAt(i) !== 0) {\r\n nonZeroPosition = i;\r\n break;\r\n }\r\n }\r\n input = input.slice(nonZeroPosition);\r\n }\r\n while (i < input.length) {\r\n const chr1 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag1 = 1;\r\n }\r\n const chr2 = input.charCodeAt(i++);\r\n if (i >= input.length) {\r\n flag2 = 1;\r\n }\r\n const chr3 = input.charCodeAt(i++);\r\n const enc1 = chr1 >> 2;\r\n const enc2 = ((chr1 & 0x03) << 4) | (chr2 >> 4);\r\n let enc3 = ((chr2 & 0x0F) << 2) | (chr3 >> 6);\r\n let enc4 = chr3 & 0x3F;\r\n if (flag1 === 1) {\r\n enc3 = enc4 = 64;\r\n }\r\n else {\r\n if (flag2 === 1) {\r\n enc4 = 64;\r\n }\r\n }\r\n if (skipPadding) {\r\n if (enc3 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}`;\r\n }\r\n else {\r\n if (enc4 === 64) {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}`;\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n }\r\n else {\r\n output += `${template.charAt(enc1)}${template.charAt(enc2)}${template.charAt(enc3)}${template.charAt(enc4)}`;\r\n }\r\n }\r\n return output;\r\n}\r\nfunction fromBase64(input, useUrlTemplate = false, cutTailZeros = false) {\r\n const template = (useUrlTemplate) ? base64UrlTemplate : base64Template;\r\n function indexOf(toSearch) {\r\n for (let i = 0; i < 64; i++) {\r\n if (template.charAt(i) === toSearch)\r\n return i;\r\n }\r\n return 64;\r\n }\r\n function test(incoming) {\r\n return ((incoming === 64) ? 0x00 : incoming);\r\n }\r\n let i = 0;\r\n let output = \"\";\r\n while (i < input.length) {\r\n const enc1 = indexOf(input.charAt(i++));\r\n const enc2 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc3 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const enc4 = (i >= input.length) ? 0x00 : indexOf(input.charAt(i++));\r\n const chr1 = (test(enc1) << 2) | (test(enc2) >> 4);\r\n const chr2 = ((test(enc2) & 0x0F) << 4) | (test(enc3) >> 2);\r\n const chr3 = ((test(enc3) & 0x03) << 6) | test(enc4);\r\n output += String.fromCharCode(chr1);\r\n if (enc3 !== 64) {\r\n output += String.fromCharCode(chr2);\r\n }\r\n if (enc4 !== 64) {\r\n output += String.fromCharCode(chr3);\r\n }\r\n }\r\n if (cutTailZeros) {\r\n const outputLength = output.length;\r\n let nonZeroStart = (-1);\r\n for (let i = (outputLength - 1); i >= 0; i--) {\r\n if (output.charCodeAt(i) !== 0) {\r\n nonZeroStart = i;\r\n break;\r\n }\r\n }\r\n if (nonZeroStart !== (-1)) {\r\n output = output.slice(0, nonZeroStart + 1);\r\n }\r\n else {\r\n output = \"\";\r\n }\r\n }\r\n return output;\r\n}\r\nfunction arrayBufferToString(buffer) {\r\n let resultString = \"\";\r\n const view = new Uint8Array(buffer);\r\n for (const element of view) {\r\n resultString += String.fromCharCode(element);\r\n }\r\n return resultString;\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n const stringLength = str.length;\r\n const resultBuffer = new ArrayBuffer(stringLength);\r\n const resultView = new Uint8Array(resultBuffer);\r\n for (let i = 0; i < stringLength; i++) {\r\n resultView[i] = str.charCodeAt(i);\r\n }\r\n return resultBuffer;\r\n}\r\nconst log2 = Math.log(2);\r\nfunction nearestPowerOf2(length) {\r\n const base = (Math.log(length) / log2);\r\n const floor = Math.floor(base);\r\n const round = Math.round(base);\r\n return ((floor === round) ? floor : round);\r\n}\r\nfunction clearProps(object, propsArray) {\r\n for (const prop of propsArray) {\r\n delete object[prop];\r\n }\r\n}\n\nexport { arrayBufferToString, bufferToHexCodes, checkBufferParams, clearProps, fromBase64, getParametersValue, getUTCDate, isEqualBuffer, nearestPowerOf2, padNumber, stringToArrayBuffer, toBase64, utilConcatBuf, utilConcatView, utilDecodeTC, utilEncodeTC, utilFromBase, utilToBase };\n","/*!\n * Copyright (c) 2014, GMO GlobalSign\n * Copyright (c) 2015-2022, Peculiar Ventures\n * All rights reserved.\n * \n * Author 2014-2019, Yury Strozhevsky\n * \n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * \n * * Redistributions in binary form must reproduce the above copyright notice, this\n * list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * \n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n */\n\nimport * as pvtsutils from 'pvtsutils';\nimport * as pvutils from 'pvutils';\n\nfunction assertBigInt() {\r\n if (typeof BigInt === \"undefined\") {\r\n throw new Error(\"BigInt is not defined. Your environment doesn't implement BigInt.\");\r\n }\r\n}\r\nfunction concat(buffers) {\r\n let outputLength = 0;\r\n let prevLength = 0;\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n outputLength += buffer.byteLength;\r\n }\r\n const retView = new Uint8Array(outputLength);\r\n for (let i = 0; i < buffers.length; i++) {\r\n const buffer = buffers[i];\r\n retView.set(new Uint8Array(buffer), prevLength);\r\n prevLength += buffer.byteLength;\r\n }\r\n return retView.buffer;\r\n}\r\nfunction checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength) {\r\n if (!(inputBuffer instanceof Uint8Array)) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer must be 'Uint8Array'\";\r\n return false;\r\n }\r\n if (!inputBuffer.byteLength) {\r\n baseBlock.error = \"Wrong parameter: inputBuffer has zero length\";\r\n return false;\r\n }\r\n if (inputOffset < 0) {\r\n baseBlock.error = \"Wrong parameter: inputOffset less than zero\";\r\n return false;\r\n }\r\n if (inputLength < 0) {\r\n baseBlock.error = \"Wrong parameter: inputLength less than zero\";\r\n return false;\r\n }\r\n if ((inputBuffer.byteLength - inputOffset - inputLength) < 0) {\r\n baseBlock.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return false;\r\n }\r\n return true;\r\n}\n\nclass ViewWriter {\r\n constructor() {\r\n this.items = [];\r\n }\r\n write(buf) {\r\n this.items.push(buf);\r\n }\r\n final() {\r\n return concat(this.items);\r\n }\r\n}\n\nconst powers2 = [new Uint8Array([1])];\r\nconst digitsString = \"0123456789\";\r\nconst NAME = \"name\";\r\nconst VALUE_HEX_VIEW = \"valueHexView\";\r\nconst IS_HEX_ONLY = \"isHexOnly\";\r\nconst ID_BLOCK = \"idBlock\";\r\nconst TAG_CLASS = \"tagClass\";\r\nconst TAG_NUMBER = \"tagNumber\";\r\nconst IS_CONSTRUCTED = \"isConstructed\";\r\nconst FROM_BER = \"fromBER\";\r\nconst TO_BER = \"toBER\";\r\nconst LOCAL = \"local\";\r\nconst EMPTY_STRING = \"\";\r\nconst EMPTY_BUFFER = new ArrayBuffer(0);\r\nconst EMPTY_VIEW = new Uint8Array(0);\r\nconst END_OF_CONTENT_NAME = \"EndOfContent\";\r\nconst OCTET_STRING_NAME = \"OCTET STRING\";\r\nconst BIT_STRING_NAME = \"BIT STRING\";\n\nfunction HexBlock(BaseClass) {\r\n var _a;\r\n return _a = class Some extends BaseClass {\r\n constructor(...args) {\r\n var _a;\r\n super(...args);\r\n const params = args[0] || {};\r\n this.isHexOnly = (_a = params.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = params.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(params.valueHex) : EMPTY_VIEW;\r\n }\r\n get valueHex() {\r\n return this.valueHexView.slice().buffer;\r\n }\r\n set valueHex(value) {\r\n this.valueHexView = new Uint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const endLength = inputOffset + inputLength;\r\n this.valueHexView = view.subarray(inputOffset, endLength);\r\n if (!this.valueHexView.length) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n this.blockLength = inputLength;\r\n return endLength;\r\n }\r\n toBER(sizeOnly = false) {\r\n if (!this.isHexOnly) {\r\n this.error = \"Flag 'isHexOnly' is not set, abort\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength);\r\n }\r\n return (this.valueHexView.byteLength === this.valueHexView.buffer.byteLength)\r\n ? this.valueHexView.buffer\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isHexOnly: this.isHexOnly,\r\n valueHex: pvtsutils.Convert.ToHex(this.valueHexView),\r\n };\r\n }\r\n },\r\n _a.NAME = \"hexBlock\",\r\n _a;\r\n}\n\nclass LocalBaseBlock {\r\n constructor({ blockLength = 0, error = EMPTY_STRING, warnings = [], valueBeforeDecode = EMPTY_VIEW, } = {}) {\r\n this.blockLength = blockLength;\r\n this.error = error;\r\n this.warnings = warnings;\r\n this.valueBeforeDecodeView = pvtsutils.BufferSourceConverter.toUint8Array(valueBeforeDecode);\r\n }\r\n static blockName() {\r\n return this.NAME;\r\n }\r\n get valueBeforeDecode() {\r\n return this.valueBeforeDecodeView.slice().buffer;\r\n }\r\n set valueBeforeDecode(value) {\r\n this.valueBeforeDecodeView = new Uint8Array(value);\r\n }\r\n toJSON() {\r\n return {\r\n blockName: this.constructor.NAME,\r\n blockLength: this.blockLength,\r\n error: this.error,\r\n warnings: this.warnings,\r\n valueBeforeDecode: pvtsutils.Convert.ToHex(this.valueBeforeDecodeView),\r\n };\r\n }\r\n}\r\nLocalBaseBlock.NAME = \"baseBlock\";\n\nclass ValueBlock extends LocalBaseBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n toBER(sizeOnly, writer) {\r\n throw TypeError(\"User need to make a specific function in a class which extends 'ValueBlock'\");\r\n }\r\n}\r\nValueBlock.NAME = \"valueBlock\";\n\nclass LocalIdentificationBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ idBlock = {}, } = {}) {\r\n var _a, _b, _c, _d;\r\n super();\r\n if (idBlock) {\r\n this.isHexOnly = (_a = idBlock.isHexOnly) !== null && _a !== void 0 ? _a : false;\r\n this.valueHexView = idBlock.valueHex ? pvtsutils.BufferSourceConverter.toUint8Array(idBlock.valueHex) : EMPTY_VIEW;\r\n this.tagClass = (_b = idBlock.tagClass) !== null && _b !== void 0 ? _b : -1;\r\n this.tagNumber = (_c = idBlock.tagNumber) !== null && _c !== void 0 ? _c : -1;\r\n this.isConstructed = (_d = idBlock.isConstructed) !== null && _d !== void 0 ? _d : false;\r\n }\r\n else {\r\n this.tagClass = -1;\r\n this.tagNumber = -1;\r\n this.isConstructed = false;\r\n }\r\n }\r\n toBER(sizeOnly = false) {\r\n let firstOctet = 0;\r\n switch (this.tagClass) {\r\n case 1:\r\n firstOctet |= 0x00;\r\n break;\r\n case 2:\r\n firstOctet |= 0x40;\r\n break;\r\n case 3:\r\n firstOctet |= 0x80;\r\n break;\r\n case 4:\r\n firstOctet |= 0xC0;\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return EMPTY_BUFFER;\r\n }\r\n if (this.isConstructed)\r\n firstOctet |= 0x20;\r\n if (this.tagNumber < 31 && !this.isHexOnly) {\r\n const retView = new Uint8Array(1);\r\n if (!sizeOnly) {\r\n let number = this.tagNumber;\r\n number &= 0x1F;\r\n firstOctet |= number;\r\n retView[0] = firstOctet;\r\n }\r\n return retView.buffer;\r\n }\r\n if (!this.isHexOnly) {\r\n const encodedBuf = pvutils.utilToBase(this.tagNumber, 7);\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const size = encodedBuf.byteLength;\r\n const retView = new Uint8Array(size + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n for (let i = 0; i < (size - 1); i++)\r\n retView[i + 1] = encodedView[i] | 0x80;\r\n retView[size] = encodedView[size - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.byteLength + 1);\r\n retView[0] = (firstOctet | 0x1F);\r\n if (!sizeOnly) {\r\n const curView = this.valueHexView;\r\n for (let i = 0; i < (curView.length - 1); i++)\r\n retView[i + 1] = curView[i] | 0x80;\r\n retView[this.valueHexView.byteLength] = curView[curView.length - 1];\r\n }\r\n return retView.buffer;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n const tagClassMask = intBuffer[0] & 0xC0;\r\n switch (tagClassMask) {\r\n case 0x00:\r\n this.tagClass = (1);\r\n break;\r\n case 0x40:\r\n this.tagClass = (2);\r\n break;\r\n case 0x80:\r\n this.tagClass = (3);\r\n break;\r\n case 0xC0:\r\n this.tagClass = (4);\r\n break;\r\n default:\r\n this.error = \"Unknown tag class\";\r\n return -1;\r\n }\r\n this.isConstructed = (intBuffer[0] & 0x20) === 0x20;\r\n this.isHexOnly = false;\r\n const tagNumberMask = intBuffer[0] & 0x1F;\r\n if (tagNumberMask !== 0x1F) {\r\n this.tagNumber = (tagNumberMask);\r\n this.blockLength = 1;\r\n }\r\n else {\r\n let count = 1;\r\n let intTagNumberBuffer = this.valueHexView = new Uint8Array(255);\r\n let tagNumberBufferMaxLength = 255;\r\n while (intBuffer[count] & 0x80) {\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n count++;\r\n if (count >= intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (count === tagNumberBufferMaxLength) {\r\n tagNumberBufferMaxLength += 255;\r\n const tempBufferView = new Uint8Array(tagNumberBufferMaxLength);\r\n for (let i = 0; i < intTagNumberBuffer.length; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(tagNumberBufferMaxLength);\r\n }\r\n }\r\n this.blockLength = (count + 1);\r\n intTagNumberBuffer[count - 1] = intBuffer[count] & 0x7F;\r\n const tempBufferView = new Uint8Array(count);\r\n for (let i = 0; i < count; i++)\r\n tempBufferView[i] = intTagNumberBuffer[i];\r\n intTagNumberBuffer = this.valueHexView = new Uint8Array(count);\r\n intTagNumberBuffer.set(tempBufferView);\r\n if (this.blockLength <= 9)\r\n this.tagNumber = pvutils.utilFromBase(intTagNumberBuffer, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Tag too long, represented as hex-coded\");\r\n }\r\n }\r\n if (((this.tagClass === 1)) &&\r\n (this.isConstructed)) {\r\n switch (this.tagNumber) {\r\n case 1:\r\n case 2:\r\n case 5:\r\n case 6:\r\n case 9:\r\n case 13:\r\n case 14:\r\n case 23:\r\n case 24:\r\n case 31:\r\n case 32:\r\n case 33:\r\n case 34:\r\n this.error = \"Constructed encoding used for primitive type\";\r\n return -1;\r\n }\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n tagClass: this.tagClass,\r\n tagNumber: this.tagNumber,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalIdentificationBlock.NAME = \"identificationBlock\";\n\nclass LocalLengthBlock extends LocalBaseBlock {\r\n constructor({ lenBlock = {}, } = {}) {\r\n var _a, _b, _c;\r\n super();\r\n this.isIndefiniteForm = (_a = lenBlock.isIndefiniteForm) !== null && _a !== void 0 ? _a : false;\r\n this.longFormUsed = (_b = lenBlock.longFormUsed) !== null && _b !== void 0 ? _b : false;\r\n this.length = (_c = lenBlock.length) !== null && _c !== void 0 ? _c : 0;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (intBuffer.length === 0) {\r\n this.error = \"Zero buffer length\";\r\n return -1;\r\n }\r\n if (intBuffer[0] === 0xFF) {\r\n this.error = \"Length block 0xFF is reserved by standard\";\r\n return -1;\r\n }\r\n this.isIndefiniteForm = intBuffer[0] === 0x80;\r\n if (this.isIndefiniteForm) {\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n this.longFormUsed = !!(intBuffer[0] & 0x80);\r\n if (this.longFormUsed === false) {\r\n this.length = (intBuffer[0]);\r\n this.blockLength = 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n const count = intBuffer[0] & 0x7F;\r\n if (count > 8) {\r\n this.error = \"Too big integer\";\r\n return -1;\r\n }\r\n if ((count + 1) > intBuffer.length) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n const lenOffset = inputOffset + 1;\r\n const lengthBufferView = view.subarray(lenOffset, lenOffset + count);\r\n if (lengthBufferView[count - 1] === 0x00)\r\n this.warnings.push(\"Needlessly long encoded length\");\r\n this.length = pvutils.utilFromBase(lengthBufferView, 8);\r\n if (this.longFormUsed && (this.length <= 127))\r\n this.warnings.push(\"Unnecessary usage of long length form\");\r\n this.blockLength = count + 1;\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly = false) {\r\n let retBuf;\r\n let retView;\r\n if (this.length > 127)\r\n this.longFormUsed = true;\r\n if (this.isIndefiniteForm) {\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = 0x80;\r\n }\r\n return retBuf;\r\n }\r\n if (this.longFormUsed) {\r\n const encodedBuf = pvutils.utilToBase(this.length, 8);\r\n if (encodedBuf.byteLength > 127) {\r\n this.error = \"Too big length\";\r\n return (EMPTY_BUFFER);\r\n }\r\n retBuf = new ArrayBuffer(encodedBuf.byteLength + 1);\r\n if (sizeOnly)\r\n return retBuf;\r\n const encodedView = new Uint8Array(encodedBuf);\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = encodedBuf.byteLength | 0x80;\r\n for (let i = 0; i < encodedBuf.byteLength; i++)\r\n retView[i + 1] = encodedView[i];\r\n return retBuf;\r\n }\r\n retBuf = new ArrayBuffer(1);\r\n if (sizeOnly === false) {\r\n retView = new Uint8Array(retBuf);\r\n retView[0] = this.length;\r\n }\r\n return retBuf;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n longFormUsed: this.longFormUsed,\r\n length: this.length,\r\n };\r\n }\r\n}\r\nLocalLengthBlock.NAME = \"lengthBlock\";\n\nconst typeStore = {};\n\nclass BaseBlock extends LocalBaseBlock {\r\n constructor({ name = EMPTY_STRING, optional = false, primitiveSchema, ...parameters } = {}, valueBlockType) {\r\n super(parameters);\r\n this.name = name;\r\n this.optional = optional;\r\n if (primitiveSchema) {\r\n this.primitiveSchema = primitiveSchema;\r\n }\r\n this.idBlock = new LocalIdentificationBlock(parameters);\r\n this.lenBlock = new LocalLengthBlock(parameters);\r\n this.valueBlock = valueBlockType ? new valueBlockType(parameters) : new ValueBlock(parameters);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n if (!writer) {\r\n prepareIndefiniteForm(this);\r\n }\r\n const idBlockBuf = this.idBlock.toBER(sizeOnly);\r\n _writer.write(idBlockBuf);\r\n if (this.lenBlock.isIndefiniteForm) {\r\n _writer.write(new Uint8Array([0x80]).buffer);\r\n this.valueBlock.toBER(sizeOnly, _writer);\r\n _writer.write(new ArrayBuffer(2));\r\n }\r\n else {\r\n const valueBlockBuf = this.valueBlock.toBER(sizeOnly);\r\n this.lenBlock.length = valueBlockBuf.byteLength;\r\n const lenBlockBuf = this.lenBlock.toBER(sizeOnly);\r\n _writer.write(lenBlockBuf);\r\n _writer.write(valueBlockBuf);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n idBlock: this.idBlock.toJSON(),\r\n lenBlock: this.lenBlock.toJSON(),\r\n valueBlock: this.valueBlock.toJSON(),\r\n name: this.name,\r\n optional: this.optional,\r\n };\r\n if (this.primitiveSchema)\r\n object.primitiveSchema = this.primitiveSchema.toJSON();\r\n return object;\r\n }\r\n toString(encoding = \"ascii\") {\r\n if (encoding === \"ascii\") {\r\n return this.onAsciiEncoding();\r\n }\r\n return pvtsutils.Convert.ToHex(this.toBER());\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`;\r\n }\r\n isEqual(other) {\r\n if (this === other) {\r\n return true;\r\n }\r\n if (!(other instanceof this.constructor)) {\r\n return false;\r\n }\r\n const thisRaw = this.toBER();\r\n const otherRaw = other.toBER();\r\n return pvutils.isEqualBuffer(thisRaw, otherRaw);\r\n }\r\n}\r\nBaseBlock.NAME = \"BaseBlock\";\r\nfunction prepareIndefiniteForm(baseBlock) {\r\n if (baseBlock instanceof typeStore.Constructed) {\r\n for (const value of baseBlock.valueBlock.value) {\r\n if (prepareIndefiniteForm(value)) {\r\n baseBlock.lenBlock.isIndefiniteForm = true;\r\n }\r\n }\r\n }\r\n return !!baseBlock.lenBlock.isIndefiniteForm;\r\n}\n\nclass BaseStringBlock extends BaseBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}, stringValueBlockType) {\r\n super(parameters, stringValueBlockType);\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n this.fromBuffer(this.valueBlock.valueHexView);\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : '${this.valueBlock.value}'`;\r\n }\r\n}\r\nBaseStringBlock.NAME = \"BaseStringBlock\";\n\nclass LocalPrimitiveValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ isHexOnly = true, ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = isHexOnly;\r\n }\r\n}\r\nLocalPrimitiveValueBlock.NAME = \"PrimitiveValueBlock\";\n\nvar _a$w;\r\nclass Primitive extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalPrimitiveValueBlock);\r\n this.idBlock.isConstructed = false;\r\n }\r\n}\r\n_a$w = Primitive;\r\n(() => {\r\n typeStore.Primitive = _a$w;\r\n})();\r\nPrimitive.NAME = \"PRIMITIVE\";\n\nfunction localChangeType(inputObject, newType) {\r\n if (inputObject instanceof newType) {\r\n return inputObject;\r\n }\r\n const newObject = new newType();\r\n newObject.idBlock = inputObject.idBlock;\r\n newObject.lenBlock = inputObject.lenBlock;\r\n newObject.warnings = inputObject.warnings;\r\n newObject.valueBeforeDecodeView = inputObject.valueBeforeDecodeView;\r\n return newObject;\r\n}\r\nfunction localFromBER(inputBuffer, inputOffset = 0, inputLength = inputBuffer.length) {\r\n const incomingOffset = inputOffset;\r\n let returnObject = new BaseBlock({}, ValueBlock);\r\n const baseBlock = new LocalBaseBlock();\r\n if (!checkBufferParams(baseBlock, inputBuffer, inputOffset, inputLength)) {\r\n returnObject.error = baseBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n const intBuffer = inputBuffer.subarray(inputOffset, inputOffset + inputLength);\r\n if (!intBuffer.length) {\r\n returnObject.error = \"Zero buffer length\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let resultOffset = returnObject.idBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.idBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.idBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.idBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.idBlock.blockLength;\r\n resultOffset = returnObject.lenBlock.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (returnObject.lenBlock.warnings.length) {\r\n returnObject.warnings.concat(returnObject.lenBlock.warnings);\r\n }\r\n if (resultOffset === -1) {\r\n returnObject.error = returnObject.lenBlock.error;\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n inputOffset = resultOffset;\r\n inputLength -= returnObject.lenBlock.blockLength;\r\n if (!returnObject.idBlock.isConstructed &&\r\n returnObject.lenBlock.isIndefiniteForm) {\r\n returnObject.error = \"Indefinite length form used for primitive encoding form\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n let newASN1Type = BaseBlock;\r\n switch (returnObject.idBlock.tagClass) {\r\n case 1:\r\n if ((returnObject.idBlock.tagNumber >= 37) &&\r\n (returnObject.idBlock.isHexOnly === false)) {\r\n returnObject.error = \"UNIVERSAL 37 and upper tags are reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n switch (returnObject.idBlock.tagNumber) {\r\n case 0:\r\n if ((returnObject.idBlock.isConstructed) &&\r\n (returnObject.lenBlock.length > 0)) {\r\n returnObject.error = \"Type [UNIVERSAL 0] is reserved\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n }\r\n newASN1Type = typeStore.EndOfContent;\r\n break;\r\n case 1:\r\n newASN1Type = typeStore.Boolean;\r\n break;\r\n case 2:\r\n newASN1Type = typeStore.Integer;\r\n break;\r\n case 3:\r\n newASN1Type = typeStore.BitString;\r\n break;\r\n case 4:\r\n newASN1Type = typeStore.OctetString;\r\n break;\r\n case 5:\r\n newASN1Type = typeStore.Null;\r\n break;\r\n case 6:\r\n newASN1Type = typeStore.ObjectIdentifier;\r\n break;\r\n case 10:\r\n newASN1Type = typeStore.Enumerated;\r\n break;\r\n case 12:\r\n newASN1Type = typeStore.Utf8String;\r\n break;\r\n case 13:\r\n newASN1Type = typeStore.RelativeObjectIdentifier;\r\n break;\r\n case 14:\r\n newASN1Type = typeStore.TIME;\r\n break;\r\n case 15:\r\n returnObject.error = \"[UNIVERSAL 15] is reserved by ASN.1 standard\";\r\n return {\r\n offset: -1,\r\n result: returnObject\r\n };\r\n case 16:\r\n newASN1Type = typeStore.Sequence;\r\n break;\r\n case 17:\r\n newASN1Type = typeStore.Set;\r\n break;\r\n case 18:\r\n newASN1Type = typeStore.NumericString;\r\n break;\r\n case 19:\r\n newASN1Type = typeStore.PrintableString;\r\n break;\r\n case 20:\r\n newASN1Type = typeStore.TeletexString;\r\n break;\r\n case 21:\r\n newASN1Type = typeStore.VideotexString;\r\n break;\r\n case 22:\r\n newASN1Type = typeStore.IA5String;\r\n break;\r\n case 23:\r\n newASN1Type = typeStore.UTCTime;\r\n break;\r\n case 24:\r\n newASN1Type = typeStore.GeneralizedTime;\r\n break;\r\n case 25:\r\n newASN1Type = typeStore.GraphicString;\r\n break;\r\n case 26:\r\n newASN1Type = typeStore.VisibleString;\r\n break;\r\n case 27:\r\n newASN1Type = typeStore.GeneralString;\r\n break;\r\n case 28:\r\n newASN1Type = typeStore.UniversalString;\r\n break;\r\n case 29:\r\n newASN1Type = typeStore.CharacterString;\r\n break;\r\n case 30:\r\n newASN1Type = typeStore.BmpString;\r\n break;\r\n case 31:\r\n newASN1Type = typeStore.DATE;\r\n break;\r\n case 32:\r\n newASN1Type = typeStore.TimeOfDay;\r\n break;\r\n case 33:\r\n newASN1Type = typeStore.DateTime;\r\n break;\r\n case 34:\r\n newASN1Type = typeStore.Duration;\r\n break;\r\n default: {\r\n const newObject = returnObject.idBlock.isConstructed\r\n ? new typeStore.Constructed()\r\n : new typeStore.Primitive();\r\n newObject.idBlock = returnObject.idBlock;\r\n newObject.lenBlock = returnObject.lenBlock;\r\n newObject.warnings = returnObject.warnings;\r\n returnObject = newObject;\r\n }\r\n }\r\n break;\r\n case 2:\r\n case 3:\r\n case 4:\r\n default: {\r\n newASN1Type = returnObject.idBlock.isConstructed\r\n ? typeStore.Constructed\r\n : typeStore.Primitive;\r\n }\r\n }\r\n returnObject = localChangeType(returnObject, newASN1Type);\r\n resultOffset = returnObject.fromBER(inputBuffer, inputOffset, returnObject.lenBlock.isIndefiniteForm ? inputLength : returnObject.lenBlock.length);\r\n returnObject.valueBeforeDecodeView = inputBuffer.subarray(incomingOffset, incomingOffset + returnObject.blockLength);\r\n return {\r\n offset: resultOffset,\r\n result: returnObject\r\n };\r\n}\r\nfunction fromBER(inputBuffer) {\r\n if (!inputBuffer.byteLength) {\r\n const result = new BaseBlock({}, ValueBlock);\r\n result.error = \"Input buffer has zero length\";\r\n return {\r\n offset: -1,\r\n result\r\n };\r\n }\r\n return localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).slice(), 0, inputBuffer.byteLength);\r\n}\n\nfunction checkLen(indefiniteLength, length) {\r\n if (indefiniteLength) {\r\n return 1;\r\n }\r\n return length;\r\n}\r\nclass LocalConstructedValueBlock extends ValueBlock {\r\n constructor({ value = [], isIndefiniteForm = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.isIndefiniteForm = isIndefiniteForm;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const view = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, view, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueBeforeDecodeView = view.subarray(inputOffset, inputOffset + inputLength);\r\n if (this.valueBeforeDecodeView.length === 0) {\r\n this.warnings.push(\"Zero buffer length\");\r\n return inputOffset;\r\n }\r\n let currentOffset = inputOffset;\r\n while (checkLen(this.isIndefiniteForm, inputLength) > 0) {\r\n const returnObject = localFromBER(view, currentOffset, inputLength);\r\n if (returnObject.offset === -1) {\r\n this.error = returnObject.result.error;\r\n this.warnings.concat(returnObject.result.warnings);\r\n return -1;\r\n }\r\n currentOffset = returnObject.offset;\r\n this.blockLength += returnObject.result.blockLength;\r\n inputLength -= returnObject.result.blockLength;\r\n this.value.push(returnObject.result);\r\n if (this.isIndefiniteForm && returnObject.result.constructor.NAME === END_OF_CONTENT_NAME) {\r\n break;\r\n }\r\n }\r\n if (this.isIndefiniteForm) {\r\n if (this.value[this.value.length - 1].constructor.NAME === END_OF_CONTENT_NAME) {\r\n this.value.pop();\r\n }\r\n else {\r\n this.warnings.push(\"No EndOfContent block encoded\");\r\n }\r\n }\r\n return currentOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const _writer = writer || new ViewWriter();\r\n for (let i = 0; i < this.value.length; i++) {\r\n this.value[i].toBER(sizeOnly, _writer);\r\n }\r\n if (!writer) {\r\n return _writer.final();\r\n }\r\n return EMPTY_BUFFER;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n isIndefiniteForm: this.isIndefiniteForm,\r\n value: [],\r\n };\r\n for (const value of this.value) {\r\n object.value.push(value.toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalConstructedValueBlock.NAME = \"ConstructedValueBlock\";\n\nvar _a$v;\r\nclass Constructed extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalConstructedValueBlock);\r\n this.idBlock.isConstructed = true;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n const resultOffset = this.valueBlock.fromBER(inputBuffer, inputOffset, (this.lenBlock.isIndefiniteForm) ? inputLength : this.lenBlock.length);\r\n if (resultOffset === -1) {\r\n this.error = this.valueBlock.error;\r\n return resultOffset;\r\n }\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n if (!this.valueBlock.error.length)\r\n this.blockLength += this.valueBlock.blockLength;\r\n return resultOffset;\r\n }\r\n onAsciiEncoding() {\r\n const values = [];\r\n for (const value of this.valueBlock.value) {\r\n values.push(value.toString(\"ascii\").split(\"\\n\").map(o => ` ${o}`).join(\"\\n\"));\r\n }\r\n const blockName = this.idBlock.tagClass === 3\r\n ? `[${this.idBlock.tagNumber}]`\r\n : this.constructor.NAME;\r\n return values.length\r\n ? `${blockName} :\\n${values.join(\"\\n\")}`\r\n : `${blockName} :`;\r\n }\r\n}\r\n_a$v = Constructed;\r\n(() => {\r\n typeStore.Constructed = _a$v;\r\n})();\r\nConstructed.NAME = \"CONSTRUCTED\";\n\nclass LocalEndOfContentValueBlock extends ValueBlock {\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n return inputOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return EMPTY_BUFFER;\r\n }\r\n}\r\nLocalEndOfContentValueBlock.override = \"EndOfContentValueBlock\";\n\nvar _a$u;\r\nclass EndOfContent extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalEndOfContentValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 0;\r\n }\r\n}\r\n_a$u = EndOfContent;\r\n(() => {\r\n typeStore.EndOfContent = _a$u;\r\n})();\r\nEndOfContent.NAME = END_OF_CONTENT_NAME;\n\nvar _a$t;\r\nclass Null extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, ValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 5;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (this.lenBlock.length > 0)\r\n this.warnings.push(\"Non-zero length of value block for Null type\");\r\n if (!this.idBlock.error.length)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (!this.lenBlock.error.length)\r\n this.blockLength += this.lenBlock.blockLength;\r\n this.blockLength += inputLength;\r\n if ((inputOffset + inputLength) > inputBuffer.byteLength) {\r\n this.error = \"End of input reached before message was fully decoded (inconsistent offset and length values)\";\r\n return -1;\r\n }\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuf = new ArrayBuffer(2);\r\n if (!sizeOnly) {\r\n const retView = new Uint8Array(retBuf);\r\n retView[0] = 0x05;\r\n retView[1] = 0x00;\r\n }\r\n if (writer) {\r\n writer.write(retBuf);\r\n }\r\n return retBuf;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME}`;\r\n }\r\n}\r\n_a$t = Null;\r\n(() => {\r\n typeStore.Null = _a$t;\r\n})();\r\nNull.NAME = \"NULL\";\n\nclass LocalBooleanValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n if (parameters.valueHex) {\r\n this.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(parameters.valueHex);\r\n }\r\n else {\r\n this.valueHexView = new Uint8Array(1);\r\n }\r\n if (value) {\r\n this.value = value;\r\n }\r\n }\r\n get value() {\r\n for (const octet of this.valueHexView) {\r\n if (octet > 0) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n set value(value) {\r\n this.valueHexView[0] = value ? 0xFF : 0x00;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n this.valueHexView = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n if (inputLength > 1)\r\n this.warnings.push(\"Boolean value encoded in more then 1 octet\");\r\n this.isHexOnly = true;\r\n pvutils.utilDecodeTC.call(this);\r\n this.blockLength = inputLength;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER() {\r\n return this.valueHexView.slice();\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalBooleanValueBlock.NAME = \"BooleanValueBlock\";\n\nvar _a$s;\r\nclass Boolean extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalBooleanValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 1;\r\n }\r\n getValue() {\r\n return this.valueBlock.value;\r\n }\r\n setValue(value) {\r\n this.valueBlock.value = value;\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.getValue}`;\r\n }\r\n}\r\n_a$s = Boolean;\r\n(() => {\r\n typeStore.Boolean = _a$s;\r\n})();\r\nBoolean.NAME = \"BOOLEAN\";\n\nclass LocalOctetStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.isConstructed = isConstructed;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = 0;\r\n if (this.isConstructed) {\r\n this.isHexOnly = false;\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (let i = 0; i < this.value.length; i++) {\r\n const currentBlockName = this.value[i].constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== OCTET_STRING_NAME) {\r\n this.error = \"OCTET STRING may consists of OCTET STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n }\r\n else {\r\n this.isHexOnly = true;\r\n resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n this.blockLength = inputLength;\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed)\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.byteLength)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalOctetStringValueBlock.NAME = \"OctetStringValueBlock\";\n\nvar _a$r;\r\nclass OctetString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalOctetStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 4;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n if (inputLength === 0) {\r\n if (this.idBlock.error.length === 0)\r\n this.blockLength += this.idBlock.blockLength;\r\n if (this.lenBlock.error.length === 0)\r\n this.blockLength += this.lenBlock.blockLength;\r\n return inputOffset;\r\n }\r\n if (!this.valueBlock.isConstructed) {\r\n const view = inputBuffer instanceof ArrayBuffer ? new Uint8Array(inputBuffer) : inputBuffer;\r\n const buf = view.subarray(inputOffset, inputOffset + inputLength);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === inputLength) {\r\n this.valueBlock.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n return `${this.constructor.NAME} : ${pvtsutils.Convert.ToHex(this.valueBlock.valueHexView)}`;\r\n }\r\n getValue() {\r\n if (!this.idBlock.isConstructed) {\r\n return this.valueBlock.valueHexView.slice().buffer;\r\n }\r\n const array = [];\r\n for (const content of this.valueBlock.value) {\r\n if (content instanceof OctetString) {\r\n array.push(content.valueBlock.valueHexView);\r\n }\r\n }\r\n return pvtsutils.BufferSourceConverter.concat(array);\r\n }\r\n}\r\n_a$r = OctetString;\r\n(() => {\r\n typeStore.OctetString = _a$r;\r\n})();\r\nOctetString.NAME = OCTET_STRING_NAME;\n\nclass LocalBitStringValueBlock extends HexBlock(LocalConstructedValueBlock) {\r\n constructor({ unusedBits = 0, isConstructed = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.unusedBits = unusedBits;\r\n this.isConstructed = isConstructed;\r\n this.blockLength = this.valueHexView.byteLength;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n let resultOffset = -1;\r\n if (this.isConstructed) {\r\n resultOffset = LocalConstructedValueBlock.prototype.fromBER.call(this, inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1)\r\n return resultOffset;\r\n for (const value of this.value) {\r\n const currentBlockName = value.constructor.NAME;\r\n if (currentBlockName === END_OF_CONTENT_NAME) {\r\n if (this.isIndefiniteForm)\r\n break;\r\n else {\r\n this.error = \"EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n }\r\n if (currentBlockName !== BIT_STRING_NAME) {\r\n this.error = \"BIT STRING may consists of BIT STRINGs only\";\r\n return -1;\r\n }\r\n const valueBlock = value.valueBlock;\r\n if ((this.unusedBits > 0) && (valueBlock.unusedBits > 0)) {\r\n this.error = \"Using of \\\"unused bits\\\" inside constructive BIT STRING allowed for least one only\";\r\n return -1;\r\n }\r\n this.unusedBits = valueBlock.unusedBits;\r\n }\r\n return resultOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.unusedBits = intBuffer[0];\r\n if (this.unusedBits > 7) {\r\n this.error = \"Unused bits for BitString must be in range 0-7\";\r\n return -1;\r\n }\r\n if (!this.unusedBits) {\r\n const buf = intBuffer.subarray(1);\r\n try {\r\n if (buf.byteLength) {\r\n const asn = localFromBER(buf, 0, buf.byteLength);\r\n if (asn.offset !== -1 && asn.offset === (inputLength - 1)) {\r\n this.value = [asn.result];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n }\r\n }\r\n this.valueHexView = intBuffer.subarray(1);\r\n this.blockLength = intBuffer.length;\r\n return (inputOffset + inputLength);\r\n }\r\n toBER(sizeOnly, writer) {\r\n if (this.isConstructed) {\r\n return LocalConstructedValueBlock.prototype.toBER.call(this, sizeOnly, writer);\r\n }\r\n if (sizeOnly) {\r\n return new ArrayBuffer(this.valueHexView.byteLength + 1);\r\n }\r\n if (!this.valueHexView.byteLength) {\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(this.valueHexView.length + 1);\r\n retView[0] = this.unusedBits;\r\n retView.set(this.valueHexView, 1);\r\n return retView.buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n unusedBits: this.unusedBits,\r\n isConstructed: this.isConstructed,\r\n };\r\n }\r\n}\r\nLocalBitStringValueBlock.NAME = \"BitStringValueBlock\";\n\nvar _a$q;\r\nclass BitString extends BaseBlock {\r\n constructor({ idBlock = {}, lenBlock = {}, ...parameters } = {}) {\r\n var _b, _c;\r\n (_b = parameters.isConstructed) !== null && _b !== void 0 ? _b : (parameters.isConstructed = !!((_c = parameters.value) === null || _c === void 0 ? void 0 : _c.length));\r\n super({\r\n idBlock: {\r\n isConstructed: parameters.isConstructed,\r\n ...idBlock,\r\n },\r\n lenBlock: {\r\n ...lenBlock,\r\n isIndefiniteForm: !!parameters.isIndefiniteForm,\r\n },\r\n ...parameters,\r\n }, LocalBitStringValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 3;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n this.valueBlock.isConstructed = this.idBlock.isConstructed;\r\n this.valueBlock.isIndefiniteForm = this.lenBlock.isIndefiniteForm;\r\n return super.fromBER(inputBuffer, inputOffset, inputLength);\r\n }\r\n onAsciiEncoding() {\r\n if (this.valueBlock.isConstructed || (this.valueBlock.value && this.valueBlock.value.length)) {\r\n return Constructed.prototype.onAsciiEncoding.call(this);\r\n }\r\n else {\r\n const bits = [];\r\n const valueHex = this.valueBlock.valueHexView;\r\n for (const byte of valueHex) {\r\n bits.push(byte.toString(2).padStart(8, \"0\"));\r\n }\r\n const bitsStr = bits.join(\"\");\r\n return `${this.constructor.NAME} : ${bitsStr.substring(0, bitsStr.length - this.valueBlock.unusedBits)}`;\r\n }\r\n }\r\n}\r\n_a$q = BitString;\r\n(() => {\r\n typeStore.BitString = _a$q;\r\n})();\r\nBitString.NAME = BIT_STRING_NAME;\n\nvar _a$p;\r\nfunction viewAdd(first, second) {\r\n const c = new Uint8Array([0]);\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n let firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value = 0;\r\n const max = (secondViewCopyLength < firstViewCopyLength) ? firstViewCopyLength : secondViewCopyLength;\r\n let counter = 0;\r\n for (let i = max; i >= 0; i--, counter++) {\r\n switch (true) {\r\n case (counter < secondViewCopy.length):\r\n value = firstViewCopy[firstViewCopyLength - counter] + secondViewCopy[secondViewCopyLength - counter] + c[0];\r\n break;\r\n default:\r\n value = firstViewCopy[firstViewCopyLength - counter] + c[0];\r\n }\r\n c[0] = value / 10;\r\n switch (true) {\r\n case (counter >= firstViewCopy.length):\r\n firstViewCopy = pvutils.utilConcatView(new Uint8Array([value % 10]), firstViewCopy);\r\n break;\r\n default:\r\n firstViewCopy[firstViewCopyLength - counter] = value % 10;\r\n }\r\n }\r\n if (c[0] > 0)\r\n firstViewCopy = pvutils.utilConcatView(c, firstViewCopy);\r\n return firstViewCopy;\r\n}\r\nfunction power2(n) {\r\n if (n >= powers2.length) {\r\n for (let p = powers2.length; p <= n; p++) {\r\n const c = new Uint8Array([0]);\r\n let digits = (powers2[p - 1]).slice(0);\r\n for (let i = (digits.length - 1); i >= 0; i--) {\r\n const newValue = new Uint8Array([(digits[i] << 1) + c[0]]);\r\n c[0] = newValue[0] / 10;\r\n digits[i] = newValue[0] % 10;\r\n }\r\n if (c[0] > 0)\r\n digits = pvutils.utilConcatView(c, digits);\r\n powers2.push(digits);\r\n }\r\n }\r\n return powers2[n];\r\n}\r\nfunction viewSub(first, second) {\r\n let b = 0;\r\n const firstView = new Uint8Array(first);\r\n const secondView = new Uint8Array(second);\r\n const firstViewCopy = firstView.slice(0);\r\n const firstViewCopyLength = firstViewCopy.length - 1;\r\n const secondViewCopy = secondView.slice(0);\r\n const secondViewCopyLength = secondViewCopy.length - 1;\r\n let value;\r\n let counter = 0;\r\n for (let i = secondViewCopyLength; i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - secondViewCopy[secondViewCopyLength - counter] - b;\r\n switch (true) {\r\n case (value < 0):\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n break;\r\n default:\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n }\r\n }\r\n if (b > 0) {\r\n for (let i = (firstViewCopyLength - secondViewCopyLength + 1); i >= 0; i--, counter++) {\r\n value = firstViewCopy[firstViewCopyLength - counter] - b;\r\n if (value < 0) {\r\n b = 1;\r\n firstViewCopy[firstViewCopyLength - counter] = value + 10;\r\n }\r\n else {\r\n b = 0;\r\n firstViewCopy[firstViewCopyLength - counter] = value;\r\n break;\r\n }\r\n }\r\n }\r\n return firstViewCopy.slice();\r\n}\r\nclass LocalIntegerValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ value, ...parameters } = {}) {\r\n super(parameters);\r\n this._valueDec = 0;\r\n if (parameters.valueHex) {\r\n this.setValueHex();\r\n }\r\n if (value !== undefined) {\r\n this.valueDec = value;\r\n }\r\n }\r\n setValueHex() {\r\n if (this.valueHexView.length >= 4) {\r\n this.warnings.push(\"Too big Integer for decoding, hex only\");\r\n this.isHexOnly = true;\r\n this._valueDec = 0;\r\n }\r\n else {\r\n this.isHexOnly = false;\r\n if (this.valueHexView.length > 0) {\r\n this._valueDec = pvutils.utilDecodeTC.call(this);\r\n }\r\n }\r\n }\r\n set valueDec(v) {\r\n this._valueDec = v;\r\n this.isHexOnly = false;\r\n this.valueHexView = new Uint8Array(pvutils.utilEncodeTC(v));\r\n }\r\n get valueDec() {\r\n return this._valueDec;\r\n }\r\n fromDER(inputBuffer, inputOffset, inputLength, expectedLength = 0) {\r\n const offset = this.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (offset === -1)\r\n return offset;\r\n const view = this.valueHexView;\r\n if ((view[0] === 0x00) && ((view[1] & 0x80) !== 0)) {\r\n this.valueHexView = view.subarray(1);\r\n }\r\n else {\r\n if (expectedLength !== 0) {\r\n if (view.length < expectedLength) {\r\n if ((expectedLength - view.length) > 1)\r\n expectedLength = view.length + 1;\r\n this.valueHexView = view.subarray(expectedLength - view.length);\r\n }\r\n }\r\n }\r\n return offset;\r\n }\r\n toDER(sizeOnly = false) {\r\n const view = this.valueHexView;\r\n switch (true) {\r\n case ((view[0] & 0x80) !== 0):\r\n {\r\n const updatedView = new Uint8Array(this.valueHexView.length + 1);\r\n updatedView[0] = 0x00;\r\n updatedView.set(view, 1);\r\n this.valueHexView = updatedView;\r\n }\r\n break;\r\n case ((view[0] === 0x00) && ((view[1] & 0x80) === 0)):\r\n {\r\n this.valueHexView = this.valueHexView.subarray(1);\r\n }\r\n break;\r\n }\r\n return this.toBER(sizeOnly);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const resultOffset = super.fromBER(inputBuffer, inputOffset, inputLength);\r\n if (resultOffset === -1) {\r\n return resultOffset;\r\n }\r\n this.setValueHex();\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n return sizeOnly\r\n ? new ArrayBuffer(this.valueHexView.length)\r\n : this.valueHexView.slice().buffer;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n toString() {\r\n const firstBit = (this.valueHexView.length * 8) - 1;\r\n let digits = new Uint8Array((this.valueHexView.length * 8) / 3);\r\n let bitNumber = 0;\r\n let currentByte;\r\n const asn1View = this.valueHexView;\r\n let result = \"\";\r\n let flag = false;\r\n for (let byteNumber = (asn1View.byteLength - 1); byteNumber >= 0; byteNumber--) {\r\n currentByte = asn1View[byteNumber];\r\n for (let i = 0; i < 8; i++) {\r\n if ((currentByte & 1) === 1) {\r\n switch (bitNumber) {\r\n case firstBit:\r\n digits = viewSub(power2(bitNumber), digits);\r\n result = \"-\";\r\n break;\r\n default:\r\n digits = viewAdd(digits, power2(bitNumber));\r\n }\r\n }\r\n bitNumber++;\r\n currentByte >>= 1;\r\n }\r\n }\r\n for (let i = 0; i < digits.length; i++) {\r\n if (digits[i])\r\n flag = true;\r\n if (flag)\r\n result += digitsString.charAt(digits[i]);\r\n }\r\n if (flag === false)\r\n result += digitsString.charAt(0);\r\n return result;\r\n }\r\n}\r\n_a$p = LocalIntegerValueBlock;\r\nLocalIntegerValueBlock.NAME = \"IntegerValueBlock\";\r\n(() => {\r\n Object.defineProperty(_a$p.prototype, \"valueHex\", {\r\n set: function (v) {\r\n this.valueHexView = new Uint8Array(v);\r\n this.setValueHex();\r\n },\r\n get: function () {\r\n return this.valueHexView.slice().buffer;\r\n },\r\n });\r\n})();\n\nvar _a$o;\r\nclass Integer extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalIntegerValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 2;\r\n }\r\n toBigInt() {\r\n assertBigInt();\r\n return BigInt(this.valueBlock.toString());\r\n }\r\n static fromBigInt(value) {\r\n assertBigInt();\r\n const bigIntValue = BigInt(value);\r\n const writer = new ViewWriter();\r\n const hex = bigIntValue.toString(16).replace(/^-/, \"\");\r\n const view = new Uint8Array(pvtsutils.Convert.FromHex(hex));\r\n if (bigIntValue < 0) {\r\n const first = new Uint8Array(view.length + (view[0] & 0x80 ? 1 : 0));\r\n first[0] |= 0x80;\r\n const firstInt = BigInt(`0x${pvtsutils.Convert.ToHex(first)}`);\r\n const secondInt = firstInt + bigIntValue;\r\n const second = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(secondInt.toString(16)));\r\n second[0] |= 0x80;\r\n writer.write(second);\r\n }\r\n else {\r\n if (view[0] & 0x80) {\r\n writer.write(new Uint8Array([0]));\r\n }\r\n writer.write(view);\r\n }\r\n const res = new Integer({\r\n valueHex: writer.final(),\r\n });\r\n return res;\r\n }\r\n convertToDER() {\r\n const integer = new Integer({ valueHex: this.valueBlock.valueHexView });\r\n integer.valueBlock.toDER();\r\n return integer;\r\n }\r\n convertFromDER() {\r\n return new Integer({\r\n valueHex: this.valueBlock.valueHexView[0] === 0\r\n ? this.valueBlock.valueHexView.subarray(1)\r\n : this.valueBlock.valueHexView,\r\n });\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString()}`;\r\n }\r\n}\r\n_a$o = Integer;\r\n(() => {\r\n typeStore.Integer = _a$o;\r\n})();\r\nInteger.NAME = \"INTEGER\";\n\nvar _a$n;\r\nclass Enumerated extends Integer {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 10;\r\n }\r\n}\r\n_a$n = Enumerated;\r\n(() => {\r\n typeStore.Enumerated = _a$n;\r\n})();\r\nEnumerated.NAME = \"ENUMERATED\";\n\nclass LocalSidValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ valueDec = -1, isFirstSid = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n this.isFirstSid = isFirstSid;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (!inputLength) {\r\n return inputOffset;\r\n }\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength)) {\r\n return -1;\r\n }\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++) {\r\n tempView[i] = this.valueHexView[i];\r\n }\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n set valueBigInt(value) {\r\n assertBigInt();\r\n let bits = BigInt(value).toString(2);\r\n while (bits.length % 7) {\r\n bits = \"0\" + bits;\r\n }\r\n const bytes = new Uint8Array(bits.length / 7);\r\n for (let i = 0; i < bytes.length; i++) {\r\n bytes[i] = parseInt(bits.slice(i * 7, i * 7 + 7), 2) + (i + 1 < bytes.length ? 0x80 : 0);\r\n }\r\n this.fromBER(bytes.buffer, 0, bytes.length);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n if (this.isFirstSid) {\r\n let sidValue = this.valueDec;\r\n if (this.valueDec <= 39)\r\n result = \"0.\";\r\n else {\r\n if (this.valueDec <= 79) {\r\n result = \"1.\";\r\n sidValue -= 40;\r\n }\r\n else {\r\n result = \"2.\";\r\n sidValue -= 80;\r\n }\r\n }\r\n result += sidValue.toString();\r\n }\r\n else\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n isFirstSid: this.isFirstSid,\r\n };\r\n }\r\n}\r\nLocalSidValueBlock.NAME = \"sidBlock\";\n\nclass LocalObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n if (this.value.length === 0)\r\n sidBlock.isFirstSid = true;\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n let flag = false;\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n if (flag) {\r\n const sidBlock = this.value[0];\r\n let plus = 0;\r\n switch (sidBlock.valueDec) {\r\n case 0:\r\n break;\r\n case 1:\r\n plus = 40;\r\n break;\r\n case 2:\r\n plus = 80;\r\n break;\r\n default:\r\n this.value = [];\r\n return;\r\n }\r\n const parsedSID = parseInt(sid, 10);\r\n if (isNaN(parsedSID))\r\n return;\r\n sidBlock.valueDec = parsedSID + plus;\r\n flag = false;\r\n }\r\n else {\r\n const sidBlock = new LocalSidValueBlock();\r\n if (sid > Number.MAX_SAFE_INTEGER) {\r\n assertBigInt();\r\n const sidValue = BigInt(sid);\r\n sidBlock.valueBigInt = sidValue;\r\n }\r\n else {\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return;\r\n }\r\n if (!this.value.length) {\r\n sidBlock.isFirstSid = true;\r\n flag = true;\r\n }\r\n this.value.push(sidBlock);\r\n }\r\n } while (pos2 !== -1);\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n if (this.value[i].isFirstSid)\r\n result = `2.{${sidStr} - 80}`;\r\n else\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++) {\r\n object.sidArray.push(this.value[i].toJSON());\r\n }\r\n return object;\r\n }\r\n}\r\nLocalObjectIdentifierValueBlock.NAME = \"ObjectIdentifierValueBlock\";\n\nvar _a$m;\r\nclass ObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 6;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$m = ObjectIdentifier;\r\n(() => {\r\n typeStore.ObjectIdentifier = _a$m;\r\n})();\r\nObjectIdentifier.NAME = \"OBJECT IDENTIFIER\";\n\nclass LocalRelativeSidValueBlock extends HexBlock(LocalBaseBlock) {\r\n constructor({ valueDec = 0, ...parameters } = {}) {\r\n super(parameters);\r\n this.valueDec = valueDec;\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n if (inputLength === 0)\r\n return inputOffset;\r\n const inputView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n if (!checkBufferParams(this, inputView, inputOffset, inputLength))\r\n return -1;\r\n const intBuffer = inputView.subarray(inputOffset, inputOffset + inputLength);\r\n this.valueHexView = new Uint8Array(inputLength);\r\n for (let i = 0; i < inputLength; i++) {\r\n this.valueHexView[i] = intBuffer[i] & 0x7F;\r\n this.blockLength++;\r\n if ((intBuffer[i] & 0x80) === 0x00)\r\n break;\r\n }\r\n const tempView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < this.blockLength; i++)\r\n tempView[i] = this.valueHexView[i];\r\n this.valueHexView = tempView;\r\n if ((intBuffer[this.blockLength - 1] & 0x80) !== 0x00) {\r\n this.error = \"End of input reached before message was fully decoded\";\r\n return -1;\r\n }\r\n if (this.valueHexView[0] === 0x00)\r\n this.warnings.push(\"Needlessly long format of SID encoding\");\r\n if (this.blockLength <= 8)\r\n this.valueDec = pvutils.utilFromBase(this.valueHexView, 7);\r\n else {\r\n this.isHexOnly = true;\r\n this.warnings.push(\"Too big SID for decoding, hex only\");\r\n }\r\n return (inputOffset + this.blockLength);\r\n }\r\n toBER(sizeOnly) {\r\n if (this.isHexOnly) {\r\n if (sizeOnly)\r\n return (new ArrayBuffer(this.valueHexView.byteLength));\r\n const curView = this.valueHexView;\r\n const retView = new Uint8Array(this.blockLength);\r\n for (let i = 0; i < (this.blockLength - 1); i++)\r\n retView[i] = curView[i] | 0x80;\r\n retView[this.blockLength - 1] = curView[this.blockLength - 1];\r\n return retView.buffer;\r\n }\r\n const encodedBuf = pvutils.utilToBase(this.valueDec, 7);\r\n if (encodedBuf.byteLength === 0) {\r\n this.error = \"Error during encoding SID value\";\r\n return EMPTY_BUFFER;\r\n }\r\n const retView = new Uint8Array(encodedBuf.byteLength);\r\n if (!sizeOnly) {\r\n const encodedView = new Uint8Array(encodedBuf);\r\n const len = encodedBuf.byteLength - 1;\r\n for (let i = 0; i < len; i++)\r\n retView[i] = encodedView[i] | 0x80;\r\n retView[len] = encodedView[len];\r\n }\r\n return retView.buffer;\r\n }\r\n toString() {\r\n let result = \"\";\r\n if (this.isHexOnly)\r\n result = pvtsutils.Convert.ToHex(this.valueHexView);\r\n else {\r\n result = this.valueDec.toString();\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n valueDec: this.valueDec,\r\n };\r\n }\r\n}\r\nLocalRelativeSidValueBlock.NAME = \"relativeSidBlock\";\n\nclass LocalRelativeObjectIdentifierValueBlock extends ValueBlock {\r\n constructor({ value = EMPTY_STRING, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = [];\r\n if (value) {\r\n this.fromString(value);\r\n }\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n let resultOffset = inputOffset;\r\n while (inputLength > 0) {\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n resultOffset = sidBlock.fromBER(inputBuffer, resultOffset, inputLength);\r\n if (resultOffset === -1) {\r\n this.blockLength = 0;\r\n this.error = sidBlock.error;\r\n return resultOffset;\r\n }\r\n this.blockLength += sidBlock.blockLength;\r\n inputLength -= sidBlock.blockLength;\r\n this.value.push(sidBlock);\r\n }\r\n return resultOffset;\r\n }\r\n toBER(sizeOnly, writer) {\r\n const retBuffers = [];\r\n for (let i = 0; i < this.value.length; i++) {\r\n const valueBuf = this.value[i].toBER(sizeOnly);\r\n if (valueBuf.byteLength === 0) {\r\n this.error = this.value[i].error;\r\n return EMPTY_BUFFER;\r\n }\r\n retBuffers.push(valueBuf);\r\n }\r\n return concat(retBuffers);\r\n }\r\n fromString(string) {\r\n this.value = [];\r\n let pos1 = 0;\r\n let pos2 = 0;\r\n let sid = \"\";\r\n do {\r\n pos2 = string.indexOf(\".\", pos1);\r\n if (pos2 === -1)\r\n sid = string.substring(pos1);\r\n else\r\n sid = string.substring(pos1, pos2);\r\n pos1 = pos2 + 1;\r\n const sidBlock = new LocalRelativeSidValueBlock();\r\n sidBlock.valueDec = parseInt(sid, 10);\r\n if (isNaN(sidBlock.valueDec))\r\n return true;\r\n this.value.push(sidBlock);\r\n } while (pos2 !== -1);\r\n return true;\r\n }\r\n toString() {\r\n let result = \"\";\r\n let isHexOnly = false;\r\n for (let i = 0; i < this.value.length; i++) {\r\n isHexOnly = this.value[i].isHexOnly;\r\n let sidStr = this.value[i].toString();\r\n if (i !== 0)\r\n result = `${result}.`;\r\n if (isHexOnly) {\r\n sidStr = `{${sidStr}}`;\r\n result += sidStr;\r\n }\r\n else\r\n result += sidStr;\r\n }\r\n return result;\r\n }\r\n toJSON() {\r\n const object = {\r\n ...super.toJSON(),\r\n value: this.toString(),\r\n sidArray: [],\r\n };\r\n for (let i = 0; i < this.value.length; i++)\r\n object.sidArray.push(this.value[i].toJSON());\r\n return object;\r\n }\r\n}\r\nLocalRelativeObjectIdentifierValueBlock.NAME = \"RelativeObjectIdentifierValueBlock\";\n\nvar _a$l;\r\nclass RelativeObjectIdentifier extends BaseBlock {\r\n constructor(parameters = {}) {\r\n super(parameters, LocalRelativeObjectIdentifierValueBlock);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 13;\r\n }\r\n getValue() {\r\n return this.valueBlock.toString();\r\n }\r\n setValue(value) {\r\n this.valueBlock.fromString(value);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.valueBlock.toString() || \"empty\"}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.getValue(),\r\n };\r\n }\r\n}\r\n_a$l = RelativeObjectIdentifier;\r\n(() => {\r\n typeStore.RelativeObjectIdentifier = _a$l;\r\n})();\r\nRelativeObjectIdentifier.NAME = \"RelativeObjectIdentifier\";\n\nvar _a$k;\r\nclass Sequence extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 16;\r\n }\r\n}\r\n_a$k = Sequence;\r\n(() => {\r\n typeStore.Sequence = _a$k;\r\n})();\r\nSequence.NAME = \"SEQUENCE\";\n\nvar _a$j;\r\nclass Set extends Constructed {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 17;\r\n }\r\n}\r\n_a$j = Set;\r\n(() => {\r\n typeStore.Set = _a$j;\r\n})();\r\nSet.NAME = \"SET\";\n\nclass LocalStringValueBlock extends HexBlock(ValueBlock) {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.isHexOnly = true;\r\n this.value = EMPTY_STRING;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n value: this.value,\r\n };\r\n }\r\n}\r\nLocalStringValueBlock.NAME = \"StringValueBlock\";\n\nclass LocalSimpleStringValueBlock extends LocalStringValueBlock {\r\n}\r\nLocalSimpleStringValueBlock.NAME = \"SimpleStringValueBlock\";\n\nclass LocalSimpleStringBlock extends BaseStringBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters, LocalSimpleStringValueBlock);\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLen = inputString.length;\r\n const view = this.valueBlock.valueHexView = new Uint8Array(strLen);\r\n for (let i = 0; i < strLen; i++)\r\n view[i] = inputString.charCodeAt(i);\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalSimpleStringBlock.NAME = \"SIMPLE STRING\";\n\nclass LocalUtf8StringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n try {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf8String(inputBuffer);\r\n }\r\n catch (ex) {\r\n this.warnings.push(`Error during \"decodeURIComponent\": ${ex}, using raw string`);\r\n this.valueBlock.value = pvtsutils.Convert.ToBinary(inputBuffer);\r\n }\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf8String(inputString));\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUtf8StringValueBlock.NAME = \"Utf8StringValueBlock\";\n\nvar _a$i;\r\nclass Utf8String extends LocalUtf8StringValueBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 12;\r\n }\r\n}\r\n_a$i = Utf8String;\r\n(() => {\r\n typeStore.Utf8String = _a$i;\r\n})();\r\nUtf8String.NAME = \"UTF8String\";\n\nclass LocalBmpStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n this.valueBlock.value = pvtsutils.Convert.ToUtf16String(inputBuffer);\r\n this.valueBlock.valueHexView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer);\r\n }\r\n fromString(inputString) {\r\n this.valueBlock.value = inputString;\r\n this.valueBlock.valueHexView = new Uint8Array(pvtsutils.Convert.FromUtf16String(inputString));\r\n }\r\n}\r\nLocalBmpStringValueBlock.NAME = \"BmpStringValueBlock\";\n\nvar _a$h;\r\nclass BmpString extends LocalBmpStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 30;\r\n }\r\n}\r\n_a$h = BmpString;\r\n(() => {\r\n typeStore.BmpString = _a$h;\r\n})();\r\nBmpString.NAME = \"BMPString\";\n\nclass LocalUniversalStringValueBlock extends LocalSimpleStringBlock {\r\n fromBuffer(inputBuffer) {\r\n const copyBuffer = ArrayBuffer.isView(inputBuffer) ? inputBuffer.slice().buffer : inputBuffer.slice(0);\r\n const valueView = new Uint8Array(copyBuffer);\r\n for (let i = 0; i < valueView.length; i += 4) {\r\n valueView[i] = valueView[i + 3];\r\n valueView[i + 1] = valueView[i + 2];\r\n valueView[i + 2] = 0x00;\r\n valueView[i + 3] = 0x00;\r\n }\r\n this.valueBlock.value = String.fromCharCode.apply(null, new Uint32Array(copyBuffer));\r\n }\r\n fromString(inputString) {\r\n const strLength = inputString.length;\r\n const valueHexView = this.valueBlock.valueHexView = new Uint8Array(strLength * 4);\r\n for (let i = 0; i < strLength; i++) {\r\n const codeBuf = pvutils.utilToBase(inputString.charCodeAt(i), 8);\r\n const codeView = new Uint8Array(codeBuf);\r\n if (codeView.length > 4)\r\n continue;\r\n const dif = 4 - codeView.length;\r\n for (let j = (codeView.length - 1); j >= 0; j--)\r\n valueHexView[i * 4 + j + dif] = codeView[j];\r\n }\r\n this.valueBlock.value = inputString;\r\n }\r\n}\r\nLocalUniversalStringValueBlock.NAME = \"UniversalStringValueBlock\";\n\nvar _a$g;\r\nclass UniversalString extends LocalUniversalStringValueBlock {\r\n constructor({ ...parameters } = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 28;\r\n }\r\n}\r\n_a$g = UniversalString;\r\n(() => {\r\n typeStore.UniversalString = _a$g;\r\n})();\r\nUniversalString.NAME = \"UniversalString\";\n\nvar _a$f;\r\nclass NumericString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 18;\r\n }\r\n}\r\n_a$f = NumericString;\r\n(() => {\r\n typeStore.NumericString = _a$f;\r\n})();\r\nNumericString.NAME = \"NumericString\";\n\nvar _a$e;\r\nclass PrintableString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 19;\r\n }\r\n}\r\n_a$e = PrintableString;\r\n(() => {\r\n typeStore.PrintableString = _a$e;\r\n})();\r\nPrintableString.NAME = \"PrintableString\";\n\nvar _a$d;\r\nclass TeletexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 20;\r\n }\r\n}\r\n_a$d = TeletexString;\r\n(() => {\r\n typeStore.TeletexString = _a$d;\r\n})();\r\nTeletexString.NAME = \"TeletexString\";\n\nvar _a$c;\r\nclass VideotexString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 21;\r\n }\r\n}\r\n_a$c = VideotexString;\r\n(() => {\r\n typeStore.VideotexString = _a$c;\r\n})();\r\nVideotexString.NAME = \"VideotexString\";\n\nvar _a$b;\r\nclass IA5String extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 22;\r\n }\r\n}\r\n_a$b = IA5String;\r\n(() => {\r\n typeStore.IA5String = _a$b;\r\n})();\r\nIA5String.NAME = \"IA5String\";\n\nvar _a$a;\r\nclass GraphicString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 25;\r\n }\r\n}\r\n_a$a = GraphicString;\r\n(() => {\r\n typeStore.GraphicString = _a$a;\r\n})();\r\nGraphicString.NAME = \"GraphicString\";\n\nvar _a$9;\r\nclass VisibleString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 26;\r\n }\r\n}\r\n_a$9 = VisibleString;\r\n(() => {\r\n typeStore.VisibleString = _a$9;\r\n})();\r\nVisibleString.NAME = \"VisibleString\";\n\nvar _a$8;\r\nclass GeneralString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 27;\r\n }\r\n}\r\n_a$8 = GeneralString;\r\n(() => {\r\n typeStore.GeneralString = _a$8;\r\n})();\r\nGeneralString.NAME = \"GeneralString\";\n\nvar _a$7;\r\nclass CharacterString extends LocalSimpleStringBlock {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 29;\r\n }\r\n}\r\n_a$7 = CharacterString;\r\n(() => {\r\n typeStore.CharacterString = _a$7;\r\n})();\r\nCharacterString.NAME = \"CharacterString\";\n\nvar _a$6;\r\nclass UTCTime extends VisibleString {\r\n constructor({ value, valueDate, ...parameters } = {}) {\r\n super(parameters);\r\n this.year = 0;\r\n this.month = 0;\r\n this.day = 0;\r\n this.hour = 0;\r\n this.minute = 0;\r\n this.second = 0;\r\n if (value) {\r\n this.fromString(value);\r\n this.valueBlock.valueHexView = new Uint8Array(value.length);\r\n for (let i = 0; i < value.length; i++)\r\n this.valueBlock.valueHexView[i] = value.charCodeAt(i);\r\n }\r\n if (valueDate) {\r\n this.fromDate(valueDate);\r\n this.valueBlock.valueHexView = new Uint8Array(this.toBuffer());\r\n }\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 23;\r\n }\r\n fromBuffer(inputBuffer) {\r\n this.fromString(String.fromCharCode.apply(null, pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer)));\r\n }\r\n toBuffer() {\r\n const str = this.toString();\r\n const buffer = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buffer);\r\n for (let i = 0; i < str.length; i++)\r\n view[i] = str.charCodeAt(i);\r\n return buffer;\r\n }\r\n fromDate(inputDate) {\r\n this.year = inputDate.getUTCFullYear();\r\n this.month = inputDate.getUTCMonth() + 1;\r\n this.day = inputDate.getUTCDate();\r\n this.hour = inputDate.getUTCHours();\r\n this.minute = inputDate.getUTCMinutes();\r\n this.second = inputDate.getUTCSeconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second)));\r\n }\r\n fromString(inputString) {\r\n const parser = /(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z/ig;\r\n const parserArray = parser.exec(inputString);\r\n if (parserArray === null) {\r\n this.error = \"Wrong input string for conversion\";\r\n return;\r\n }\r\n const year = parseInt(parserArray[1], 10);\r\n if (year >= 50)\r\n this.year = 1900 + year;\r\n else\r\n this.year = 2000 + year;\r\n this.month = parseInt(parserArray[2], 10);\r\n this.day = parseInt(parserArray[3], 10);\r\n this.hour = parseInt(parserArray[4], 10);\r\n this.minute = parseInt(parserArray[5], 10);\r\n this.second = parseInt(parserArray[6], 10);\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = new Array(7);\r\n outputArray[0] = pvutils.padNumber(((this.year < 2000) ? (this.year - 1900) : (this.year - 2000)), 2);\r\n outputArray[1] = pvutils.padNumber(this.month, 2);\r\n outputArray[2] = pvutils.padNumber(this.day, 2);\r\n outputArray[3] = pvutils.padNumber(this.hour, 2);\r\n outputArray[4] = pvutils.padNumber(this.minute, 2);\r\n outputArray[5] = pvutils.padNumber(this.second, 2);\r\n outputArray[6] = \"Z\";\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n onAsciiEncoding() {\r\n return `${this.constructor.NAME} : ${this.toDate().toISOString()}`;\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n year: this.year,\r\n month: this.month,\r\n day: this.day,\r\n hour: this.hour,\r\n minute: this.minute,\r\n second: this.second,\r\n };\r\n }\r\n}\r\n_a$6 = UTCTime;\r\n(() => {\r\n typeStore.UTCTime = _a$6;\r\n})();\r\nUTCTime.NAME = \"UTCTime\";\n\nvar _a$5;\r\nclass GeneralizedTime extends UTCTime {\r\n constructor(parameters = {}) {\r\n var _b;\r\n super(parameters);\r\n (_b = this.millisecond) !== null && _b !== void 0 ? _b : (this.millisecond = 0);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 24;\r\n }\r\n fromDate(inputDate) {\r\n super.fromDate(inputDate);\r\n this.millisecond = inputDate.getUTCMilliseconds();\r\n }\r\n toDate() {\r\n return (new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)));\r\n }\r\n fromString(inputString) {\r\n let isUTC = false;\r\n let timeString = \"\";\r\n let dateTimeString = \"\";\r\n let fractionPart = 0;\r\n let parser;\r\n let hourDifference = 0;\r\n let minuteDifference = 0;\r\n if (inputString[inputString.length - 1] === \"Z\") {\r\n timeString = inputString.substring(0, inputString.length - 1);\r\n isUTC = true;\r\n }\r\n else {\r\n const number = new Number(inputString[inputString.length - 1]);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n timeString = inputString;\r\n }\r\n if (isUTC) {\r\n if (timeString.indexOf(\"+\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n if (timeString.indexOf(\"-\") !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n else {\r\n let multiplier = 1;\r\n let differencePosition = timeString.indexOf(\"+\");\r\n let differenceString = \"\";\r\n if (differencePosition === -1) {\r\n differencePosition = timeString.indexOf(\"-\");\r\n multiplier = -1;\r\n }\r\n if (differencePosition !== -1) {\r\n differenceString = timeString.substring(differencePosition + 1);\r\n timeString = timeString.substring(0, differencePosition);\r\n if ((differenceString.length !== 2) && (differenceString.length !== 4))\r\n throw new Error(\"Wrong input string for conversion\");\r\n let number = parseInt(differenceString.substring(0, 2), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n hourDifference = multiplier * number;\r\n if (differenceString.length === 4) {\r\n number = parseInt(differenceString.substring(2, 4), 10);\r\n if (isNaN(number.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n minuteDifference = multiplier * number;\r\n }\r\n }\r\n }\r\n let fractionPointPosition = timeString.indexOf(\".\");\r\n if (fractionPointPosition === -1)\r\n fractionPointPosition = timeString.indexOf(\",\");\r\n if (fractionPointPosition !== -1) {\r\n const fractionPartCheck = new Number(`0${timeString.substring(fractionPointPosition)}`);\r\n if (isNaN(fractionPartCheck.valueOf()))\r\n throw new Error(\"Wrong input string for conversion\");\r\n fractionPart = fractionPartCheck.valueOf();\r\n dateTimeString = timeString.substring(0, fractionPointPosition);\r\n }\r\n else\r\n dateTimeString = timeString;\r\n switch (true) {\r\n case (dateTimeString.length === 8):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1)\r\n throw new Error(\"Wrong input string for conversion\");\r\n break;\r\n case (dateTimeString.length === 10):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.minute = Math.floor(fractionResult);\r\n fractionResult = 60 * (fractionResult - this.minute);\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 12):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n let fractionResult = 60 * fractionPart;\r\n this.second = Math.floor(fractionResult);\r\n fractionResult = 1000 * (fractionResult - this.second);\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n case (dateTimeString.length === 14):\r\n parser = /(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})/ig;\r\n if (fractionPointPosition !== -1) {\r\n const fractionResult = 1000 * fractionPart;\r\n this.millisecond = Math.floor(fractionResult);\r\n }\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n const parserArray = parser.exec(dateTimeString);\r\n if (parserArray === null)\r\n throw new Error(\"Wrong input string for conversion\");\r\n for (let j = 1; j < parserArray.length; j++) {\r\n switch (j) {\r\n case 1:\r\n this.year = parseInt(parserArray[j], 10);\r\n break;\r\n case 2:\r\n this.month = parseInt(parserArray[j], 10);\r\n break;\r\n case 3:\r\n this.day = parseInt(parserArray[j], 10);\r\n break;\r\n case 4:\r\n this.hour = parseInt(parserArray[j], 10) + hourDifference;\r\n break;\r\n case 5:\r\n this.minute = parseInt(parserArray[j], 10) + minuteDifference;\r\n break;\r\n case 6:\r\n this.second = parseInt(parserArray[j], 10);\r\n break;\r\n default:\r\n throw new Error(\"Wrong input string for conversion\");\r\n }\r\n }\r\n if (isUTC === false) {\r\n const tempDate = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\r\n this.year = tempDate.getUTCFullYear();\r\n this.month = tempDate.getUTCMonth();\r\n this.day = tempDate.getUTCDay();\r\n this.hour = tempDate.getUTCHours();\r\n this.minute = tempDate.getUTCMinutes();\r\n this.second = tempDate.getUTCSeconds();\r\n this.millisecond = tempDate.getUTCMilliseconds();\r\n }\r\n }\r\n toString(encoding = \"iso\") {\r\n if (encoding === \"iso\") {\r\n const outputArray = [];\r\n outputArray.push(pvutils.padNumber(this.year, 4));\r\n outputArray.push(pvutils.padNumber(this.month, 2));\r\n outputArray.push(pvutils.padNumber(this.day, 2));\r\n outputArray.push(pvutils.padNumber(this.hour, 2));\r\n outputArray.push(pvutils.padNumber(this.minute, 2));\r\n outputArray.push(pvutils.padNumber(this.second, 2));\r\n if (this.millisecond !== 0) {\r\n outputArray.push(\".\");\r\n outputArray.push(pvutils.padNumber(this.millisecond, 3));\r\n }\r\n outputArray.push(\"Z\");\r\n return outputArray.join(\"\");\r\n }\r\n return super.toString(encoding);\r\n }\r\n toJSON() {\r\n return {\r\n ...super.toJSON(),\r\n millisecond: this.millisecond,\r\n };\r\n }\r\n}\r\n_a$5 = GeneralizedTime;\r\n(() => {\r\n typeStore.GeneralizedTime = _a$5;\r\n})();\r\nGeneralizedTime.NAME = \"GeneralizedTime\";\n\nvar _a$4;\r\nclass DATE extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 31;\r\n }\r\n}\r\n_a$4 = DATE;\r\n(() => {\r\n typeStore.DATE = _a$4;\r\n})();\r\nDATE.NAME = \"DATE\";\n\nvar _a$3;\r\nclass TimeOfDay extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 32;\r\n }\r\n}\r\n_a$3 = TimeOfDay;\r\n(() => {\r\n typeStore.TimeOfDay = _a$3;\r\n})();\r\nTimeOfDay.NAME = \"TimeOfDay\";\n\nvar _a$2;\r\nclass DateTime extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 33;\r\n }\r\n}\r\n_a$2 = DateTime;\r\n(() => {\r\n typeStore.DateTime = _a$2;\r\n})();\r\nDateTime.NAME = \"DateTime\";\n\nvar _a$1;\r\nclass Duration extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 34;\r\n }\r\n}\r\n_a$1 = Duration;\r\n(() => {\r\n typeStore.Duration = _a$1;\r\n})();\r\nDuration.NAME = \"Duration\";\n\nvar _a;\r\nclass TIME extends Utf8String {\r\n constructor(parameters = {}) {\r\n super(parameters);\r\n this.idBlock.tagClass = 1;\r\n this.idBlock.tagNumber = 14;\r\n }\r\n}\r\n_a = TIME;\r\n(() => {\r\n typeStore.TIME = _a;\r\n})();\r\nTIME.NAME = \"TIME\";\n\nclass Any {\r\n constructor({ name = EMPTY_STRING, optional = false, } = {}) {\r\n this.name = name;\r\n this.optional = optional;\r\n }\r\n}\n\nclass Choice extends Any {\r\n constructor({ value = [], ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n }\r\n}\n\nclass Repeated extends Any {\r\n constructor({ value = new Any(), local = false, ...parameters } = {}) {\r\n super(parameters);\r\n this.value = value;\r\n this.local = local;\r\n }\r\n}\n\nclass RawData {\r\n constructor({ data = EMPTY_VIEW } = {}) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(data);\r\n }\r\n get data() {\r\n return this.dataView.slice().buffer;\r\n }\r\n set data(value) {\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(value);\r\n }\r\n fromBER(inputBuffer, inputOffset, inputLength) {\r\n const endLength = inputOffset + inputLength;\r\n this.dataView = pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer).subarray(inputOffset, endLength);\r\n return endLength;\r\n }\r\n toBER(sizeOnly) {\r\n return this.dataView.slice().buffer;\r\n }\r\n}\n\nfunction compareSchema(root, inputData, inputSchema) {\r\n if (inputSchema instanceof Choice) {\r\n for (let j = 0; j < inputSchema.value.length; j++) {\r\n const result = compareSchema(root, inputData, inputSchema.value[j]);\r\n if (result.verified) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n }\r\n {\r\n const _result = {\r\n verified: false,\r\n result: {\r\n error: \"Wrong values for Choice type\"\r\n },\r\n };\r\n if (inputSchema.hasOwnProperty(NAME))\r\n _result.name = inputSchema.name;\r\n return _result;\r\n }\r\n }\r\n if (inputSchema instanceof Any) {\r\n if (inputSchema.hasOwnProperty(NAME))\r\n root[inputSchema.name] = inputData;\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((root instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong root object\" }\r\n };\r\n }\r\n if ((inputData instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 data\" }\r\n };\r\n }\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((ID_BLOCK in inputSchema) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((FROM_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if ((TO_BER in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const encodedId = inputSchema.idBlock.toBER(false);\r\n if (encodedId.byteLength === 0) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error encoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n const decodedOffset = inputSchema.idBlock.fromBER(encodedId, 0, encodedId.byteLength);\r\n if (decodedOffset === -1) {\r\n return {\r\n verified: false,\r\n result: { error: \"Error decoding idBlock for ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_CLASS) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagClass !== inputData.idBlock.tagClass) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(TAG_NUMBER) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.tagNumber !== inputData.idBlock.tagNumber) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.hasOwnProperty(IS_CONSTRUCTED) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isConstructed !== inputData.idBlock.isConstructed) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (!(IS_HEX_ONLY in inputSchema.idBlock)) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly !== inputData.idBlock.isHexOnly) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.idBlock.isHexOnly) {\r\n if ((VALUE_HEX_VIEW in inputSchema.idBlock) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema\" }\r\n };\r\n }\r\n const schemaView = inputSchema.idBlock.valueHexView;\r\n const asn1View = inputData.idBlock.valueHexView;\r\n if (schemaView.length !== asn1View.length) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < schemaView.length; i++) {\r\n if (schemaView[i] !== asn1View[1]) {\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n }\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n root[inputSchema.name] = inputData;\r\n }\r\n if (inputSchema instanceof typeStore.Constructed) {\r\n let admission = 0;\r\n let result = {\r\n verified: false,\r\n result: {\r\n error: \"Unknown error\",\r\n }\r\n };\r\n let maxLength = inputSchema.valueBlock.value.length;\r\n if (maxLength > 0) {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n maxLength = inputData.valueBlock.value.length;\r\n }\r\n }\r\n if (maxLength === 0) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if ((inputData.valueBlock.value.length === 0) &&\r\n (inputSchema.valueBlock.value.length !== 0)) {\r\n let _optional = true;\r\n for (let i = 0; i < inputSchema.valueBlock.value.length; i++)\r\n _optional = _optional && (inputSchema.valueBlock.value[i].optional || false);\r\n if (_optional) {\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n root.error = \"Inconsistent object length\";\r\n return {\r\n verified: false,\r\n result: root\r\n };\r\n }\r\n for (let i = 0; i < maxLength; i++) {\r\n if ((i - admission) >= inputData.valueBlock.value.length) {\r\n if (inputSchema.valueBlock.value[i].optional === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n root.error = \"Inconsistent length between ASN.1 data and schema\";\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n }\r\n else {\r\n if (inputSchema.valueBlock.value[0] instanceof Repeated) {\r\n result = compareSchema(root, inputData.valueBlock.value[i], inputSchema.valueBlock.value[0].value);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[0].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n if ((NAME in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].name.length > 0)) {\r\n let arrayRoot = {};\r\n if ((LOCAL in inputSchema.valueBlock.value[0]) && (inputSchema.valueBlock.value[0].local))\r\n arrayRoot = inputData;\r\n else\r\n arrayRoot = root;\r\n if (typeof arrayRoot[inputSchema.valueBlock.value[0].name] === \"undefined\")\r\n arrayRoot[inputSchema.valueBlock.value[0].name] = [];\r\n arrayRoot[inputSchema.valueBlock.value[0].name].push(inputData.valueBlock.value[i]);\r\n }\r\n }\r\n else {\r\n result = compareSchema(root, inputData.valueBlock.value[i - admission], inputSchema.valueBlock.value[i]);\r\n if (result.verified === false) {\r\n if (inputSchema.valueBlock.value[i].optional)\r\n admission++;\r\n else {\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name)\r\n delete root[inputSchema.name];\r\n }\r\n return result;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n if (result.verified === false) {\r\n const _result = {\r\n verified: false,\r\n result: root\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n }\r\n if (inputSchema.primitiveSchema &&\r\n (VALUE_HEX_VIEW in inputData.valueBlock)) {\r\n const asn1 = localFromBER(inputData.valueBlock.valueHexView);\r\n if (asn1.offset === -1) {\r\n const _result = {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n if (inputSchema.name) {\r\n inputSchema.name = inputSchema.name.replace(/^\\s+|\\s+$/g, EMPTY_STRING);\r\n if (inputSchema.name) {\r\n delete root[inputSchema.name];\r\n _result.name = inputSchema.name;\r\n }\r\n }\r\n return _result;\r\n }\r\n return compareSchema(root, asn1.result, inputSchema.primitiveSchema);\r\n }\r\n return {\r\n verified: true,\r\n result: root\r\n };\r\n}\r\nfunction verifySchema(inputBuffer, inputSchema) {\r\n if ((inputSchema instanceof Object) === false) {\r\n return {\r\n verified: false,\r\n result: { error: \"Wrong ASN.1 schema type\" }\r\n };\r\n }\r\n const asn1 = localFromBER(pvtsutils.BufferSourceConverter.toUint8Array(inputBuffer));\r\n if (asn1.offset === -1) {\r\n return {\r\n verified: false,\r\n result: asn1.result\r\n };\r\n }\r\n return compareSchema(asn1.result, asn1.result, inputSchema);\r\n}\n\nexport { Any, BaseBlock, BaseStringBlock, BitString, BmpString, Boolean, CharacterString, Choice, Constructed, DATE, DateTime, Duration, EndOfContent, Enumerated, GeneralString, GeneralizedTime, GraphicString, HexBlock, IA5String, Integer, Null, NumericString, ObjectIdentifier, OctetString, Primitive, PrintableString, RawData, RelativeObjectIdentifier, Repeated, Sequence, Set, TIME, TeletexString, TimeOfDay, UTCTime, UniversalString, Utf8String, ValueBlock, VideotexString, ViewWriter, VisibleString, compareSchema, fromBER, verifySchema };\n","/**\n * Signing a message failed\n */\nexport class SigningError extends Error {\n constructor(message = 'An error occurred while signing a message') {\n super(message);\n this.name = 'SigningError';\n }\n}\n/**\n * Verifying a message signature failed\n */\nexport class VerificationError extends Error {\n constructor(message = 'An error occurred while verifying a message') {\n super(message);\n this.name = 'VerificationError';\n }\n}\n/**\n * WebCrypto was not available in the current context\n */\nexport class WebCryptoMissingError extends Error {\n constructor(message = 'Missing Web Crypto API') {\n super(message);\n this.name = 'WebCryptoMissingError';\n }\n}\n//# sourceMappingURL=errors.js.map","/* eslint-env browser */\nimport { WebCryptoMissingError } from '../errors.js';\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\nexport default {\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw new WebCryptoMissingError('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api');\n }\n return nativeCrypto;\n }\n};\n//# sourceMappingURL=webcrypto.browser.js.map","import webcrypto from './webcrypto.js';\nexport default webcrypto;\n//# sourceMappingURL=index.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport {} from 'multiformats/hashes/digest';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { hashAndSign, utils, hashAndVerify } from './index.js';\nexport class RSAPublicKey {\n type = 'RSA';\n _key;\n _raw;\n _multihash;\n constructor(key, digest) {\n this._key = key;\n this._multihash = digest;\n }\n get raw() {\n if (this._raw == null) {\n this._raw = utils.jwkToPkix(this._key);\n }\n return this._raw;\n }\n toMultihash() {\n return this._multihash;\n }\n toCID() {\n return CID.createV1(114, this._multihash);\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig) {\n return hashAndVerify(this._key, sig, data);\n }\n}\nexport class RSAPrivateKey {\n type = 'RSA';\n _key;\n _raw;\n publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this.publicKey = publicKey;\n }\n get raw() {\n if (this._raw == null) {\n this._raw = utils.jwkToPkcs1(this._key);\n }\n return this._raw;\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message) {\n return hashAndSign(this._key, message);\n }\n}\n//# sourceMappingURL=rsa.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport randomBytes from '../../random-bytes.js';\nimport webcrypto from '../../webcrypto/index.js';\nimport * as utils from './utils.js';\nexport { utils };\nexport async function generateRSAKey(bits) {\n const pair = await webcrypto.get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\nexport { randomBytes as getRandomValues };\nexport async function hashAndSign(key, msg) {\n const privateKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await webcrypto.get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nexport async function hashAndVerify(key, sig, msg) {\n const publicKey = await webcrypto.get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return webcrypto.get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new InvalidParametersError('Private and public key are required');\n }\n return Promise.all([\n webcrypto.get().subtle.exportKey('jwk', pair.privateKey),\n webcrypto.get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nexport function rsaKeySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new InvalidParametersError('invalid key type');\n }\n else if (jwk.n == null) {\n throw new InvalidParametersError('invalid key modulus');\n }\n const bytes = uint8ArrayFromString(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=index.browser.js.map","import { InvalidParametersError, InvalidPublicKeyError } from '@libp2p/interface';\nimport { sha256 } from '@noble/hashes/sha256';\nimport * as asn1js from 'asn1js';\nimport { create } from 'multiformats/hashes/digest';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport * as pb from '../keys.js';\nimport { RSAPrivateKey as RSAPrivateKeyClass, RSAPublicKey as RSAPublicKeyClass } from './rsa.js';\nimport { generateRSAKey, rsaKeySize } from './index.js';\nexport const MAX_RSA_KEY_SIZE = 8192;\nconst SHA2_256_CODE = 0x12;\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nexport function pkcs1ToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: asn1jsIntegerToBase64(values[1]),\n e: asn1jsIntegerToBase64(values[2]),\n d: asn1jsIntegerToBase64(values[3]),\n p: asn1jsIntegerToBase64(values[4]),\n q: asn1jsIntegerToBase64(values[5]),\n dp: asn1jsIntegerToBase64(values[6]),\n dq: asn1jsIntegerToBase64(values[7]),\n qi: asn1jsIntegerToBase64(values[8]),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nexport function jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new InvalidParametersError('JWK was missing components');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Integer({ value: 0 }),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.d, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.p, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.q, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dp, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.dq, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKIX in ASN1 DER format to a JWK key\n */\nexport function pkixToJwk(bytes) {\n const { result } = asn1js.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: asn1jsIntegerToBase64(values[0]),\n e: asn1jsIntegerToBase64(values[1])\n };\n}\n/**\n * Convert a JWK key to PKIX in ASN1 DER format\n */\nexport function jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new InvalidParametersError('JWK was missing components');\n }\n const root = new asn1js.Sequence({\n value: [\n new asn1js.Sequence({\n value: [\n // rsaEncryption\n new asn1js.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js.BitString({\n valueHex: new asn1js.Sequence({\n value: [\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.n, 'base64url'))),\n asn1js.Integer.fromBigInt(bufToBn(uint8ArrayFromString(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction asn1jsIntegerToBase64(int) {\n let buf = int.valueBlock.valueHexView;\n // chrome rejects values with leading 0s\n while (buf[0] === 0) {\n buf = buf.subarray(1);\n }\n return uint8ArrayToString(buf, 'base64url');\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\n/**\n * Turn PCKS#1 DER bytes to a PrivateKey\n */\nexport function pkcs1ToRSAPrivateKey(bytes) {\n const jwk = pkcs1ToJwk(bytes);\n return jwkToRSAPrivateKey(jwk);\n}\n/**\n * Turn PKIX bytes to a PublicKey\n */\nexport function pkixToRSAPublicKey(bytes) {\n const jwk = pkixToJwk(bytes);\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidPublicKeyError('Key size is too large');\n }\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: bytes\n }));\n const digest = create(SHA2_256_CODE, hash);\n return new RSAPublicKeyClass(jwk, digest);\n}\nexport function jwkToRSAPrivateKey(jwk) {\n if (rsaKeySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large');\n }\n const keys = jwkToJWKKeyPair(jwk);\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }));\n const digest = create(SHA2_256_CODE, hash);\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest));\n}\nexport async function generateRSAKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new InvalidParametersError('Key size is too large');\n }\n const keys = await generateRSAKey(bits);\n const hash = sha256(pb.PublicKey.encode({\n Type: pb.KeyType.RSA,\n Data: jwkToPkix(keys.publicKey)\n }));\n const digest = create(SHA2_256_CODE, hash);\n return new RSAPrivateKeyClass(keys.privateKey, new RSAPublicKeyClass(keys.publicKey, digest));\n}\n/**\n * Takes a jwk key and returns a JWK KeyPair\n */\nexport function jwkToJWKKeyPair(key) {\n if (key == null) {\n throw new InvalidParametersError('Missing key parameter');\n }\n return {\n privateKey: key,\n publicKey: {\n kty: key.kty,\n n: key.n,\n e: key.e\n }\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n ahash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n abytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { pippenger, validateBasic, wNAF, } from './curve.js';\nimport { Field, getMinHashLength, invert, mapHashToField, mod, validateField, } from './modular.js';\nimport * as ut from './utils.js';\nimport { abool, ensureBytes, memoized } from './utils.js';\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n abool('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = ut.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? ut.numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = ut.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = ut.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n ut.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return ut.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key))\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);\n }\n if (wrapPrivateKey)\n num = mod(num, N); // disabled by default, enabled for BLS\n ut.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = memoized((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = memoized((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return pippenger(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (this.is0() || sc === _1n)\n return this;\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n ut.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n abool('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n abool('isCompressed', isCompressed);\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n abool('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!ut.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n ut.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n ut.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = getMinHashLength(CURVE.n);\n return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // Our custom check \"just in case\"\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n ut.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || ut.isBytes(sg);\n const isObj = !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n let _sig = undefined;\n let P;\n try {\n if (isObj)\n _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact')\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!_sig && format !== 'der')\n _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n return false;\n }\n if (!_sig)\n return false;\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { createCurve } from './_shortw_utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { aInRange, bytesToNumberBE, concatBytes, ensureBytes, inRange, numberToBytesBE, } from './abstract/utils.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n *\n * @example\n * import { secp256k1 } from '@noble/curves/secp256k1';\n *\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n */\nexport const secp256k1 = createCurve({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7),\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n aInRange('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!inRange(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!inRange(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n */\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/** secp256k1 hash-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\n/** secp256k1 encode-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","import { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport function base64urlToBuffer(str, len) {\n let buf = uint8ArrayFromString(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = uint8ArrayConcat([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nexport function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { publicKeyToProtobuf } from '../index.js';\nimport { validateSecp256k1PublicKey, compressSecp256k1PublicKey, computeSecp256k1PublicKey, validateSecp256k1PrivateKey } from './utils.js';\nimport { hashAndVerify, hashAndSign } from './index.js';\nexport class Secp256k1PublicKey {\n type = 'secp256k1';\n raw;\n _key;\n constructor(key) {\n this._key = validateSecp256k1PublicKey(key);\n this.raw = compressSecp256k1PublicKey(this._key);\n }\n toMultihash() {\n return identity.digest(publicKeyToProtobuf(this));\n }\n toCID() {\n return CID.createV1(114, this.toMultihash());\n }\n toString() {\n return base58btc.encode(this.toMultihash().bytes).substring(1);\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n verify(data, sig) {\n return hashAndVerify(this._key, sig, data);\n }\n}\nexport class Secp256k1PrivateKey {\n type = 'secp256k1';\n raw;\n publicKey;\n constructor(key, publicKey) {\n this.raw = validateSecp256k1PrivateKey(key);\n this.publicKey = new Secp256k1PublicKey(publicKey ?? computeSecp256k1PublicKey(key));\n }\n equals(key) {\n if (key == null || !(key.raw instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.raw, key.raw);\n }\n sign(message) {\n return hashAndSign(this.raw, message);\n }\n}\n//# sourceMappingURL=secp256k1.js.map","import { InvalidPrivateKeyError, InvalidPublicKeyError } from '@libp2p/interface';\nimport { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { Secp256k1PublicKey as Secp256k1PublicKeyClass, Secp256k1PrivateKey as Secp256k1PrivateKeyClass } from './secp256k1.js';\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\nexport { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength };\nexport function unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKeyClass(bytes);\n}\nexport function unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKeyClass(bytes);\n}\nexport async function generateSecp256k1KeyPair() {\n const privateKeyBytes = generateSecp256k1PrivateKey();\n return new Secp256k1PrivateKeyClass(privateKeyBytes);\n}\nexport function compressSecp256k1PublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nexport function decompressSecp256k1PublicKey(key) {\n const point = secp.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nexport function validateSecp256k1PrivateKey(key) {\n try {\n secp.getPublicKey(key, true);\n return key;\n }\n catch (err) {\n throw new InvalidPrivateKeyError(String(err));\n }\n}\nexport function validateSecp256k1PublicKey(key) {\n try {\n secp.ProjectivePoint.fromHex(key);\n return key;\n }\n catch (err) {\n throw new InvalidPublicKeyError(String(err));\n }\n}\nexport function computeSecp256k1PublicKey(privateKey) {\n try {\n return secp.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new InvalidPrivateKeyError(String(err));\n }\n}\nexport function generateSecp256k1PrivateKey() {\n return secp.utils.randomPrivateKey();\n}\n//# sourceMappingURL=utils.js.map","import { secp256k1 as secp } from '@noble/curves/secp256k1';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { SigningError, VerificationError } from '../../errors.js';\nimport { isPromise } from '../../util.js';\n/**\n * Hash and sign message with private key\n */\nexport function hashAndSign(key, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new SigningError(String(err));\n });\n }\n try {\n return secp.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new SigningError(String(err));\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nexport function hashAndVerify(key, sig, msg) {\n const p = sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if (isPromise(p)) {\n return p.then(({ digest }) => secp.verify(sig, digest, key))\n .catch(err => {\n throw new VerificationError(String(err));\n });\n }\n try {\n return secp.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new VerificationError(String(err));\n }\n}\n//# sourceMappingURL=index.browser.js.map","/**\n * @packageDocumentation\n *\n * ## Supported Key Types\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\nimport { UnsupportedKeyTypeError } from '@libp2p/interface';\nimport { generateEd25519KeyPair, generateEd25519KeyPairFromSeed, unmarshalEd25519PrivateKey, unmarshalEd25519PublicKey } from './ed25519/utils.js';\nimport * as pb from './keys.js';\nimport { pkcs1ToRSAPrivateKey, pkixToRSAPublicKey, generateRSAKeyPair } from './rsa/utils.js';\nimport { generateSecp256k1KeyPair, unmarshalSecp256k1PrivateKey, unmarshalSecp256k1PublicKey } from './secp256k1/utils.js';\nexport { generateEphemeralKeyPair } from './ecdh/index.js';\nexport { keyStretcher } from './key-stretcher.js';\nexport async function generateKeyPair(type, bits) {\n if (type === 'Ed25519') {\n return generateEd25519KeyPair();\n }\n if (type === 'secp256k1') {\n return generateSecp256k1KeyPair();\n }\n if (type === 'RSA') {\n return generateRSAKeyPair(bits ?? 2048);\n }\n throw new UnsupportedKeyTypeError();\n}\nexport async function generateKeyPairFromSeed(type, seed) {\n if (type !== 'Ed25519') {\n throw new UnsupportedKeyTypeError('Seed key derivation only supported for Ed25519 keys');\n }\n return generateEd25519KeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nexport function publicKeyFromProtobuf(buf) {\n const { Type, Data } = pb.PublicKey.decode(buf);\n const data = Data ?? new Uint8Array();\n switch (Type) {\n case pb.KeyType.RSA:\n return pkixToRSAPublicKey(data);\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Creates a public key from the raw key bytes\n */\nexport function publicKeyFromRaw(buf) {\n if (buf.byteLength === 32) {\n return unmarshalEd25519PublicKey(buf);\n }\n else if (buf.byteLength === 33) {\n return unmarshalSecp256k1PublicKey(buf);\n }\n else {\n return pkixToRSAPublicKey(buf);\n }\n}\n/**\n * Creates a public key from an identity multihash which contains a protobuf\n * encoded Ed25519 or secp256k1 public key.\n *\n * RSA keys are not supported as in practice we they are not stored in identity\n * multihashes since the hash would be very large.\n */\nexport function publicKeyFromMultihash(digest) {\n const { Type, Data } = pb.PublicKey.decode(digest.digest);\n const data = Data ?? new Uint8Array();\n switch (Type) {\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PublicKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PublicKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nexport function publicKeyToProtobuf(key) {\n return pb.PublicKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n });\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nexport function privateKeyFromProtobuf(buf) {\n const decoded = pb.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case pb.KeyType.RSA:\n return pkcs1ToRSAPrivateKey(data);\n case pb.KeyType.Ed25519:\n return unmarshalEd25519PrivateKey(data);\n case pb.KeyType.secp256k1:\n return unmarshalSecp256k1PrivateKey(data);\n default:\n throw new UnsupportedKeyTypeError();\n }\n}\n/**\n * Creates a private key from the raw key bytes. For Ed25519 keys this requires\n * the public key to be appended to the private key otherwise we can't\n * differentiate between Ed25519 and secp256k1 keys as they are the same length.\n */\nexport function privateKeyFromRaw(buf) {\n if (buf.byteLength === 64) {\n return unmarshalEd25519PrivateKey(buf);\n }\n else if (buf.byteLength === 32) {\n return unmarshalSecp256k1PrivateKey(buf);\n }\n else {\n return pkcs1ToRSAPrivateKey(buf);\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nexport function privateKeyToProtobuf(key) {\n return pb.PrivateKey.encode({\n Type: pb.KeyType[key.type],\n Data: key.raw\n });\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nexport const serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nexport const serviceDependencies = Symbol.for('@libp2p/service-dependencies');\nexport * from './connection/index.js';\nexport * from './connection-encrypter/index.js';\nexport * from './connection-gater/index.js';\nexport * from './content-routing/index.js';\nexport * from './keys/index.js';\nexport * from './metrics/index.js';\nexport * from './peer-discovery/index.js';\nexport * from './peer-id/index.js';\nexport * from './peer-info/index.js';\nexport * from './peer-routing/index.js';\nexport * from './peer-store/index.js';\nexport * from './peer-store/tags.js';\nexport * from './pubsub/index.js';\nexport * from './record/index.js';\nexport * from './stream-handler/index.js';\nexport * from './stream-muxer/index.js';\nexport * from './topology/index.js';\nexport * from './transport/index.js';\nexport * from './errors.js';\nexport * from './event-target.js';\nexport * from './events.js';\nexport * from './startable.js';\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { peerIdSymbol } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { CID } from 'multiformats/cid';\nimport { identity } from 'multiformats/hashes/identity';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nclass PeerIdImpl {\n type;\n multihash;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n toMultihash() {\n return this.multihash;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return uint8ArrayEquals(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return this.toString() === id;\n }\n else if (id?.toMultihash()?.bytes != null) {\n return uint8ArrayEquals(this.multihash.bytes, id.toMultihash().bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nexport class RSAPeerId extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nexport class Ed25519PeerId extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.publicKey;\n }\n}\nexport class Secp256k1PeerId extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.publicKey;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nexport class URLPeerId {\n type = 'url';\n multihash;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = identity.digest(uint8ArrayFromString(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toMultihash() {\n return this.multihash;\n }\n toCID() {\n return CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.toMultihash());\n }\n toJSON() {\n return this.toString();\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = uint8ArrayToString(other);\n }\n return other.toString() === this.toString();\n }\n}\n//# sourceMappingURL=peer-id.js.map","/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\nimport { publicKeyFromMultihash } from '@libp2p/crypto/keys';\nimport { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface';\nimport { base58btc } from 'multiformats/bases/base58';\nimport {} from 'multiformats/cid';\nimport * as Digest from 'multiformats/hashes/digest';\nimport { identity } from 'multiformats/hashes/identity';\nimport { sha256 } from 'multiformats/hashes/sha2';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RSAPeerId as RSAPeerIdClass, Ed25519PeerId as Ed25519PeerIdClass, Secp256k1PeerId as Secp256k1PeerIdClass, URLPeerId as URLPeerIdClass } from './peer-id.js';\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nexport function peerIdFromString(str, decoder) {\n let multihash;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n multihash = Digest.decode(base58btc.decode(`z${str}`));\n }\n else {\n if (decoder == null) {\n throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with \"1\" or \"Q\"');\n }\n multihash = Digest.decode(decoder.decode(str));\n }\n return peerIdFromMultihash(multihash);\n}\nexport function peerIdFromPublicKey(publicKey) {\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n else if (publicKey.type === 'RSA') {\n return new RSAPeerIdClass({\n multihash: publicKey.toCID().multihash,\n publicKey\n });\n }\n throw new UnsupportedKeyTypeError();\n}\nexport function peerIdFromPrivateKey(privateKey) {\n return peerIdFromPublicKey(privateKey.publicKey);\n}\nexport function peerIdFromMultihash(multihash) {\n if (isSha256Multihash(multihash)) {\n return new RSAPeerIdClass({ multihash });\n }\n else if (isIdentityMultihash(multihash)) {\n try {\n const publicKey = publicKeyFromMultihash(multihash);\n if (publicKey.type === 'Ed25519') {\n return new Ed25519PeerIdClass({ multihash, publicKey });\n }\n else if (publicKey.type === 'secp256k1') {\n return new Secp256k1PeerIdClass({ multihash, publicKey });\n }\n }\n catch (err) {\n // was not Ed or secp key, try URL\n const url = uint8ArrayToString(multihash.digest);\n return new URLPeerIdClass(new URL(url));\n }\n }\n throw new InvalidMultihashError('Supplied PeerID Multihash is invalid');\n}\nexport function peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new InvalidCIDError('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = uint8ArrayToString(cid.multihash.digest);\n return new URLPeerIdClass(new URL(url));\n }\n return peerIdFromMultihash(cid.multihash);\n}\nfunction isIdentityMultihash(multihash) {\n return multihash.code === identity.code;\n}\nfunction isSha256Multihash(multihash) {\n return multihash.code === sha256.code;\n}\n//# sourceMappingURL=index.js.map","/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code, name) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = name ?? 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceSignal(promise, signal, opts) {\n if (signal == null) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName));\n }\n let listener;\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName);\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error);\n };\n signal.addEventListener('abort', listener);\n })\n ]);\n }\n finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\nimport deferred, {} from 'p-defer';\nimport { raceSignal } from 'race-signal';\nclass QueuelessPushable {\n readNext;\n haveNext;\n ended;\n nextResult;\n constructor() {\n this.ended = false;\n this.readNext = deferred();\n this.haveNext = deferred();\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n async next() {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise;\n }\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined');\n }\n const nextResult = this.nextResult;\n this.nextResult = undefined;\n // signal to the supplier that we read the value\n this.readNext.resolve();\n this.readNext = deferred();\n return nextResult;\n }\n async throw(err) {\n this.ended = true;\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => { });\n this.haveNext.reject(err);\n }\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n async return() {\n const result = {\n done: true,\n value: undefined\n };\n await this._push(undefined);\n return result;\n }\n async push(value, options) {\n await this._push(value, options);\n }\n async end(err, options) {\n if (err != null) {\n await this.throw(err);\n }\n else {\n // abortable return\n await this._push(undefined, options);\n }\n }\n async _push(value, options) {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable');\n }\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise;\n }\n if (value != null) {\n this.nextResult = { done: false, value };\n }\n else {\n this.ended = true;\n this.nextResult = { done: true, value: undefined };\n }\n // let the consumer know we have a new value\n this.haveNext.resolve();\n this.haveNext = deferred();\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await raceSignal(this.readNext.promise, options?.signal, options);\n }\n}\nexport function queuelessPushable() {\n return new QueuelessPushable();\n}\n//# sourceMappingURL=index.js.map","/**\n * The incoming stream ended before the expected number of bytes were read\n */\nexport class UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\nimport { queuelessPushable } from 'it-queueless-pushable';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { UnexpectedEOFError } from './errors.js';\n/**\n * @deprecated This will not be exported in a future release\n */\nexport class CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * @deprecated This will not be exported in a future release\n */\nexport class AbortError extends CodeError {\n type;\n constructor(message) {\n super(message, 'ABORT_ERR');\n this.type = 'aborted';\n this.name = 'AbortError';\n }\n}\nexport function byteStream(duplex, opts) {\n const write = queuelessPushable();\n duplex.sink(write).catch(async (err) => {\n await write.end(err);\n });\n duplex.sink = async (source) => {\n for await (const buf of source) {\n await write.push(buf);\n }\n await write.end();\n };\n let source = duplex.source;\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]();\n }\n else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]();\n }\n const readBuffer = new Uint8ArrayList();\n const W = {\n read: async (bytes, options) => {\n options?.signal?.throwIfAborted();\n let listener;\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'));\n };\n options?.signal?.addEventListener('abort', listener);\n });\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n return new Uint8ArrayList();\n }\n return value;\n }\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n throw new UnexpectedEOFError('unexpected end of input');\n }\n readBuffer.append(value);\n }\n const buf = readBuffer.sublist(0, bytes);\n readBuffer.consume(bytes);\n return buf;\n }\n finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener);\n }\n }\n },\n write: async (data, options) => {\n options?.signal?.throwIfAborted();\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options);\n }\n else {\n await write.push(data.subarray(), options);\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source;\n duplex.source = (async function* () {\n if (opts?.yieldBytes === false) {\n yield readBuffer;\n }\n else {\n yield* readBuffer;\n }\n yield* originalStream;\n }());\n }\n return duplex;\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","/**\n * The reported length of the next data message was not a positive integer\n */\nexport class InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nexport class InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nexport class InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\nimport { byteStream } from 'it-byte-stream';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { InvalidDataLengthError, InvalidDataLengthLengthError, InvalidMessageLengthError } from './errors.js';\nexport function lpStream(duplex, opts = {}) {\n const bytes = byteStream(duplex, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = varint.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? varint.decode;\n const encodeLength = opts?.lengthEncoder ?? varint.encode;\n const W = {\n read: async (options) => {\n let dataLength = -1;\n const lengthBuffer = new Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options));\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (dataLength < 0) {\n throw new InvalidMessageLengthError('Invalid message length');\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new InvalidDataLengthLengthError('message length length too long');\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new InvalidDataLengthError('message length too long');\n }\n return bytes.read(dataLength, options);\n },\n write: async (data, options) => {\n // encode, write\n await bytes.write(new Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n writeV: async (data, options) => {\n const list = new Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap: () => {\n return bytes.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","import defer from 'p-defer';\n/**\n * A pair of streams where one drains from the other\n */\nexport function pair() {\n const deferred = defer();\n let piped = false;\n return {\n sink: async (source) => {\n if (piped) {\n throw new Error('already piped');\n }\n piped = true;\n deferred.resolve(source);\n },\n source: (async function* () {\n const source = await deferred.promise;\n yield* source;\n }())\n };\n}\n//# sourceMappingURL=index.js.map","export const NOISE_MSG_MAX_LENGTH_BYTES = 65535;\nexport const NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG = NOISE_MSG_MAX_LENGTH_BYTES - 16;\nexport const DUMP_SESSION_KEYS = Boolean(globalThis.process?.env?.DUMP_SESSION_KEYS);\n//# sourceMappingURL=constants.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexport function isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr) => new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n else if (isBytes(data))\n data = copyBytes(data);\n else\n throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts == null || typeof opts !== 'object')\n throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n// For runtime check if class implements interface\nexport class Hash {\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = (params, c) => {\n Object.assign(c, params);\n return c;\n};\n// Polyfill for Safari 14\nexport function setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\nexport function u64Lengths(ciphertext, AAD) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\nexport function copyBytes(bytes) {\n return Uint8Array.from(bytes);\n}\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n//# sourceMappingURL=utils.js.map","// Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\nimport { bool as abool, bytes as abytes, number as anumber } from './_assert.js';\nimport { checkOpts, clean, copyBytes, u32 } from './utils.js';\n/*\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n const counter = new Uint8Array(4);\n chacha(..., counter, ...); // counter is now 1\n chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n salsa20: s[0] | k(4) | s[1] | nonce(2) | ctr(2) | s[2] | k(4) | s[3]\n chacha: s(4) | k(8) | ctr(1) | nonce(3)\n chacha20orig: s(4) | k(8) | ctr(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n*/\n// We can't make top-level var depend on utils.utf8ToBytes\n// because it's not present in all envs. Creating a similar fn here\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split('').map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes('expand 16-byte k');\nconst sigma32 = _utf8ToBytes('expand 32-byte k');\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\nexport const sigma = sigma32_32.slice();\nexport function rotl(a, b) {\n return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32]) // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = new Uint32Array();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n const len = data.length;\n const block = new Uint8Array(BLOCK_LEN);\n const b32 = u32(block);\n // Make sure that buffers aligned to 4 bytes\n const isAligned = isAligned32(data) && isAligned32(output);\n const d32 = isAligned ? u32(data) : U32_EMPTY;\n const o32 = isAligned ? u32(output) : U32_EMPTY;\n for (let pos = 0; pos < len; counter++) {\n core(sigma, key, nonce, b32, counter, rounds);\n if (counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n const take = Math.min(BLOCK_LEN, len - pos);\n // aligned to 4 bytes\n if (isAligned && take === BLOCK_LEN) {\n const pos32 = pos / 4;\n if (pos % 4 !== 0)\n throw new Error('arx: invalid block position');\n for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n posj = pos32 + j;\n o32[posj] = d32[posj] ^ b32[j];\n }\n pos += BLOCK_LEN;\n continue;\n }\n for (let j = 0, posj; j < take; j++) {\n posj = pos + j;\n output[posj] = data[posj] ^ block[j];\n }\n pos += take;\n }\n}\nexport function createCipher(core, opts) {\n const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);\n if (typeof core !== 'function')\n throw new Error('core must be a function');\n anumber(counterLength);\n anumber(rounds);\n abool(counterRight);\n abool(allowShortKeys);\n return (key, nonce, data, output, counter = 0) => {\n abytes(key);\n abytes(nonce);\n abytes(data);\n const len = data.length;\n if (output === undefined)\n output = new Uint8Array(len);\n abytes(output);\n anumber(counter);\n if (counter < 0 || counter >= MAX_COUNTER)\n throw new Error('arx: counter overflow');\n if (output.length < len)\n throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n const toClean = [];\n // Key & sigma\n // key=16 -> sigma16, k=key|key\n // key=32 -> sigma32, k=key\n let l = key.length, k, sigma;\n if (l === 32) {\n toClean.push((k = copyBytes(key)));\n sigma = sigma32_32;\n }\n else if (l === 16 && allowShortKeys) {\n k = new Uint8Array(32);\n k.set(key);\n k.set(key, 16);\n sigma = sigma16_32;\n toClean.push(k);\n }\n else {\n throw new Error(`arx: invalid 32-byte key, got length=${l}`);\n }\n // Nonce\n // salsa20: 8 (8-byte counter)\n // chacha20orig: 8 (8-byte counter)\n // chacha20: 12 (4-byte counter)\n // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)\n // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)\n // Align nonce to 4 bytes\n if (!isAligned32(nonce))\n toClean.push((nonce = copyBytes(nonce)));\n const k32 = u32(k);\n // hsalsa & hchacha: handle extended nonce\n if (extendNonceFn) {\n if (nonce.length !== 24)\n throw new Error(`arx: extended nonce must be 24 bytes`);\n extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n nonce = nonce.subarray(16);\n }\n // Handle nonce counter\n const nonceNcLen = 16 - counterLength;\n if (nonceNcLen !== nonce.length)\n throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n // Pad counter when nonce is 64 bit\n if (nonceNcLen !== 12) {\n const nc = new Uint8Array(12);\n nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n nonce = nc;\n toClean.push(nonce);\n }\n const n32 = u32(nonce);\n runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n clean(...toClean);\n return output;\n };\n}\n//# sourceMappingURL=_arx.js.map","import { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\nimport { clean, toBytes } from './utils.js';\n// Poly1305 is a fast and parallel secret-key message-authentication code.\n// https://cr.yp.to/mac.html, https://cr.yp.to/mac/poly1305-20050329.pdf\n// https://datatracker.ietf.org/doc/html/rfc8439\n// Based on Public Domain poly1305-donna https://github.com/floodyberry/poly1305-donna\nconst u8to16 = (a, i) => (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\nclass Poly1305 {\n constructor(key) {\n this.blockLen = 16;\n this.outputLen = 16;\n this.buffer = new Uint8Array(16);\n this.r = new Uint16Array(10);\n this.h = new Uint16Array(10);\n this.pad = new Uint16Array(8);\n this.pos = 0;\n this.finished = false;\n key = toBytes(key);\n abytes(key, 32);\n const t0 = u8to16(key, 0);\n const t1 = u8to16(key, 2);\n const t2 = u8to16(key, 4);\n const t3 = u8to16(key, 6);\n const t4 = u8to16(key, 8);\n const t5 = u8to16(key, 10);\n const t6 = u8to16(key, 12);\n const t7 = u8to16(key, 14);\n // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n this.r[0] = t0 & 0x1fff;\n this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n this.r[5] = (t4 >>> 1) & 0x1ffe;\n this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n this.r[9] = (t7 >>> 5) & 0x007f;\n for (let i = 0; i < 8; i++)\n this.pad[i] = u8to16(key, 16 + 2 * i);\n }\n process(data, offset, isLast = false) {\n const hibit = isLast ? 0 : 1 << 11;\n const { h, r } = this;\n const r0 = r[0];\n const r1 = r[1];\n const r2 = r[2];\n const r3 = r[3];\n const r4 = r[4];\n const r5 = r[5];\n const r6 = r[6];\n const r7 = r[7];\n const r8 = r[8];\n const r9 = r[9];\n const t0 = u8to16(data, offset + 0);\n const t1 = u8to16(data, offset + 2);\n const t2 = u8to16(data, offset + 4);\n const t3 = u8to16(data, offset + 6);\n const t4 = u8to16(data, offset + 8);\n const t5 = u8to16(data, offset + 10);\n const t6 = u8to16(data, offset + 12);\n const t7 = u8to16(data, offset + 14);\n let h0 = h[0] + (t0 & 0x1fff);\n let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n let h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n let h9 = h[9] + ((t7 >>> 5) | hibit);\n let c = 0;\n let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);\n c = d0 >>> 13;\n d0 &= 0x1fff;\n d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);\n c += d0 >>> 13;\n d0 &= 0x1fff;\n let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);\n c = d1 >>> 13;\n d1 &= 0x1fff;\n d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);\n c += d1 >>> 13;\n d1 &= 0x1fff;\n let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n c = d2 >>> 13;\n d2 &= 0x1fff;\n d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);\n c += d2 >>> 13;\n d2 &= 0x1fff;\n let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n c = d3 >>> 13;\n d3 &= 0x1fff;\n d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);\n c += d3 >>> 13;\n d3 &= 0x1fff;\n let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n c = d4 >>> 13;\n d4 &= 0x1fff;\n d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);\n c += d4 >>> 13;\n d4 &= 0x1fff;\n let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n c = d5 >>> 13;\n d5 &= 0x1fff;\n d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);\n c += d5 >>> 13;\n d5 &= 0x1fff;\n let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n c = d6 >>> 13;\n d6 &= 0x1fff;\n d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n c += d6 >>> 13;\n d6 &= 0x1fff;\n let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n c = d7 >>> 13;\n d7 &= 0x1fff;\n d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n c += d7 >>> 13;\n d7 &= 0x1fff;\n let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n c = d8 >>> 13;\n d8 &= 0x1fff;\n d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n c += d8 >>> 13;\n d8 &= 0x1fff;\n let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n c = d9 >>> 13;\n d9 &= 0x1fff;\n d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n c += d9 >>> 13;\n d9 &= 0x1fff;\n c = ((c << 2) + c) | 0;\n c = (c + d0) | 0;\n d0 = c & 0x1fff;\n c = c >>> 13;\n d1 += c;\n h[0] = d0;\n h[1] = d1;\n h[2] = d2;\n h[3] = d3;\n h[4] = d4;\n h[5] = d5;\n h[6] = d6;\n h[7] = d7;\n h[8] = d8;\n h[9] = d9;\n }\n finalize() {\n const { h, pad } = this;\n const g = new Uint16Array(10);\n let c = h[1] >>> 13;\n h[1] &= 0x1fff;\n for (let i = 2; i < 10; i++) {\n h[i] += c;\n c = h[i] >>> 13;\n h[i] &= 0x1fff;\n }\n h[0] += c * 5;\n c = h[0] >>> 13;\n h[0] &= 0x1fff;\n h[1] += c;\n c = h[1] >>> 13;\n h[1] &= 0x1fff;\n h[2] += c;\n g[0] = h[0] + 5;\n c = g[0] >>> 13;\n g[0] &= 0x1fff;\n for (let i = 1; i < 10; i++) {\n g[i] = h[i] + c;\n c = g[i] >>> 13;\n g[i] &= 0x1fff;\n }\n g[9] -= 1 << 13;\n let mask = (c ^ 1) - 1;\n for (let i = 0; i < 10; i++)\n g[i] &= mask;\n mask = ~mask;\n for (let i = 0; i < 10; i++)\n h[i] = (h[i] & mask) | g[i];\n h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n let f = h[0] + pad[0];\n h[0] = f & 0xffff;\n for (let i = 1; i < 8; i++) {\n f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n h[i] = f & 0xffff;\n }\n clean(g);\n }\n update(data) {\n aexists(this);\n const { buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input\n if (take === blockLen) {\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(data, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(buffer, 0, false);\n this.pos = 0;\n }\n }\n return this;\n }\n destroy() {\n clean(this.h, this.r, this.buffer, this.pad);\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { buffer, h } = this;\n let { pos } = this;\n if (pos) {\n buffer[pos++] = 1;\n for (; pos < 16; pos++)\n buffer[pos] = 0;\n this.process(buffer, 0, true);\n }\n this.finalize();\n let opos = 0;\n for (let i = 0; i < 8; i++) {\n out[opos++] = h[i] >>> 0;\n out[opos++] = h[i] >>> 8;\n }\n return out;\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n}\nexport function wrapConstructorWithKey(hashCons) {\n const hashC = (msg, key) => hashCons(key).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(32));\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key) => hashCons(key);\n return hashC;\n}\nexport const poly1305 = wrapConstructorWithKey((key) => new Poly1305(key));\n//# sourceMappingURL=_poly1305.js.map","// prettier-ignore\nimport { createCipher, rotl } from './_arx.js';\nimport { bytes as abytes } from './_assert.js';\nimport { poly1305 } from './_poly1305.js';\nimport { clean, createView, equalBytes, setBigUint64, wrapCipher, } from './utils.js';\n// ChaCha20 stream cipher was released in 2008. ChaCha aims to increase\n// the diffusion per round, but had slightly less cryptanalysis.\n// https://cr.yp.to/chacha.html, http://cr.yp.to/chacha/chacha-20080128.pdf\n/**\n * ChaCha core function.\n */\n// prettier-ignore\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\" \"nd 3\" \"2-by\" \"te k\"\n y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key\n y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key\n y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Counter\tNonce Nonce\n // Save state to temporary variables\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n for (let r = 0; r < rounds; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n // Write output\n let oi = 0;\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\n/**\n * hchacha helper method, used primarily in xchacha, to hash\n * key and nonce into key' and nonce'.\n * Same as chachaCore, but there doesn't seem to be a way to move the block\n * out without 25% performance hit.\n */\n// prettier-ignore\nexport function hchacha(s, k, i, o32) {\n let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];\n for (let r = 0; r < 20; r += 2) {\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 16);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 12);\n x00 = (x00 + x04) | 0;\n x12 = rotl(x12 ^ x00, 8);\n x08 = (x08 + x12) | 0;\n x04 = rotl(x04 ^ x08, 7);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 16);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 12);\n x01 = (x01 + x05) | 0;\n x13 = rotl(x13 ^ x01, 8);\n x09 = (x09 + x13) | 0;\n x05 = rotl(x05 ^ x09, 7);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 16);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 12);\n x02 = (x02 + x06) | 0;\n x14 = rotl(x14 ^ x02, 8);\n x10 = (x10 + x14) | 0;\n x06 = rotl(x06 ^ x10, 7);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 16);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 12);\n x03 = (x03 + x07) | 0;\n x15 = rotl(x15 ^ x03, 8);\n x11 = (x11 + x15) | 0;\n x07 = rotl(x07 ^ x11, 7);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 16);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 12);\n x00 = (x00 + x05) | 0;\n x15 = rotl(x15 ^ x00, 8);\n x10 = (x10 + x15) | 0;\n x05 = rotl(x05 ^ x10, 7);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 16);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 12);\n x01 = (x01 + x06) | 0;\n x12 = rotl(x12 ^ x01, 8);\n x11 = (x11 + x12) | 0;\n x06 = rotl(x06 ^ x11, 7);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 16);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 12);\n x02 = (x02 + x07) | 0;\n x13 = rotl(x13 ^ x02, 8);\n x08 = (x08 + x13) | 0;\n x07 = rotl(x07 ^ x08, 7);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 16);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 12);\n x03 = (x03 + x04) | 0;\n x14 = rotl(x14 ^ x03, 8);\n x09 = (x09 + x14) | 0;\n x04 = rotl(x04 ^ x09, 7);\n }\n let oi = 0;\n o32[oi++] = x00;\n o32[oi++] = x01;\n o32[oi++] = x02;\n o32[oi++] = x03;\n o32[oi++] = x12;\n o32[oi++] = x13;\n o32[oi++] = x14;\n o32[oi++] = x15;\n}\n/**\n * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter.\n */\nexport const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n allowShortKeys: true,\n});\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n allowShortKeys: false,\n});\n/**\n * XChaCha eXtended-nonce ChaCha. 24-byte nonce.\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n */\nexport const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 8,\n extendNonceFn: hchacha,\n allowShortKeys: false,\n});\n/**\n * Reduced 8-round chacha, described in original paper.\n */\nexport const chacha8 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 8,\n});\n/**\n * Reduced 12-round chacha, described in original paper.\n */\nexport const chacha12 = /* @__PURE__ */ createCipher(chachaCore, {\n counterRight: false,\n counterLength: 4,\n rounds: 12,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n h.update(msg);\n const left = msg.length % 16;\n if (left)\n h.update(ZEROS16.subarray(left));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, data, AAD) {\n const authKey = fn(key, nonce, ZEROS32);\n const h = poly1305.create(authKey);\n if (AAD)\n updatePadded(h, AAD);\n updatePadded(h, data);\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(data.length), true);\n h.update(num);\n const res = h.digest();\n clean(authKey, num);\n return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them similar to:\n * https://github.com/paulmillr/scure-base/blob/b266c73dde977b1dd7ef40ef7a23cc15aab526b3/index.ts#L250\n * But it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n const tagLength = 16;\n abytes(key, 32);\n abytes(nonce);\n return {\n encrypt(plaintext, output) {\n const plength = plaintext.length;\n const clength = plength + tagLength;\n if (output) {\n abytes(output, clength);\n }\n else {\n output = new Uint8Array(clength);\n }\n xorStream(key, nonce, plaintext, output, 1);\n const tag = computeTag(xorStream, key, nonce, output.subarray(0, -tagLength), AAD);\n output.set(tag, plength); // append tag\n clean(tag);\n return output;\n },\n decrypt(ciphertext, output) {\n const clength = ciphertext.length;\n const plength = clength - tagLength;\n if (clength < tagLength)\n throw new Error(`encrypted data must be at least ${tagLength} bytes`);\n if (output) {\n abytes(output, plength);\n }\n else {\n output = new Uint8Array(plength);\n }\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = computeTag(xorStream, key, nonce, data, AAD);\n if (!equalBytes(passedTag, tag))\n throw new Error('invalid tag');\n xorStream(key, nonce, data, output, 1);\n clean(tag);\n return output;\n },\n };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n * With 12-byte nonce, it's not safe to use fill it with random (CSPRNG), due to collision chance.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n/**\n * XChaCha20-Poly1305 extended-nonce chacha.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha\n * With 24-byte nonce, it's safe to use fill it with random (CSPRNG).\n */\nexport const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, _poly1305_aead(xchacha20));\n//# sourceMappingURL=chacha.js.map","/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\nimport { ahash, anumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { toBytes } from './utils.js';\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nexport function extract(hash, ikm, salt) {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return hmac(hash, toBytes(salt), toBytes(ikm));\n}\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nexport function expand(hash, prk, info, length = 32) {\n ahash(hash);\n anumber(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nexport const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map","import { pureJsCrypto } from './js.js';\nexport const defaultCrypto = pureJsCrypto;\n//# sourceMappingURL=index.browser.js.map","import { chacha20poly1305 } from '@noble/ciphers/chacha';\nimport { x25519 } from '@noble/curves/ed25519';\nimport { extract, expand } from '@noble/hashes/hkdf';\nimport { sha256 } from '@noble/hashes/sha256';\nexport const pureJsCrypto = {\n hashSHA256(data) {\n return sha256(data.subarray());\n },\n getHKDF(ck, ikm) {\n const prk = extract(sha256, ikm, ck);\n const okmU8Array = expand(sha256, prk, undefined, 96);\n const okm = okmU8Array;\n const k1 = okm.subarray(0, 32);\n const k2 = okm.subarray(32, 64);\n const k3 = okm.subarray(64, 96);\n return [k1, k2, k3];\n },\n generateX25519KeyPair() {\n const secretKey = x25519.utils.randomPrivateKey();\n const publicKey = x25519.getPublicKey(secretKey);\n return {\n publicKey,\n privateKey: secretKey\n };\n },\n generateX25519KeyPairFromSeed(seed) {\n const publicKey = x25519.getPublicKey(seed);\n return {\n publicKey,\n privateKey: seed\n };\n },\n generateX25519SharedKey(privateKey, publicKey) {\n return x25519.getSharedSecret(privateKey.subarray(), publicKey.subarray());\n },\n chaCha20Poly1305Encrypt(plaintext, nonce, ad, k) {\n return chacha20poly1305(k, nonce, ad).encrypt(plaintext.subarray());\n },\n chaCha20Poly1305Decrypt(ciphertext, nonce, ad, k, dst) {\n return chacha20poly1305(k, nonce, ad).decrypt(ciphertext.subarray(), dst);\n }\n};\n//# sourceMappingURL=js.js.map","import {} from 'uint8arraylist';\nimport { allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc';\nexport const uint16BEEncode = (value) => {\n const target = uint8ArrayAllocUnsafe(2);\n target[0] = value >> 8;\n target[1] = value;\n return target;\n};\nuint16BEEncode.bytes = 2;\nexport const uint16BEDecode = (data) => {\n if (data.length < 2)\n throw RangeError('Could not decode int16BE');\n if (data instanceof Uint8Array) {\n let value = 0;\n value += data[0] << 8;\n value += data[1];\n return value;\n }\n return data.getUint16(0);\n};\nuint16BEDecode.bytes = 2;\n//# sourceMappingURL=encoder.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { DUMP_SESSION_KEYS } from './constants.js';\nexport function logLocalStaticKeys(s, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (s) {\n keyLogger(`LOCAL_STATIC_PUBLIC_KEY ${uint8ArrayToString(s.publicKey, 'hex')}`);\n keyLogger(`LOCAL_STATIC_PRIVATE_KEY ${uint8ArrayToString(s.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local static keys.');\n }\n}\nexport function logLocalEphemeralKeys(e, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (e) {\n keyLogger(`LOCAL_PUBLIC_EPHEMERAL_KEY ${uint8ArrayToString(e.publicKey, 'hex')}`);\n keyLogger(`LOCAL_PRIVATE_EPHEMERAL_KEY ${uint8ArrayToString(e.privateKey, 'hex')}`);\n }\n else {\n keyLogger('Missing local ephemeral keys.');\n }\n}\nexport function logRemoteStaticKey(rs, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (rs) {\n keyLogger(`REMOTE_STATIC_PUBLIC_KEY ${uint8ArrayToString(rs.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote static public key.');\n }\n}\nexport function logRemoteEphemeralKey(re, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n if (re) {\n keyLogger(`REMOTE_EPHEMERAL_PUBLIC_KEY ${uint8ArrayToString(re.subarray(), 'hex')}`);\n }\n else {\n keyLogger('Missing remote ephemeral keys.');\n }\n}\nexport function logCipherState(cs1, cs2, keyLogger) {\n if (!keyLogger.enabled || !DUMP_SESSION_KEYS) {\n return;\n }\n keyLogger(`CIPHER_STATE_1 ${cs1.n.getUint64()} ${cs1.k && uint8ArrayToString(cs1.k, 'hex')}`);\n keyLogger(`CIPHER_STATE_2 ${cs2.n.getUint64()} ${cs2.k && uint8ArrayToString(cs2.k, 'hex')}`);\n}\n//# sourceMappingURL=logger.js.map","export class InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\n//# sourceMappingURL=errors.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport const MIN_NONCE = 0;\n// For performance reasons, the nonce is represented as a JS `number`\n// Although JS `number` can safely represent integers up to 2 ** 53 - 1, we choose to only use\n// 4 bytes to store the data for performance reason.\n// This is a slight deviation from the noise spec, which describes the max nonce as 2 ** 64 - 2\n// The effect is that this implementation will need a new handshake to be performed after fewer messages are exchanged than other implementations with full uint64 nonces.\n// this MAX_NONCE is still a large number of messages, so the practical effect of this is negligible.\nexport const MAX_NONCE = 0xffffffff;\nconst ERR_MAX_NONCE = 'Cipherstate has reached maximum n, a new handshake must be performed';\n/**\n * The nonce is an uint that's increased over time.\n * Maintaining different representations help improve performance.\n */\nexport class Nonce {\n n;\n bytes;\n view;\n constructor(n = MIN_NONCE) {\n this.n = n;\n this.bytes = uint8ArrayAlloc(12);\n this.view = new DataView(this.bytes.buffer, this.bytes.byteOffset, this.bytes.byteLength);\n this.view.setUint32(4, n, true);\n }\n increment() {\n this.n++;\n // Even though we're treating the nonce as 8 bytes, RFC7539 specifies 12 bytes for a nonce.\n this.view.setUint32(4, this.n, true);\n }\n getBytes() {\n return this.bytes;\n }\n getUint64() {\n return this.n;\n }\n assertValue() {\n if (this.n > MAX_NONCE) {\n throw new Error(ERR_MAX_NONCE);\n }\n }\n}\n//# sourceMappingURL=nonce.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { InvalidCryptoExchangeError } from './errors.js';\nimport { Nonce } from './nonce.js';\n// Code in this file is a direct translation of a subset of the noise protocol https://noiseprotocol.org/noise.html,\n// agnostic to libp2p's usage of noise\nexport const ZEROLEN = uint8ArrayAlloc(0);\nexport class CipherState {\n k;\n n;\n crypto;\n constructor(crypto, k = undefined, n = 0) {\n this.crypto = crypto;\n this.k = k;\n this.n = new Nonce(n);\n }\n hasKey() {\n return Boolean(this.k);\n }\n encryptWithAd(ad, plaintext) {\n if (!this.hasKey()) {\n return plaintext;\n }\n this.n.assertValue();\n const e = this.crypto.encrypt(plaintext, this.n.getBytes(), ad, this.k);\n this.n.increment();\n return e;\n }\n decryptWithAd(ad, ciphertext, dst) {\n if (!this.hasKey()) {\n return ciphertext;\n }\n this.n.assertValue();\n const plaintext = this.crypto.decrypt(ciphertext, this.n.getBytes(), ad, this.k, dst);\n this.n.increment();\n return plaintext;\n }\n}\nexport class SymmetricState {\n cs;\n ck;\n h;\n crypto;\n constructor(crypto, protocolName) {\n this.crypto = crypto;\n const protocolNameBytes = uint8ArrayFromString(protocolName, 'utf-8');\n this.h = hashProtocolName(crypto, protocolNameBytes);\n this.ck = this.h;\n this.cs = new CipherState(crypto);\n }\n mixKey(ikm) {\n const [ck, tempK] = this.crypto.hkdf(this.ck, ikm);\n this.ck = ck;\n this.cs = new CipherState(this.crypto, tempK);\n }\n mixHash(data) {\n this.h = this.crypto.hash(new Uint8ArrayList(this.h, data));\n }\n encryptAndHash(plaintext) {\n const ciphertext = this.cs.encryptWithAd(this.h, plaintext);\n this.mixHash(ciphertext);\n return ciphertext;\n }\n decryptAndHash(ciphertext) {\n const plaintext = this.cs.decryptWithAd(this.h, ciphertext);\n this.mixHash(ciphertext);\n return plaintext;\n }\n split() {\n const [tempK1, tempK2] = this.crypto.hkdf(this.ck, ZEROLEN);\n return [new CipherState(this.crypto, tempK1), new CipherState(this.crypto, tempK2)];\n }\n}\nexport class AbstractHandshakeState {\n ss;\n s;\n e;\n rs;\n re;\n initiator;\n crypto;\n constructor(init) {\n const { crypto, protocolName, prologue, initiator, s, e, rs, re } = init;\n this.crypto = crypto;\n this.ss = new SymmetricState(crypto, protocolName);\n this.ss.mixHash(prologue);\n this.initiator = initiator;\n this.s = s;\n this.e = e;\n this.rs = rs;\n this.re = re;\n }\n writeE() {\n if (this.e) {\n throw new Error('ephemeral keypair is already set');\n }\n const e = this.crypto.generateKeypair();\n this.ss.mixHash(e.publicKey);\n this.e = e;\n return e.publicKey;\n }\n writeS() {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n return this.ss.encryptAndHash(this.s.publicKey);\n }\n writeEE() {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.re));\n }\n writeES() {\n if (this.initiator) {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n else {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n }\n writeSE() {\n if (this.initiator) {\n if (!this.s) {\n throw new Error('static keypair is not set');\n }\n if (!this.re) {\n throw new Error('remote ephemeral public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.s, this.re));\n }\n else {\n if (!this.e) {\n throw new Error('ephemeral keypair is not set');\n }\n if (!this.rs) {\n throw new Error('remote static public key is not set');\n }\n this.ss.mixKey(this.crypto.dh(this.e, this.rs));\n }\n }\n readE(message, offset = 0) {\n if (this.re) {\n throw new Error('remote ephemeral public key is already set');\n }\n if (message.byteLength < offset + 32) {\n throw new Error('message is not long enough');\n }\n this.re = message.sublist(offset, offset + 32);\n this.ss.mixHash(this.re);\n }\n readS(message, offset = 0) {\n if (this.rs) {\n throw new Error('remote static public key is already set');\n }\n const cipherLength = 32 + (this.ss.cs.hasKey() ? 16 : 0);\n if (message.byteLength < offset + cipherLength) {\n throw new Error('message is not long enough');\n }\n const temp = message.sublist(offset, offset + cipherLength);\n this.rs = this.ss.decryptAndHash(temp);\n return cipherLength;\n }\n readEE() {\n this.writeEE();\n }\n readES() {\n this.writeES();\n }\n readSE() {\n this.writeSE();\n }\n}\n/**\n * A IHandshakeState that's optimized for the XX pattern\n */\nexport class XXHandshakeState extends AbstractHandshakeState {\n // e\n writeMessageA(payload) {\n return new Uint8ArrayList(this.writeE(), this.ss.encryptAndHash(payload));\n }\n // e, ee, s, es\n writeMessageB(payload) {\n const e = this.writeE();\n this.writeEE();\n const encS = this.writeS();\n this.writeES();\n return new Uint8ArrayList(e, encS, this.ss.encryptAndHash(payload));\n }\n // s, se\n writeMessageC(payload) {\n const encS = this.writeS();\n this.writeSE();\n return new Uint8ArrayList(encS, this.ss.encryptAndHash(payload));\n }\n // e\n readMessageA(message) {\n try {\n this.readE(message);\n return this.ss.decryptAndHash(message.sublist(32));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 0 validation fail: ${e.message}`);\n }\n }\n // e, ee, s, es\n readMessageB(message) {\n try {\n this.readE(message);\n this.readEE();\n const consumed = this.readS(message, 32);\n this.readES();\n return this.ss.decryptAndHash(message.sublist(32 + consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 1 validation fail: ${e.message}`);\n }\n }\n // s, se\n readMessageC(message) {\n try {\n const consumed = this.readS(message);\n this.readSE();\n return this.ss.decryptAndHash(message.sublist(consumed));\n }\n catch (e) {\n throw new InvalidCryptoExchangeError(`handshake stage 2 validation fail: ${e.message}`);\n }\n }\n}\nfunction hashProtocolName(crypto, protocolName) {\n if (protocolName.length <= 32) {\n const h = uint8ArrayAlloc(32);\n h.set(protocolName);\n return h;\n }\n else {\n return crypto.hash(protocolName);\n }\n}\n//# sourceMappingURL=protocol.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var NoiseExtensions;\n(function (NoiseExtensions) {\n let _codec;\n NoiseExtensions.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.webtransportCerthashes != null) {\n for (const value of obj.webtransportCerthashes) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n webtransportCerthashes: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.webtransportCerthashes.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseExtensions.encode = (obj) => {\n return encodeMessage(obj, NoiseExtensions.codec());\n };\n NoiseExtensions.decode = (buf) => {\n return decodeMessage(buf, NoiseExtensions.codec());\n };\n})(NoiseExtensions || (NoiseExtensions = {}));\nexport var NoiseHandshakePayload;\n(function (NoiseHandshakePayload) {\n let _codec;\n NoiseHandshakePayload.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.identityKey != null && obj.identityKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.identityKey);\n }\n if ((obj.identitySig != null && obj.identitySig.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.identitySig);\n }\n if (obj.extensions != null) {\n w.uint32(34);\n NoiseExtensions.codec().encode(obj.extensions, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n identityKey: uint8ArrayAlloc(0),\n identitySig: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.identityKey = reader.bytes();\n break;\n }\n case 2: {\n obj.identitySig = reader.bytes();\n break;\n }\n case 4: {\n obj.extensions = NoiseExtensions.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n NoiseHandshakePayload.encode = (obj) => {\n return encodeMessage(obj, NoiseHandshakePayload.codec());\n };\n NoiseHandshakePayload.decode = (buf) => {\n return decodeMessage(buf, NoiseHandshakePayload.codec());\n };\n})(NoiseHandshakePayload || (NoiseHandshakePayload = {}));\n//# sourceMappingURL=payload.js.map","import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';\nimport { UnexpectedPeerError } from '@libp2p/interface';\nimport {} from 'uint8arraylist';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { NoiseHandshakePayload } from './proto/payload.js';\nexport async function createHandshakePayload(privateKey, staticPublicKey, extensions) {\n const identitySig = await privateKey.sign(getSignaturePayload(staticPublicKey));\n return NoiseHandshakePayload.encode({\n identityKey: publicKeyToProtobuf(privateKey.publicKey),\n identitySig,\n extensions\n });\n}\nexport async function decodeHandshakePayload(payloadBytes, remoteStaticKey, remoteIdentityKey) {\n try {\n const payload = NoiseHandshakePayload.decode(payloadBytes);\n const publicKey = publicKeyFromProtobuf(payload.identityKey);\n if (remoteIdentityKey?.equals(publicKey) === false) {\n throw new Error(`Payload identity key ${publicKey} does not match expected remote identity key ${remoteIdentityKey}`);\n }\n if (!remoteStaticKey) {\n throw new Error('Remote static does not exist');\n }\n const signaturePayload = getSignaturePayload(remoteStaticKey);\n if (!(await publicKey.verify(signaturePayload, payload.identitySig))) {\n throw new Error('Invalid payload signature');\n }\n return payload;\n }\n catch (e) {\n throw new UnexpectedPeerError(e.message);\n }\n}\nexport function getSignaturePayload(publicKey) {\n const prefix = uint8ArrayFromString('noise-libp2p-static-key:');\n if (publicKey instanceof Uint8Array) {\n return uint8ArrayConcat([prefix, publicKey], prefix.length + publicKey.length);\n }\n publicKey.prepend(prefix);\n return publicKey;\n}\n//# sourceMappingURL=utils.js.map","import { publicKeyFromProtobuf } from '@libp2p/crypto/keys';\nimport { serviceCapabilities } from '@libp2p/interface';\nimport { peerIdFromPublicKey } from '@libp2p/peer-id';\nimport { decode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { duplexPair } from 'it-pair/duplex';\nimport { pipe } from 'it-pipe';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { NOISE_MSG_MAX_LENGTH_BYTES } from './constants.js';\nimport { defaultCrypto } from './crypto/index.js';\nimport { wrapCrypto } from './crypto.js';\nimport { uint16BEDecode, uint16BEEncode } from './encoder.js';\nimport { registerMetrics } from './metrics.js';\nimport { performHandshakeInitiator, performHandshakeResponder } from './performHandshake.js';\nimport { decryptStream, encryptStream } from './streaming.js';\nexport class Noise {\n protocol = '/noise';\n crypto;\n prologue;\n staticKey;\n extensions;\n metrics;\n components;\n constructor(components, init = {}) {\n const { staticNoiseKey, extensions, crypto, prologueBytes } = init;\n const { metrics } = components;\n this.components = components;\n const _crypto = crypto ?? defaultCrypto;\n this.crypto = wrapCrypto(_crypto);\n this.extensions = extensions;\n this.metrics = metrics ? registerMetrics(metrics) : undefined;\n if (staticNoiseKey) {\n // accepts x25519 private key of length 32\n this.staticKey = _crypto.generateX25519KeyPairFromSeed(staticNoiseKey);\n }\n else {\n this.staticKey = _crypto.generateX25519KeyPair();\n }\n this.prologue = prologueBytes ?? uint8ArrayAlloc(0);\n }\n [Symbol.toStringTag] = '@chainsafe/libp2p-noise';\n [serviceCapabilities] = [\n '@libp2p/connection-encryption',\n '@chainsafe/libp2p-noise'\n ];\n /**\n * Encrypt outgoing data to the remote party (handshake as initiator)\n *\n * @param connection - streaming iterable duplex that will be encrypted\n * @param options\n * @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer\n * @param options.signal - Used to abort the operation\n */\n async secureOutbound(connection, options) {\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshakeInitiator(wrappedConnection, this.components.privateKey, options?.remotePeer?.publicKey, options);\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n const publicKey = publicKeyFromProtobuf(handshake.payload.identityKey);\n return {\n conn: connection,\n remoteExtensions: handshake.payload.extensions,\n remotePeer: peerIdFromPublicKey(publicKey)\n };\n }\n /**\n * Decrypt incoming data (handshake as responder).\n *\n * @param connection - streaming iterable duplex that will be encrypted\n * @param options\n * @param options.remotePeer - PeerId of the remote peer. Used to validate the integrity of the remote peer\n * @param options.signal - Used to abort the operation\n */\n async secureInbound(connection, options) {\n const wrappedConnection = lpStream(connection, {\n lengthEncoder: uint16BEEncode,\n lengthDecoder: uint16BEDecode,\n maxDataLength: NOISE_MSG_MAX_LENGTH_BYTES\n });\n const handshake = await this.performHandshakeResponder(wrappedConnection, this.components.privateKey, options?.remotePeer?.publicKey, options);\n const conn = await this.createSecureConnection(wrappedConnection, handshake);\n connection.source = conn.source;\n connection.sink = conn.sink;\n const publicKey = publicKeyFromProtobuf(handshake.payload.identityKey);\n return {\n conn: connection,\n remoteExtensions: handshake.payload.extensions,\n remotePeer: peerIdFromPublicKey(publicKey)\n };\n }\n /**\n * Perform XX handshake as initiator.\n */\n async performHandshakeInitiator(connection, \n // TODO: pass private key in noise constructor via Components\n privateKey, remoteIdentityKey, options) {\n let result;\n try {\n result = await performHandshakeInitiator({\n connection,\n privateKey,\n remoteIdentityKey,\n log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: this.extensions\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n /**\n * Perform XX handshake as responder.\n */\n async performHandshakeResponder(connection, privateKey, remoteIdentityKey, options) {\n let result;\n try {\n result = await performHandshakeResponder({\n connection,\n privateKey,\n remoteIdentityKey,\n log: this.components.logger.forComponent('libp2p:noise:xxhandshake'),\n crypto: this.crypto,\n prologue: this.prologue,\n s: this.staticKey,\n extensions: this.extensions\n }, options);\n this.metrics?.xxHandshakeSuccesses.increment();\n }\n catch (e) {\n this.metrics?.xxHandshakeErrors.increment();\n throw e;\n }\n return result;\n }\n async createSecureConnection(connection, handshake) {\n // Create encryption box/unbox wrapper\n const [secure, user] = duplexPair();\n const network = connection.unwrap();\n await pipe(secure, // write to wrapper\n encryptStream(handshake, this.metrics), // encrypt data + prefix with message length\n network, // send to the remote peer\n (source) => decode(source, { lengthDecoder: uint16BEDecode }), // read message length prefix\n decryptStream(handshake, this.metrics), // decrypt the incoming data\n secure // pipe to the wrapper\n );\n return user;\n }\n}\n//# sourceMappingURL=noise.js.map","export function wrapCrypto(crypto) {\n return {\n generateKeypair: crypto.generateX25519KeyPair,\n dh: (keypair, publicKey) => crypto.generateX25519SharedKey(keypair.privateKey, publicKey).subarray(0, 32),\n encrypt: crypto.chaCha20Poly1305Encrypt,\n decrypt: crypto.chaCha20Poly1305Decrypt,\n hash: crypto.hashSHA256,\n hkdf: crypto.getHKDF\n };\n}\n//# sourceMappingURL=crypto.js.map","export function registerMetrics(metrics) {\n return {\n xxHandshakeSuccesses: metrics.registerCounter('libp2p_noise_xxhandshake_successes_total', {\n help: 'Total count of noise xxHandshakes successes_'\n }),\n xxHandshakeErrors: metrics.registerCounter('libp2p_noise_xxhandshake_error_total', {\n help: 'Total count of noise xxHandshakes errors'\n }),\n encryptedPackets: metrics.registerCounter('libp2p_noise_encrypted_packets_total', {\n help: 'Total count of noise encrypted packets successfully'\n }),\n decryptedPackets: metrics.registerCounter('libp2p_noise_decrypted_packets_total', {\n help: 'Total count of noise decrypted packets'\n }),\n decryptErrors: metrics.registerCounter('libp2p_noise_decrypt_errors_total', {\n help: 'Total count of noise decrypt errors'\n })\n };\n}\n//# sourceMappingURL=metrics.js.map","import { logLocalStaticKeys, logLocalEphemeralKeys, logRemoteEphemeralKey, logRemoteStaticKey, logCipherState } from './logger.js';\nimport { ZEROLEN, XXHandshakeState } from './protocol.js';\nimport { createHandshakePayload, decodeHandshakePayload } from './utils.js';\nexport async function performHandshakeInitiator(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remoteIdentityKey, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: true,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Initiator starting to send first message.');\n await connection.write(xx.writeMessageA(ZEROLEN), options);\n log.trace('Stage 0 - Initiator finished sending first message.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 1 - Initiator waiting to receive first message from responder...');\n const plaintext = xx.readMessageB(await connection.read(options));\n log.trace('Stage 1 - Initiator received the message.');\n logRemoteEphemeralKey(xx.re, log);\n logRemoteStaticKey(xx.rs, log);\n log.trace(\"Initiator going to check remote's signature...\");\n const receivedPayload = await decodeHandshakePayload(plaintext, xx.rs, remoteIdentityKey);\n log.trace('All good with the signature!');\n log.trace('Stage 2 - Initiator sending third handshake message.');\n await connection.write(xx.writeMessageC(payload), options);\n log.trace('Stage 2 - Initiator sent message with signed payload.');\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: receivedPayload,\n encrypt: (plaintext) => cs1.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs2.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\nexport async function performHandshakeResponder(init, options) {\n const { log, connection, crypto, privateKey, prologue, s, remoteIdentityKey, extensions } = init;\n const payload = await createHandshakePayload(privateKey, s.publicKey, extensions);\n const xx = new XXHandshakeState({\n crypto,\n protocolName: 'Noise_XX_25519_ChaChaPoly_SHA256',\n initiator: false,\n prologue,\n s\n });\n logLocalStaticKeys(xx.s, log);\n log.trace('Stage 0 - Responder waiting to receive first message.');\n xx.readMessageA(await connection.read(options));\n log.trace('Stage 0 - Responder received first message.');\n logRemoteEphemeralKey(xx.re, log);\n log.trace('Stage 1 - Responder sending out first message with signed payload and static key.');\n await connection.write(xx.writeMessageB(payload), options);\n log.trace('Stage 1 - Responder sent the second handshake message with signed payload.');\n logLocalEphemeralKeys(xx.e, log);\n log.trace('Stage 2 - Responder waiting for third handshake message...');\n const plaintext = xx.readMessageC(await connection.read(options));\n log.trace('Stage 2 - Responder received the message, finished handshake.');\n const receivedPayload = await decodeHandshakePayload(plaintext, xx.rs, remoteIdentityKey);\n const [cs1, cs2] = xx.ss.split();\n logCipherState(cs1, cs2, log);\n return {\n payload: receivedPayload,\n encrypt: (plaintext) => cs2.encryptWithAd(ZEROLEN, plaintext),\n decrypt: (ciphertext, dst) => cs1.decryptWithAd(ZEROLEN, ciphertext, dst)\n };\n}\n//# sourceMappingURL=performHandshake.js.map","import { pair } from './index.js';\n/**\n * Two duplex streams that are attached to each other\n */\nexport function duplexPair() {\n const a = pair();\n const b = pair();\n return [\n {\n source: a.source,\n sink: b.sink\n },\n {\n source: b.source,\n sink: a.sink\n }\n ];\n}\n//# sourceMappingURL=duplex.js.map","import { Uint8ArrayList } from 'uint8arraylist';\nimport { NOISE_MSG_MAX_LENGTH_BYTES, NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG } from './constants.js';\nimport { uint16BEEncode } from './encoder.js';\nconst CHACHA_TAG_LENGTH = 16;\n// Returns generator that encrypts payload from the user\nexport function encryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES_WITHOUT_TAG;\n if (end > chunk.length) {\n end = chunk.length;\n }\n let data;\n if (chunk instanceof Uint8Array) {\n data = handshake.encrypt(chunk.subarray(i, end));\n }\n else {\n data = handshake.encrypt(chunk.sublist(i, end));\n }\n metrics?.encryptedPackets.increment();\n yield new Uint8ArrayList(uint16BEEncode(data.byteLength), data);\n }\n }\n };\n}\n// Decrypt received payload to the user\nexport function decryptStream(handshake, metrics) {\n return async function* (source) {\n for await (const chunk of source) {\n for (let i = 0; i < chunk.length; i += NOISE_MSG_MAX_LENGTH_BYTES) {\n let end = i + NOISE_MSG_MAX_LENGTH_BYTES;\n if (end > chunk.length) {\n end = chunk.length;\n }\n if (end - CHACHA_TAG_LENGTH < i) {\n throw new Error('Invalid chunk');\n }\n const encrypted = chunk.sublist(i, end);\n // memory allocation is not cheap so reuse the encrypted Uint8Array\n // see https://github.com/ChainSafe/js-libp2p-noise/pull/242#issue-1422126164\n // this is ok because chacha20 reads bytes one by one and don't reread after that\n // it's also tested in https://github.com/ChainSafe/as-chacha20poly1305/pull/1/files#diff-25252846b58979dcaf4e41d47b3eadd7e4f335e7fb98da6c049b1f9cd011f381R48\n const dst = chunk.subarray(i, end - CHACHA_TAG_LENGTH);\n try {\n const plaintext = handshake.decrypt(encrypted, dst);\n metrics?.decryptedPackets.increment();\n yield plaintext;\n }\n catch (e) {\n metrics?.decryptErrors.increment();\n throw e;\n }\n }\n }\n };\n}\n//# sourceMappingURL=streaming.js.map","/**\n * @packageDocumentation\n *\n * This repository contains TypeScript implementation of noise protocol, an encryption protocol used in libp2p.\n *\n * ## Usage\n *\n * Install with `yarn add @chainsafe/libp2p-noise` or `npm i @chainsafe/libp2p-noise`.\n *\n * Example of using default noise configuration and passing it to the libp2p config:\n *\n * ```ts\n * import {createLibp2p} from \"libp2p\"\n * import {noise} from \"@chainsafe/libp2p-noise\"\n *\n * //custom noise configuration, pass it instead of `noise()`\n * //x25519 private key\n * const n = noise({ staticNoiseKey });\n *\n * const libp2p = await createLibp2p({\n * connectionEncrypters: [noise()],\n * //... other options\n * })\n * ```\n *\n * See the [NoiseInit](https://github.com/ChainSafe/js-libp2p-noise/blob/master/src/noise.ts#L22-L30) interface for noise configuration options.\n *\n * ## API\n *\n * This module exposes an implementation of the [ConnectionEncrypter](https://libp2p.github.io/js-libp2p/interfaces/_libp2p_interface.ConnectionEncrypter.html) interface.\n *\n * ## Bring your own crypto\n *\n * You can provide a custom crypto implementation (instead of the default, based on [@noble](https://paulmillr.com/noble/)) by adding a `crypto` field to the init argument passed to the `Noise` factory.\n *\n * The implementation must conform to the `ICryptoInterface`, defined in \n */\nimport { Noise } from './noise.js';\nexport { pureJsCrypto } from './crypto/js.js';\nexport function noise(init = {}) {\n return (components) => new Noise(components, init);\n}\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');\n//# sourceMappingURL=index.js.map","import { multiaddr } from '@multiformats/multiaddr';\n/*\n * Valid combinations\n */\nexport const DNS4 = base('dns4');\nexport const DNS6 = base('dns6');\nexport const DNSADDR = base('dnsaddr');\nexport const DNS = or(base('dns'), DNSADDR, DNS4, DNS6);\nexport const IP = or(base('ip4'), base('ip6'));\nexport const TCP = or(and(IP, base('tcp')), and(DNS, base('tcp')));\nexport const UDP = and(IP, base('udp'));\nexport const UTP = and(UDP, base('utp'));\nexport const QUIC = and(UDP, base('quic'));\nexport const QUICV1 = and(UDP, base('quic-v1'));\nconst _WebSockets = or(and(TCP, base('ws')), and(DNS, base('ws')));\nexport const WebSockets = or(and(_WebSockets, base('p2p')), _WebSockets);\nconst _WebSocketsSecure = or(and(TCP, base('wss')), and(DNS, base('wss')), and(TCP, base('tls'), base('ws')), and(DNS, base('tls'), base('ws')));\nexport const WebSocketsSecure = or(and(_WebSocketsSecure, base('p2p')), _WebSocketsSecure);\nexport const HTTP = or(and(TCP, base('http')), and(IP, base('http')), and(DNS, base('http')));\nexport const HTTPS = or(and(TCP, base('https')), and(IP, base('https')), and(DNS, base('https')));\nconst _WebRTCDirect = and(UDP, base('webrtc-direct'), base('certhash'));\nexport const WebRTCDirect = or(and(_WebRTCDirect, base('p2p')), _WebRTCDirect);\nconst _WebTransport = and(QUICV1, base('webtransport'), base('certhash'), base('certhash'));\nexport const WebTransport = or(and(_WebTransport, base('p2p')), _WebTransport);\n/**\n * @deprecated\n */\nexport const P2PWebRTCStar = or(and(WebSockets, base('p2p-webrtc-star'), base('p2p')), and(WebSocketsSecure, base('p2p-webrtc-star'), base('p2p')), and(WebSockets, base('p2p-webrtc-star')), and(WebSocketsSecure, base('p2p-webrtc-star')));\nexport const WebSocketStar = or(and(WebSockets, base('p2p-websocket-star'), base('p2p')), and(WebSocketsSecure, base('p2p-websocket-star'), base('p2p')), and(WebSockets, base('p2p-websocket-star')), and(WebSocketsSecure, base('p2p-websocket-star')));\n/**\n * @deprecated\n */\nexport const P2PWebRTCDirect = or(and(HTTP, base('p2p-webrtc-direct'), base('p2p')), and(HTTPS, base('p2p-webrtc-direct'), base('p2p')), and(HTTP, base('p2p-webrtc-direct')), and(HTTPS, base('p2p-webrtc-direct')));\nexport const Reliable = or(_WebSockets, _WebSocketsSecure, HTTP, HTTPS, P2PWebRTCStar, P2PWebRTCDirect, TCP, UTP, QUIC, DNS, WebRTCDirect, WebTransport);\n// Unlike ws-star, stardust can run over any transport thus removing the requirement for websockets (but don't even think about running a stardust server over webrtc-star ;) )\nexport const Stardust = or(and(Reliable, base('p2p-stardust'), base('p2p')), and(Reliable, base('p2p-stardust')));\nconst _P2P = or(and(Reliable, base('p2p')), P2PWebRTCStar, P2PWebRTCDirect, WebRTCDirect, WebTransport, base('p2p'));\nconst _Circuit = or(and(_P2P, base('p2p-circuit'), _P2P), and(_P2P, base('p2p-circuit')), and(base('p2p-circuit'), _P2P), and(Reliable, base('p2p-circuit')), and(base('p2p-circuit'), Reliable), base('p2p-circuit'));\nconst CircuitRecursive = () => or(and(_Circuit, CircuitRecursive), _Circuit);\nexport const Circuit = CircuitRecursive();\nexport const P2P = or(and(Circuit, _P2P, Circuit), and(_P2P, Circuit), and(Circuit, _P2P), Circuit, _P2P);\nexport const IPFS = P2P;\nexport const WebRTC = or(and(Circuit, base('webrtc'), base('p2p')), and(Circuit, base('webrtc')), and(Reliable, base('webrtc'), base('p2p')), and(Reliable, base('webrtc')), base('webrtc'));\n/*\n * Validation funcs\n */\nfunction makeMatchesFunction(partialMatch) {\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const out = partialMatch(ma.protoNames());\n if (out === null) {\n return false;\n }\n if (out === true || out === false) {\n return out;\n }\n return out.length === 0;\n }\n return matches;\n}\nfunction and(...args) {\n function partialMatch(a) {\n if (a.length < args.length) {\n return null;\n }\n let out = a;\n args.some((arg) => {\n out = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (Array.isArray(out)) {\n a = out;\n }\n if (out === null) {\n return true;\n }\n return false;\n });\n return out;\n }\n return {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n}\nfunction or(...args) {\n function partialMatch(a) {\n let out = null;\n args.some((arg) => {\n const res = typeof arg === 'function'\n ? arg().partialMatch(a)\n : arg.partialMatch(a);\n if (res != null) {\n out = res;\n return true;\n }\n return false;\n });\n return out;\n }\n const result = {\n toString: function () { return '{ ' + args.join(' ') + ' }'; },\n input: args,\n matches: makeMatchesFunction(partialMatch),\n partialMatch\n };\n return result;\n}\nfunction base(n) {\n const name = n;\n function matches(a) {\n let ma;\n try {\n ma = multiaddr(a);\n }\n catch (err) { // catch error\n return false; // also if it's invalid it's probably not matching as well so return false\n }\n const pnames = ma.protoNames();\n if (pnames.length === 1 && pnames[0] === name) {\n return true;\n }\n return false;\n }\n function partialMatch(protos) {\n if (protos.length === 0) {\n return null;\n }\n if (protos[0] === name) {\n return protos.slice(1);\n }\n return null;\n }\n return {\n toString: function () { return name; },\n matches,\n partialMatch\n };\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\nimport { TypedEventEmitter, peerDiscoverySymbol, serviceCapabilities } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { P2P } from '@multiformats/mafmt';\nimport { multiaddr } from '@multiformats/multiaddr';\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap';\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000;\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends TypedEventEmitter {\n static tag = 'bootstrap';\n log;\n timer;\n list;\n timeout;\n components;\n _init;\n constructor(components, options = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses');\n }\n super();\n this.components = components;\n this.log = components.logger.forComponent('libp2p:bootstrap');\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT;\n this.list = [];\n for (const candidate of options.list) {\n if (!P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr');\n continue;\n }\n const ma = multiaddr(candidate);\n const peerIdStr = ma.getPeerId();\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id');\n continue;\n }\n const peerData = {\n id: peerIdFromString(peerIdStr),\n multiaddrs: [ma]\n };\n this.list.push(peerData);\n }\n this._init = options;\n }\n [peerDiscoverySymbol] = this;\n [Symbol.toStringTag] = '@libp2p/bootstrap';\n [serviceCapabilities] = [\n '@libp2p/peer-discovery'\n ];\n isStarted() {\n return Boolean(this.timer);\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted()) {\n return;\n }\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout);\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err);\n });\n }, this.timeout);\n }\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers() {\n if (this.timer == null) {\n return;\n }\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL\n }\n },\n multiaddrs: peerData.multiaddrs\n });\n // check we are still running\n if (this.timer == null) {\n return;\n }\n this.safeDispatchEvent('peer', { detail: peerData });\n this.components.connectionManager.openConnection(peerData.id)\n .catch(err => {\n this.log.error('could not dial bootstrap peer %p', peerData.id, err);\n });\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n this.timer = undefined;\n }\n}\nexport function bootstrap(init) {\n return (components) => new Bootstrap(components, init);\n}\n//# sourceMappingURL=index.js.map","// The domain string used for peer records contained in a Envelope.\nexport const ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nexport const ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n multiaddr: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.multiaddr = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return encodeMessage(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf, opts) => {\n return decodeMessage(buf, AddressInfo.codec(), opts);\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peerId: uint8ArrayAlloc(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.peerId = reader.bytes();\n break;\n }\n case 2: {\n obj.seq = reader.uint64();\n break;\n }\n case 3: {\n if (opts.limits?.addresses != null && obj.addresses.length === opts.limits.addresses) {\n throw new MaxLengthError('Decode error - map field \"addresses\" had too many elements');\n }\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.addresses$\n }));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return encodeMessage(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf, opts) => {\n return decodeMessage(buf, PeerRecord.codec(), opts);\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n publicKey: uint8ArrayAlloc(0),\n payloadType: uint8ArrayAlloc(0),\n payload: uint8ArrayAlloc(0),\n signature: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.publicKey = reader.bytes();\n break;\n }\n case 2: {\n obj.payloadType = reader.bytes();\n break;\n }\n case 3: {\n obj.payload = reader.bytes();\n break;\n }\n case 5: {\n obj.signature = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return encodeMessage(obj, Envelope.codec());\n };\n Envelope.decode = (buf, opts) => {\n return decodeMessage(buf, Envelope.codec(), opts);\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map","import { peerIdFromMultihash } from '@libp2p/peer-id';\nimport { arrayEquals } from '@libp2p/utils/array-equals';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport * as Digest from 'multiformats/hashes/digest';\nimport { ENVELOPE_DOMAIN_PEER_RECORD, ENVELOPE_PAYLOAD_TYPE_PEER_RECORD } from './consts.js';\nimport { PeerRecord as Protobuf } from './peer-record.js';\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nexport class PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = Protobuf.decode(buf);\n const peerId = peerIdFromMultihash(Digest.decode(peerRecord.peerId));\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => multiaddr(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n peerId: this.peerId.toMultihash().bytes,\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!arrayEquals(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nexport function arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map","/**\n * The key in the record is not valid for the domain\n */\nexport class InvalidSignatureError extends Error {\n constructor(message = 'Invalid signature') {\n super(message);\n this.name = 'InvalidSignatureError';\n }\n}\n//# sourceMappingURL=errors.js.map","import { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { fromString as uint8arraysFromString } from 'uint8arrays/from-string';\nimport { Envelope as Protobuf } from './envelope.js';\nimport { InvalidSignatureError } from './errors.js';\nexport class RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = Protobuf.decode(data);\n const publicKey = publicKeyFromProtobuf(envelopeData.publicKey);\n return new RecordEnvelope({\n publicKey,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, privateKey) => {\n if (privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const signature = await privateKey.sign(signData.subarray());\n return new RecordEnvelope({\n publicKey: privateKey.publicKey,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new InvalidSignatureError('Envelope signature is not valid for the given domain');\n }\n return envelope;\n };\n publicKey;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { publicKey, payloadType, payload, signature } = init;\n this.publicKey = publicKey;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = Protobuf.encode({\n publicKey: publicKeyToProtobuf(this.publicKey),\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return uint8ArrayEquals(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n return this.publicKey.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = uint8arraysFromString(domain);\n const domainLength = varint.encode(domainUint8Array.byteLength);\n const payloadTypeLength = varint.encode(payloadType.length);\n const payloadLength = varint.encode(payload.length);\n return new Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map","import { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { Netmask } from 'netmask';\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n];\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new Netmask(ipRange));\nfunction ipv4Check(ipAddr) {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr))\n return true;\n }\n return false;\n}\nfunction isIpv4MappedIpv6(ipAddr) {\n return /^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(ipAddr);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2\n */\nfunction ipv4MappedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n if (parts.length < 2) {\n return false;\n }\n const octet34 = parts[parts.length - 1].padStart(4, '0');\n const octet12 = parts[parts.length - 2].padStart(4, '0');\n const ip4 = `${parseInt(octet12.substring(0, 2), 16)}.${parseInt(octet12.substring(2), 16)}.${parseInt(octet34.substring(0, 2), 16)}.${parseInt(octet34.substring(2), 16)}`;\n return ipv4Check(ip4);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.2 example 3\n */\nfunction isIpv4EmbeddedIpv6(ipAddr) {\n return /^::ffff:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr);\n}\nfunction ipv4EmbeddedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n const ip4 = parts[parts.length - 1];\n return ipv4Check(ip4);\n}\nfunction ipv6Check(ipAddr) {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr);\n}\nexport function isPrivateIp(ip) {\n if (isIPv4(ip))\n return ipv4Check(ip);\n else if (isIpv4MappedIpv6(ip))\n return ipv4MappedIpv6Check(ip);\n else if (isIpv4EmbeddedIpv6(ip))\n return ipv4EmbeddedIpv6Check(ip);\n else if (isIPv6(ip))\n return ipv6Check(ip);\n else\n return undefined;\n}\n//# sourceMappingURL=private-ip.js.map","import { isPrivateIp } from '../private-ip.js';\nconst CODEC_IP4 = 0x04;\nconst CODEC_IP6 = 0x29;\nconst CODEC_DNS = 0x35;\nconst CODEC_DNS4 = 0x36;\nconst CODEC_DNS6 = 0x37;\nconst CODEC_DNSADDR = 0x38;\n/**\n * Check if a given multiaddr starts with a private address\n */\nexport function isPrivate(ma) {\n try {\n const [[codec, value]] = ma.stringTuples();\n if (value == null) {\n return true;\n }\n if (codec === CODEC_DNS || codec === CODEC_DNS4 || codec === CODEC_DNS6 || codec === CODEC_DNSADDR) {\n return false;\n }\n if (codec === CODEC_IP4 || codec === CODEC_IP6) {\n return isPrivateIp(value) ?? false;\n }\n }\n catch {\n }\n return true;\n}\n//# sourceMappingURL=is-private.js.map","import { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma) => {\n return ma.toString().split('/').slice(1);\n};\nexport const func = (fn) => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false;\n }\n if (fn(vals[0])) {\n return vals.slice(1);\n }\n return false;\n },\n pattern: 'fn'\n };\n};\nexport const literal = (str) => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n };\n};\nexport const string = () => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n };\n};\nexport const number = () => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n };\n};\nexport const peerId = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false;\n }\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n base58btc.decode(`z${vals[1]}`);\n }\n catch (err) {\n return false;\n }\n }\n else {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/p2p/{peerid}'\n };\n};\nexport const certhash = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'certhash') {\n return false;\n }\n try {\n base64url.decode(vals[1]);\n }\n catch {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/certhash/{certhash}'\n };\n};\nexport const optional = (matcher) => {\n return {\n match: (vals) => {\n const result = matcher.match(vals);\n if (result === false) {\n return vals;\n }\n return result;\n },\n pattern: `optional(${matcher.pattern})`\n };\n};\nexport const or = (...matchers) => {\n return {\n match: (vals) => {\n let matches;\n for (const matcher of matchers) {\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n continue;\n }\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result;\n }\n }\n if (matches == null) {\n return false;\n }\n return matches;\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nexport const and = (...matchers) => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n return false;\n }\n vals = result;\n }\n return vals;\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nexport function fmt(...matchers) {\n function match(ma) {\n let parts = toParts(ma);\n for (const matcher of matchers) {\n const result = matcher.match(parts);\n if (result === false) {\n return false;\n }\n parts = result;\n }\n return parts;\n }\n function matches(ma) {\n const result = match(ma);\n return result !== false;\n }\n function exactMatch(ma) {\n const result = match(ma);\n if (result === false) {\n return false;\n }\n return result.length === 0;\n }\n return {\n matchers,\n matches,\n exactMatch\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\nimport { isIPv4, isIPv6 } from '@chainsafe/is-ip';\nimport { and, or, literal, string, peerId, optional, fmt, func, number, certhash } from './utils.js';\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string());\nconst _DNS6 = and(literal('dns6'), string());\nconst _DNSADDR = and(literal('dnsaddr'), string());\nconst _DNS = and(literal('dns'), string());\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nexport const DNS4 = fmt(_DNS4, optional(peerId()));\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nexport const DNS6 = fmt(_DNS6, optional(peerId()));\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNSADDR = fmt(_DNSADDR, optional(peerId()));\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nexport const DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()));\nconst _IP4 = and(literal('ip4'), func(isIPv4));\nconst _IP6 = and(literal('ip6'), func(isIPv6));\nconst _IP = or(_IP4, _IP6);\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nexport const IP_OR_DOMAIN = fmt(or(_IP, and(or(_DNS, _DNSADDR, _DNS4, _DNS6), optional(peerId()))));\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nexport const IP4 = fmt(_IP4);\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nexport const IP6 = fmt(_IP6);\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nexport const IP = fmt(_IP);\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number());\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number());\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nexport const TCP = fmt(and(_TCP, optional(peerId())));\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nexport const UDP = fmt(_UDP);\nconst _QUIC = and(_UDP, literal('quic'), optional(peerId()));\nconst _QUICV1 = and(_UDP, literal('quic-v1'), optional(peerId()));\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1);\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nexport const QUIC = fmt(_QUIC);\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nexport const QUICV1 = fmt(_QUICV1);\nconst _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUICV1);\nconst _WebSockets = or(and(_WEB, literal('ws'), optional(peerId())));\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nexport const WebSockets = fmt(_WebSockets);\nconst _WebSocketsSecure = or(and(_WEB, literal('wss'), optional(peerId())), and(_WEB, literal('tls'), optional(and(literal('sni'), string())), literal('ws'), optional(peerId())));\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nexport const WebSocketsSecure = fmt(_WebSocketsSecure);\nconst _WebRTCDirect = and(_UDP, literal('webrtc-direct'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nexport const WebRTCDirect = fmt(_WebRTCDirect);\nconst _WebTransport = and(_QUICV1, literal('webtransport'), optional(certhash()), optional(certhash()), optional(peerId()));\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nexport const WebTransport = fmt(_WebTransport);\nconst _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(peerId())), and(QUIC_V0_OR_V1, optional(peerId())), and(_IP_OR_DOMAIN, optional(peerId())), _WebRTCDirect, _WebTransport, peerId());\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nexport const P2P = fmt(_P2P);\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId());\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nexport const Circuit = fmt(_Circuit);\nconst _WebRTC = or(and(_P2P, literal('p2p-circuit'), literal('webrtc'), optional(peerId())), and(_P2P, literal('webrtc'), optional(peerId())), and(literal('webrtc'), optional(peerId())));\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nexport const WebRTC = fmt(_WebRTC);\nconst _HTTP = or(and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('http'), optional(peerId())));\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nexport const HTTP = fmt(_HTTP);\nconst _HTTPS = or(and(_IP_OR_DOMAIN, literal('tcp'), or(and(literal('443'), literal('http')), and(number(), literal('https'))), optional(peerId())), and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('https'), optional(peerId())));\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nexport const HTTPS = fmt(_HTTPS);\nconst _Memory = or(and(literal('memory'), string(), optional(peerId())));\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nexport const Memory = fmt(_Memory);\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed Protobuf encoded\n * messages over streams.\n *\n * @example\n *\n * ```typescript\n * import { pbStream } from 'it-protobuf-stream'\n * import { MessageType } from './src/my-message-type.js'\n *\n * // RequestType and ResponseType have been generate from `.proto` files and have\n * // `.encode` and `.decode` methods for serialization/deserialization\n *\n * const stream = pbStream(duplex)\n *\n * // write a message to the stream\n * stream.write({\n * foo: 'bar'\n * }, MessageType)\n *\n * // read a message from the stream\n * const res = await stream.read(MessageType)\n * ```\n */\nimport { lpStream } from 'it-length-prefixed-stream';\nexport function pbStream(duplex, opts) {\n const lp = lpStream(duplex, opts);\n const W = {\n read: async (proto, options) => {\n // readLP, decode\n const value = await lp.read(options);\n return proto.decode(value);\n },\n write: async (message, proto, options) => {\n // encode, writeLP\n await lp.write(proto.encode(message), options);\n },\n writeV: async (messages, proto, options) => {\n // encode, writeLP\n await lp.writeV(messages.map(message => proto.encode(message)), options);\n },\n pb: (proto) => {\n return {\n read: async (options) => W.read(proto, options),\n write: async (d, options) => W.write(d, proto, options),\n writeV: async (d, options) => W.writeV(d, proto, options),\n unwrap: () => W\n };\n },\n unwrap: () => {\n return lp.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, message } from 'protons-runtime';\nexport var Identify;\n(function (Identify) {\n let _codec;\n Identify.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.protocolVersion != null) {\n w.uint32(42);\n w.string(obj.protocolVersion);\n }\n if (obj.agentVersion != null) {\n w.uint32(50);\n w.string(obj.agentVersion);\n }\n if (obj.publicKey != null) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if (obj.listenAddrs != null) {\n for (const value of obj.listenAddrs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (obj.observedAddr != null) {\n w.uint32(34);\n w.bytes(obj.observedAddr);\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(26);\n w.string(value);\n }\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(66);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n listenAddrs: [],\n protocols: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 5: {\n obj.protocolVersion = reader.string();\n break;\n }\n case 6: {\n obj.agentVersion = reader.string();\n break;\n }\n case 1: {\n obj.publicKey = reader.bytes();\n break;\n }\n case 2: {\n if (opts.limits?.listenAddrs != null && obj.listenAddrs.length === opts.limits.listenAddrs) {\n throw new MaxLengthError('Decode error - map field \"listenAddrs\" had too many elements');\n }\n obj.listenAddrs.push(reader.bytes());\n break;\n }\n case 4: {\n obj.observedAddr = reader.bytes();\n break;\n }\n case 3: {\n if (opts.limits?.protocols != null && obj.protocols.length === opts.limits.protocols) {\n throw new MaxLengthError('Decode error - map field \"protocols\" had too many elements');\n }\n obj.protocols.push(reader.string());\n break;\n }\n case 8: {\n obj.signedPeerRecord = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Identify.encode = (obj) => {\n return encodeMessage(obj, Identify.codec());\n };\n Identify.decode = (buf, opts) => {\n return decodeMessage(buf, Identify.codec(), opts);\n };\n})(Identify || (Identify = {}));\n//# sourceMappingURL=message.js.map","import detectElectron from 'is-electron'\n\nexport const isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nexport const isElectron = detectElectron()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nexport const isBrowser = isEnvWithDom && !isElectron\nexport const isElectronMain = isElectron && !isEnvWithDom\nexport const isElectronRenderer = isElectron && isEnvWithDom\nexport const isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nexport const isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nexport const isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nexport const isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n","import { publicKeyFromProtobuf } from '@libp2p/crypto/keys';\nimport { InvalidMessageError } from '@libp2p/interface';\nimport { peerIdFromCID, peerIdFromPublicKey } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe';\nimport { IDENTIFY_PROTOCOL_VERSION, MAX_IDENTIFY_MESSAGE_SIZE, MAX_PUSH_CONCURRENCY } from './consts.js';\nexport const defaultValues = {\n protocolPrefix: 'ipfs',\n timeout: 5000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxObservedAddresses: 10,\n maxMessageSize: MAX_IDENTIFY_MESSAGE_SIZE,\n runOnConnectionOpen: true,\n runOnSelfUpdate: true,\n runOnLimitedConnection: true,\n concurrency: MAX_PUSH_CONCURRENCY\n};\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nexport function getCleanMultiaddr(addr) {\n if (addr != null && addr.length > 0) {\n try {\n return multiaddr(addr);\n }\n catch {\n }\n }\n}\nexport function getAgentVersion(nodeInfo, agentVersion) {\n if (agentVersion != null) {\n return agentVersion;\n }\n agentVersion = `${nodeInfo.name}/${nodeInfo.version}`;\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (isNode || isElectronMain) {\n agentVersion += ` UserAgent=${globalThis.process.version}`;\n }\n else if (isBrowser || isWebWorker || isElectronRenderer || isReactNative) {\n agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`;\n }\n return agentVersion;\n}\nexport async function consumeIdentifyMessage(peerStore, events, log, connection, message) {\n log('received identify from %p', connection.remotePeer);\n if (message == null) {\n throw new InvalidMessageError('message was null or undefined');\n }\n const peer = {};\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: multiaddr(buf)\n }));\n }\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols;\n }\n if (message.publicKey != null) {\n const publicKey = publicKeyFromProtobuf(message.publicKey);\n const peerId = peerIdFromPublicKey(publicKey);\n if (!peerId.equals(connection.remotePeer)) {\n throw new InvalidMessageError('public key did not match remote PeerId');\n }\n peer.publicKey = publicKey;\n }\n let output;\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n log.trace('received signedPeerRecord from %p', connection.remotePeer);\n let peerRecordEnvelope = message.signedPeerRecord;\n const envelope = await RecordEnvelope.openAndCertify(peerRecordEnvelope, PeerRecord.DOMAIN);\n let peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n const envelopePeer = peerIdFromCID(envelope.publicKey.toCID());\n // Verify peerId\n if (!peerRecord.peerId.equals(envelopePeer)) {\n throw new InvalidMessageError('signing key does not match PeerId in the PeerRecord');\n }\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new InvalidMessageError('signing key does not match remote PeerId');\n }\n let existingPeer;\n try {\n existingPeer = await peerStore.get(peerRecord.peerId);\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n throw err;\n }\n }\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata;\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n peerRecord = storedRecord;\n peerRecordEnvelope = existingPeer.peerRecordEnvelope;\n }\n }\n }\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope;\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }));\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n };\n }\n else {\n log('%p did not send a signed peer record', connection.remotePeer);\n }\n log.trace('patching %p with', connection.remotePeer, peer);\n await peerStore.patch(connection.remotePeer, peer);\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata = {};\n if (message.agentVersion != null) {\n metadata.AgentVersion = uint8ArrayFromString(message.agentVersion);\n }\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = uint8ArrayFromString(message.protocolVersion);\n }\n log.trace('merging %p metadata', connection.remotePeer, metadata);\n await peerStore.merge(connection.remotePeer, {\n metadata\n });\n }\n const result = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => multiaddr(buf)),\n observedAddr: message.observedAddr == null ? undefined : multiaddr(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n };\n events.safeDispatchEvent('peer:identify', { detail: result });\n return result;\n}\nexport class AbstractIdentify {\n host;\n protocol;\n started;\n timeout;\n peerId;\n privateKey;\n peerStore;\n registrar;\n addressManager;\n maxInboundStreams;\n maxOutboundStreams;\n maxMessageSize;\n maxObservedAddresses;\n events;\n runOnLimitedConnection;\n log;\n constructor(components, init) {\n this.protocol = init.protocol;\n this.started = false;\n this.peerId = components.peerId;\n this.privateKey = components.privateKey;\n this.peerStore = components.peerStore;\n this.registrar = components.registrar;\n this.addressManager = components.addressManager;\n this.events = components.events;\n this.log = init.log;\n this.timeout = init.timeout ?? defaultValues.timeout;\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams;\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams;\n this.maxMessageSize = init.maxMessageSize ?? defaultValues.maxMessageSize;\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses;\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? defaultValues.runOnLimitedConnection;\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: getAgentVersion(components.nodeInfo, init.agentVersion)\n };\n }\n isStarted() {\n return this.started;\n }\n async start() {\n if (this.started) {\n return;\n }\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: uint8ArrayFromString(this.host.agentVersion),\n ProtocolVersion: uint8ArrayFromString(this.host.protocolVersion)\n }\n });\n await this.registrar.handle(this.protocol, (data) => {\n void this.handleProtocol(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n });\n this.started = true;\n }\n async stop() {\n await this.registrar.unhandle(this.protocol);\n this.started = false;\n }\n}\n//# sourceMappingURL=utils.js.map","export const PROTOCOL_VERSION = 'ipfs/0.1.0'; // deprecated\nexport const MULTICODEC_IDENTIFY = '/ipfs/id/1.0.0'; // deprecated\nexport const MULTICODEC_IDENTIFY_PUSH = '/ipfs/id/push/1.0.0'; // deprecated\nexport const IDENTIFY_PROTOCOL_VERSION = '0.1.0';\nexport const MULTICODEC_IDENTIFY_PROTOCOL_NAME = 'id';\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME = 'id/push';\nexport const MULTICODEC_IDENTIFY_PROTOCOL_VERSION = '1.0.0';\nexport const MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION = '1.0.0';\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nexport const MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8;\n// https://github.com/libp2p/go-libp2p/blob/0385ec924bad172f74a74db09939e97c079b1420/p2p/protocol/identify/id.go#L47C7-L47C25\nexport const MAX_PUSH_CONCURRENCY = 32;\n//# sourceMappingURL=consts.js.map","/* eslint-disable complexity */\nimport { publicKeyFromProtobuf, publicKeyToProtobuf } from '@libp2p/crypto/keys';\nimport { InvalidMessageError, UnsupportedProtocolError, serviceCapabilities, setMaxListeners } from '@libp2p/interface';\nimport { peerIdFromCID } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport { isGlobalUnicast } from '@libp2p/utils/multiaddr/is-global-unicast';\nimport { isPrivate } from '@libp2p/utils/multiaddr/is-private';\nimport { protocols } from '@multiformats/multiaddr';\nimport { IP_OR_DOMAIN, TCP } from '@multiformats/multiaddr-matcher';\nimport { pbStream } from 'it-protobuf-stream';\nimport { MULTICODEC_IDENTIFY_PROTOCOL_NAME, MULTICODEC_IDENTIFY_PROTOCOL_VERSION } from './consts.js';\nimport { Identify as IdentifyMessage } from './pb/message.js';\nimport { AbstractIdentify, consumeIdentifyMessage, defaultValues, getCleanMultiaddr } from './utils.js';\nconst CODEC_IP6 = 0x29;\nexport class Identify extends AbstractIdentify {\n constructor(components, init = {}) {\n super(components, {\n ...init,\n protocol: `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`,\n log: components.logger.forComponent('libp2p:identify')\n });\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail;\n this.identify(connection)\n .catch(err => {\n if (err.name === UnsupportedProtocolError.name) {\n // the remote did not support identify, ignore the error\n return;\n }\n this.log.error('error during identify trigged by connection:open', err);\n });\n });\n }\n }\n [serviceCapabilities] = [\n '@libp2p/identify'\n ];\n async _identify(connection, options = {}) {\n let stream;\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnLimitedConnection: this.runOnLimitedConnection\n });\n const pb = pbStream(stream, {\n maxDataLength: this.maxMessageSize\n }).pb(IdentifyMessage);\n const message = await pb.read(options);\n await stream.close(options);\n return message;\n }\n catch (err) {\n stream?.abort(err);\n throw err;\n }\n }\n async identify(connection, options = {}) {\n const message = await this._identify(connection, options);\n const { publicKey, protocols, observedAddr } = message;\n if (publicKey == null) {\n throw new InvalidMessageError('public key was missing from identify message');\n }\n const key = publicKeyFromProtobuf(publicKey);\n const id = peerIdFromCID(key.toCID());\n if (!connection.remotePeer.equals(id)) {\n throw new InvalidMessageError('identified peer does not match the expected peer');\n }\n if (this.peerId.equals(id)) {\n throw new InvalidMessageError('identified peer is our own peer id?');\n }\n // if the observed address is publicly routable, add it to the address\n // manager for verification via AutoNAT\n this.maybeAddObservedAddress(observedAddr);\n this.log('identify completed for peer %p and protocols %o', id, protocols);\n return consumeIdentifyMessage(this.peerStore, this.events, this.log, connection, message);\n }\n maybeAddObservedAddress(observedAddr) {\n const cleanObservedAddr = getCleanMultiaddr(observedAddr);\n if (cleanObservedAddr == null) {\n return;\n }\n this.log.trace('our observed address was %a', cleanObservedAddr);\n if (isPrivate(cleanObservedAddr)) {\n this.log.trace('our observed address was private');\n return;\n }\n const tuples = cleanObservedAddr.stringTuples();\n if (tuples[0][0] === CODEC_IP6 && !isGlobalUnicast(cleanObservedAddr)) {\n this.log.trace('our observed address was IPv6 but not a global unicast address');\n return;\n }\n if (TCP.exactMatch(cleanObservedAddr)) {\n // TODO: because socket dials can't use the same local port as the TCP\n // listener, many unique observed addresses are reported so ignore all\n // TCP addresses until https://github.com/libp2p/js-libp2p/issues/2620\n // is resolved\n return;\n }\n this.log.trace('storing the observed address');\n this.addressManager.addObservedAddr(cleanObservedAddr);\n }\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async handleProtocol(data) {\n const { connection, stream } = data;\n const signal = AbortSignal.timeout(this.timeout);\n setMaxListeners(Infinity, signal);\n try {\n const peerData = await this.peerStore.get(this.peerId);\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode(protocols('p2p').code));\n let signedPeerRecord = peerData.peerRecordEnvelope;\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new PeerRecord({\n peerId: this.peerId,\n multiaddrs\n });\n const envelope = await RecordEnvelope.seal(peerRecord, this.privateKey);\n signedPeerRecord = envelope.marshal().subarray();\n }\n let observedAddr = connection.remoteAddr.bytes;\n if (!IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined;\n }\n const pb = pbStream(stream).pb(IdentifyMessage);\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey: publicKeyToProtobuf(this.privateKey.publicKey),\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n this.log.error('could not respond to identify request', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=identify.js.map","import { cidrContains } from '@chainsafe/netmask';\nconst CODEC_IP6 = 0x29;\n/**\n * Check if a given multiaddr is an IPv6 global unicast address\n */\nexport function isGlobalUnicast(ma) {\n try {\n const [[codec, value]] = ma.stringTuples();\n if (value == null) {\n return false;\n }\n if (codec === CODEC_IP6) {\n return cidrContains('2000::/3', value);\n }\n }\n catch {\n }\n return false;\n}\n//# sourceMappingURL=is-global-unicast.js.map","import { IpNet } from \"./ipnet.js\";\nexport { ipToString } from \"./util.js\";\nexport { maskIp, iPv4FromIPv6, isIPv4mappedIPv6 } from \"./ip.js\";\nexport { IpNet } from \"./ipnet.js\";\nexport { parseCidr } from \"./cidr.js\";\n/**\n * Checks if cidr block contains ip address\n * @param cidr ipv4 or ipv6 formatted cidr . Example 198.51.100.14/24 or 2001:db8::/48\n * @param ip ipv4 or ipv6 address Example 198.51.100.14 or 2001:db8::\n *\n */\nexport function cidrContains(cidr, ip) {\n const ipnet = new IpNet(cidr);\n return ipnet.contains(ip);\n}\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Use the `identify` function to add support for the [Identify protocol](https://github.com/libp2p/specs/blob/master/identify/README.md) to libp2p.\n *\n * This protocol allows network peers to discover the multiaddrs the current node listens on, and the protocols it supports.\n *\n * A second function, `identifyPush` is also exported to add support for [identify/push](https://github.com/libp2p/specs/blob/master/identify/README.md#identifypush).\n *\n * This protocol will send updates to all connected peers when the multiaddrs or protocols of the current node change.\n *\n * > [!TIP]\n * > For maximum network compatibility you should configure both protocols\n *\n * @example Enabling identify\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identify } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identify: identify()\n * }\n * })\n * ```\n *\n * @example Enabling identify push\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { identifyPush } from '@libp2p/identify'\n *\n * const node = await createLibp2p({\n * // ...other options\n * services: {\n * identifyPush: identifyPush()\n * }\n * })\n * ```\n */\nimport { IdentifyPush as IdentifyPushClass } from './identify-push.js';\nimport { Identify as IdentifyClass } from './identify.js';\nexport function identify(init = {}) {\n return (components) => new IdentifyClass(components, init);\n}\nexport function identifyPush(init = {}) {\n return (components) => new IdentifyPushClass(components, init);\n}\n//# sourceMappingURL=index.js.map","import { getIterator } from 'get-iterator';\nimport { isPromise } from './is-promise.js';\nexport function closeSource(source, log) {\n const res = getIterator(source).return?.();\n if (isPromise(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err);\n });\n }\n}\n//# sourceMappingURL=close-source.js.map","export function getIterator(obj) {\n if (obj != null) {\n if (typeof obj[Symbol.iterator] === 'function') {\n return obj[Symbol.iterator]();\n }\n if (typeof obj[Symbol.asyncIterator] === 'function') {\n return obj[Symbol.asyncIterator]();\n }\n if (typeof obj.next === 'function') {\n return obj; // probably an iterator\n }\n }\n throw new Error('argument is not an iterator or iterable');\n}\n//# sourceMappingURL=index.js.map","export function isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=is-promise.js.map","// From https://github.com/sindresorhus/random-int/blob/c37741b56f76b9160b0b63dae4e9c64875128146/index.js#L13-L15\nconst randomInteger = (minimum, maximum) => Math.floor((Math.random() * (maximum - minimum + 1)) + minimum);\n\nconst createAbortError = () => {\n\tconst error = new Error('Delay aborted');\n\terror.name = 'AbortError';\n\treturn error;\n};\n\nconst clearMethods = new WeakMap();\n\nexport function createDelay({clearTimeout: defaultClear, setTimeout: defaultSet} = {}) {\n\t// We cannot use `async` here as we need the promise identity.\n\treturn (milliseconds, {value, signal} = {}) => {\n\t\t// TODO: Use `signal?.throwIfAborted()` when targeting Node.js 18.\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(createAbortError());\n\t\t}\n\n\t\tlet timeoutId;\n\t\tlet settle;\n\t\tlet rejectFunction;\n\t\tconst clear = defaultClear ?? clearTimeout;\n\n\t\tconst signalListener = () => {\n\t\t\tclear(timeoutId);\n\t\t\trejectFunction(createAbortError());\n\t\t};\n\n\t\tconst cleanup = () => {\n\t\t\tif (signal) {\n\t\t\t\tsignal.removeEventListener('abort', signalListener);\n\t\t\t}\n\t\t};\n\n\t\tconst delayPromise = new Promise((resolve, reject) => {\n\t\t\tsettle = () => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(value);\n\t\t\t};\n\n\t\t\trejectFunction = reject;\n\t\t\ttimeoutId = (defaultSet ?? setTimeout)(settle, milliseconds);\n\t\t});\n\n\t\tif (signal) {\n\t\t\tsignal.addEventListener('abort', signalListener, {once: true});\n\t\t}\n\n\t\tclearMethods.set(delayPromise, () => {\n\t\t\tclear(timeoutId);\n\t\t\ttimeoutId = null;\n\t\t\tsettle();\n\t\t});\n\n\t\treturn delayPromise;\n\t};\n}\n\nconst delay = createDelay();\n\nexport default delay;\n\nexport async function rangeDelay(minimum, maximum, options = {}) {\n\treturn delay(randomInteger(minimum, maximum), options);\n}\n\nexport function clearDelay(promise) {\n\tclearMethods.get(promise)?.();\n}\n","/**\n * A rate limit was hit\n */\nexport class RateLimitError extends Error {\n remainingPoints;\n msBeforeNext;\n consumedPoints;\n isFirstInDuration;\n constructor(message = 'Rate limit exceeded', props) {\n super(message);\n this.name = 'RateLimitError';\n this.remainingPoints = props.remainingPoints;\n this.msBeforeNext = props.msBeforeNext;\n this.consumedPoints = props.consumedPoints;\n this.isFirstInDuration = props.isFirstInDuration;\n }\n}\nexport class QueueFullError extends Error {\n static name = 'QueueFullError';\n constructor(message = 'The queue was full') {\n super(message);\n this.name = 'QueueFullError';\n }\n}\n//# sourceMappingURL=errors.js.map","import delay from 'delay';\nimport { RateLimitError } from './errors.js';\nexport class RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new RateLimitError('Rate limit exceeded', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await delay(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nexport class MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map","export var MessageTypes;\n(function (MessageTypes) {\n MessageTypes[MessageTypes[\"NEW_STREAM\"] = 0] = \"NEW_STREAM\";\n MessageTypes[MessageTypes[\"MESSAGE_RECEIVER\"] = 1] = \"MESSAGE_RECEIVER\";\n MessageTypes[MessageTypes[\"MESSAGE_INITIATOR\"] = 2] = \"MESSAGE_INITIATOR\";\n MessageTypes[MessageTypes[\"CLOSE_RECEIVER\"] = 3] = \"CLOSE_RECEIVER\";\n MessageTypes[MessageTypes[\"CLOSE_INITIATOR\"] = 4] = \"CLOSE_INITIATOR\";\n MessageTypes[MessageTypes[\"RESET_RECEIVER\"] = 5] = \"RESET_RECEIVER\";\n MessageTypes[MessageTypes[\"RESET_INITIATOR\"] = 6] = \"RESET_INITIATOR\";\n})(MessageTypes || (MessageTypes = {}));\nexport const MessageTypeNames = Object.freeze({\n 0: 'NEW_STREAM',\n 1: 'MESSAGE_RECEIVER',\n 2: 'MESSAGE_INITIATOR',\n 3: 'CLOSE_RECEIVER',\n 4: 'CLOSE_INITIATOR',\n 5: 'RESET_RECEIVER',\n 6: 'RESET_INITIATOR'\n});\nexport const InitiatorMessageTypes = Object.freeze({\n NEW_STREAM: MessageTypes.NEW_STREAM,\n MESSAGE: MessageTypes.MESSAGE_INITIATOR,\n CLOSE: MessageTypes.CLOSE_INITIATOR,\n RESET: MessageTypes.RESET_INITIATOR\n});\nexport const ReceiverMessageTypes = Object.freeze({\n MESSAGE: MessageTypes.MESSAGE_RECEIVER,\n CLOSE: MessageTypes.CLOSE_RECEIVER,\n RESET: MessageTypes.RESET_RECEIVER\n});\n//# sourceMappingURL=message-types.js.map","import { InvalidMessageError } from '@libp2p/interface';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { MessageTypeNames, MessageTypes } from './message-types.js';\nexport const MAX_MSG_SIZE = 1 << 20; // 1MB\nexport const MAX_MSG_QUEUE_SIZE = 4 << 20; // 4MB\nexport class Decoder {\n _buffer;\n _headerInfo;\n _maxMessageSize;\n _maxUnprocessedMessageQueueSize;\n constructor(maxMessageSize = MAX_MSG_SIZE, maxUnprocessedMessageQueueSize = MAX_MSG_QUEUE_SIZE) {\n this._buffer = new Uint8ArrayList();\n this._headerInfo = null;\n this._maxMessageSize = maxMessageSize;\n this._maxUnprocessedMessageQueueSize = maxUnprocessedMessageQueueSize;\n }\n write(chunk) {\n if (chunk == null || chunk.length === 0) {\n return [];\n }\n this._buffer.append(chunk);\n if (this._buffer.byteLength > this._maxUnprocessedMessageQueueSize) {\n throw new InvalidMessageError('Unprocessed message queue size too large!');\n }\n const msgs = [];\n while (this._buffer.length !== 0) {\n if (this._headerInfo == null) {\n try {\n this._headerInfo = this._decodeHeader(this._buffer);\n }\n catch (err) {\n if (err.name === 'InvalidMessageError') {\n throw err;\n }\n break; // We haven't received enough data yet\n }\n }\n const { id, type, length, offset } = this._headerInfo;\n const bufferedDataLength = this._buffer.length - offset;\n if (bufferedDataLength < length) {\n break; // not enough data yet\n }\n const msg = {\n id,\n type\n };\n if (type === MessageTypes.NEW_STREAM || type === MessageTypes.MESSAGE_INITIATOR || type === MessageTypes.MESSAGE_RECEIVER) {\n msg.data = this._buffer.sublist(offset, offset + length);\n }\n msgs.push(msg);\n this._buffer.consume(offset + length);\n this._headerInfo = null;\n }\n return msgs;\n }\n /**\n * Attempts to decode the message header from the buffer\n */\n _decodeHeader(data) {\n const { value: h, offset } = readVarInt(data);\n const { value: length, offset: end } = readVarInt(data, offset);\n const type = h & 7;\n // @ts-expect-error h is a number not a CODE\n if (MessageTypeNames[type] == null) {\n throw new Error(`Invalid type received: ${type}`);\n }\n // test message type varint + data length\n if (length > this._maxMessageSize) {\n throw new InvalidMessageError('Message size too large');\n }\n // @ts-expect-error h is a number not a CODE\n return { id: h >> 3, type, offset: offset + end, length };\n }\n}\nconst MSB = 0x80;\nconst REST = 0x7F;\nfunction readVarInt(buf, offset = 0) {\n let res = 0;\n let shift = 0;\n let counter = offset;\n let b;\n const l = buf.length;\n do {\n if (counter >= l || shift > 49) {\n offset = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf.get(counter++);\n res += shift < 28\n ? (b & REST) << shift\n : (b & REST) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB);\n offset = counter - offset;\n return {\n value: res,\n offset\n };\n}\n//# sourceMappingURL=decode.js.map","import * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { allocUnsafe } from 'uint8arrays/alloc';\nimport { MessageTypes } from './message-types.js';\nconst POOL_SIZE = 10 * 1024;\nclass Encoder {\n _pool;\n _poolOffset;\n constructor() {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n /**\n * Encodes the given message and adds it to the passed list\n */\n write(msg, list) {\n const pool = this._pool;\n let offset = this._poolOffset;\n varint.encode(msg.id << 3 | msg.type, pool, offset);\n offset += varint.encodingLength(msg.id << 3 | msg.type);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n varint.encode(msg.data.length, pool, offset);\n offset += varint.encodingLength(msg.data.length);\n }\n else {\n varint.encode(0, pool, offset);\n offset += varint.encodingLength(0);\n }\n const header = pool.subarray(this._poolOffset, offset);\n if (POOL_SIZE - offset < 100) {\n this._pool = allocUnsafe(POOL_SIZE);\n this._poolOffset = 0;\n }\n else {\n this._poolOffset = offset;\n }\n list.append(header);\n if ((msg.type === MessageTypes.NEW_STREAM || msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) && msg.data != null) {\n list.append(msg.data);\n }\n }\n}\nconst encoder = new Encoder();\n/**\n * Encode and yield one or more messages\n */\nexport async function* encode(source) {\n for await (const message of source) {\n const list = new Uint8ArrayList();\n encoder.write(message, list);\n yield list;\n }\n}\n//# sourceMappingURL=encode.js.map","/**\n * There was an error in the stream input buffer\n */\nexport class StreamInputBufferError extends Error {\n constructor(message = 'Stream input buffer error') {\n super(message);\n this.name = 'StreamInputBufferError';\n }\n}\n//# sourceMappingURL=errors.js.map","import { StreamResetError, StreamStateError } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport defer, {} from 'p-defer';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { closeSource } from './close-source.js';\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000;\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\nexport class AbstractStream {\n id;\n direction;\n timeline;\n protocol;\n metadata;\n source;\n status;\n readStatus;\n writeStatus;\n log;\n sinkController;\n sinkEnd;\n closed;\n endErr;\n streamSource;\n onEnd;\n onCloseRead;\n onCloseWrite;\n onReset;\n onAbort;\n sendCloseWriteTimeout;\n sendingData;\n constructor(init) {\n this.sinkController = new AbortController();\n this.sinkEnd = defer();\n this.closed = defer();\n this.log = init.log;\n // stream status\n this.status = 'open';\n this.readStatus = 'ready';\n this.writeStatus = 'ready';\n this.id = init.id;\n this.metadata = init.metadata ?? {};\n this.direction = init.direction;\n this.timeline = {\n open: Date.now()\n };\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT;\n this.onEnd = init.onEnd;\n this.onCloseRead = init?.onCloseRead;\n this.onCloseWrite = init?.onCloseWrite;\n this.onReset = init?.onReset;\n this.onAbort = init?.onAbort;\n this.source = this.streamSource = pushable({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err);\n }\n else {\n this.log.trace('source ended');\n }\n this.onSourceEnd(err);\n }\n });\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this);\n }\n async sink(source) {\n if (this.writeStatus !== 'ready') {\n throw new StreamStateError(`writable end state is \"${this.writeStatus}\" not \"ready\"`);\n }\n try {\n this.writeStatus = 'writing';\n const options = {\n signal: this.sinkController.signal\n };\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options);\n if (isPromise(res)) {\n await res;\n }\n }\n const abortListener = () => {\n closeSource(source, this.log);\n };\n try {\n this.sinkController.signal.addEventListener('abort', abortListener);\n this.log.trace('sink reading from source');\n for await (let data of source) {\n data = data instanceof Uint8Array ? new Uint8ArrayList(data) : data;\n const res = this.sendData(data, options);\n if (isPromise(res)) {\n this.sendingData = pDefer();\n await res;\n this.sendingData.resolve();\n this.sendingData = undefined;\n }\n }\n }\n finally {\n this.sinkController.signal.removeEventListener('abort', abortListener);\n }\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus);\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing';\n this.log.trace('send close write to remote');\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n });\n this.writeStatus = 'closed';\n }\n this.onSinkEnd();\n }\n catch (err) {\n this.log.trace('sink ended with error, calling abort with error', err);\n this.abort(err);\n throw err;\n }\n finally {\n this.log.trace('resolve sink end');\n this.sinkEnd.resolve();\n }\n }\n onSourceEnd(err) {\n if (this.timeline.closeRead != null) {\n return;\n }\n this.timeline.closeRead = Date.now();\n this.readStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseRead?.();\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('source ended, waiting for sink to end');\n }\n }\n onSinkEnd(err) {\n if (this.timeline.closeWrite != null) {\n return;\n }\n this.timeline.closeWrite = Date.now();\n this.writeStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseWrite?.();\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('sink ended, waiting for source to end');\n }\n }\n // Close for both Reading and Writing\n async close(options) {\n if (this.status !== 'open') {\n return;\n }\n this.log.trace('closing gracefully');\n this.status = 'closing';\n // wait for read and write ends to close\n await raceSignal(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal);\n this.status = 'closed';\n this.log.trace('closed gracefully');\n }\n async closeRead(options = {}) {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return;\n }\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus);\n const readStatus = this.readStatus;\n this.readStatus = 'closing';\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote');\n await this.sendCloseRead(options);\n }\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength);\n this.streamSource.end();\n }\n this.log.trace('closed readable end of stream');\n }\n async closeWrite(options = {}) {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return;\n }\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus);\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array');\n await raceSignal(this.sink([]), options.signal);\n }\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await raceSignal(this.sendingData.promise, options.signal);\n }\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink');\n this.sinkController.abort();\n await raceSignal(this.sinkEnd.promise, options.signal);\n }\n this.writeStatus = 'closed';\n this.log.trace('closed writable end of stream');\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n this.log('abort with error', err);\n // try to send a reset message\n this.log('try to send reset to remote');\n const res = this.sendReset();\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err);\n });\n }\n this.status = 'aborted';\n this.timeline.abort = Date.now();\n this._closeSinkAndSource(err);\n this.onAbort?.(err);\n }\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n const err = new StreamResetError('stream reset');\n this.status = 'reset';\n this.timeline.reset = Date.now();\n this._closeSinkAndSource(err);\n this.onReset?.();\n }\n _closeSinkAndSource(err) {\n this._closeSink(err);\n this._closeSource(err);\n }\n _closeSink(err) {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source');\n this.sinkController.abort();\n }\n this.onSinkEnd(err);\n }\n _closeSource(err) {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength);\n this.readStatus = 'closing';\n this.streamSource.end(err);\n }\n }\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite() {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed');\n return;\n }\n this.log.trace('remote close write');\n this._closeSource();\n }\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead() {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed');\n return;\n }\n this.log.trace('remote close read');\n this._closeSink();\n }\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed');\n return;\n }\n this.log.trace('stream destroyed');\n this._closeSinkAndSource();\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush(data) {\n this.streamSource.push(data);\n }\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength() {\n return this.streamSource.readableLength;\n }\n}\n//# sourceMappingURL=abstract-stream.js.map","import { AbstractStream } from '@libp2p/utils/abstract-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_MSG_SIZE } from './decode.js';\nimport { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js';\nexport class MplexStream extends AbstractStream {\n name;\n streamId;\n send;\n types;\n maxDataSize;\n constructor(init) {\n super(init);\n this.types = init.direction === 'outbound' ? InitiatorMessageTypes : ReceiverMessageTypes;\n this.send = init.send;\n this.name = init.name;\n this.streamId = init.streamId;\n this.maxDataSize = init.maxDataSize;\n }\n async sendNewStream() {\n await this.send({ id: this.streamId, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(this.name)) });\n }\n async sendData(data) {\n data = data.sublist();\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize);\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n });\n data.consume(toSend);\n }\n }\n async sendReset() {\n await this.send({ id: this.streamId, type: this.types.RESET });\n }\n async sendCloseWrite() {\n await this.send({ id: this.streamId, type: this.types.CLOSE });\n }\n async sendCloseRead() {\n // mplex does not support close read, only close write\n }\n}\nexport function createStream(options) {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options;\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name ?? id}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n });\n}\n//# sourceMappingURL=stream.js.map","import { TooManyOutboundProtocolStreamsError, MuxerClosedError } from '@libp2p/interface';\nimport { closeSource } from '@libp2p/utils/close-source';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { pipe } from 'it-pipe';\nimport { pushable } from 'it-pushable';\nimport { toString as uint8ArrayToString } from 'uint8arrays';\nimport { Decoder } from './decode.js';\nimport { encode } from './encode.js';\nimport { StreamInputBufferError } from './errors.js';\nimport { MessageTypes, MessageTypeNames } from './message-types.js';\nimport { createStream } from './stream.js';\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB\nconst DISCONNECT_THRESHOLD = 5;\nconst CLOSE_TIMEOUT = 500;\nfunction printMessage(msg) {\n const output = {\n ...msg,\n type: `${MessageTypeNames[msg.type]} (${msg.type})`\n };\n if (msg.type === MessageTypes.NEW_STREAM) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray());\n }\n if (msg.type === MessageTypes.MESSAGE_INITIATOR || msg.type === MessageTypes.MESSAGE_RECEIVER) {\n output.data = uint8ArrayToString(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16');\n }\n return output;\n}\nexport class MplexStreamMuxer {\n protocol = '/mplex/6.7.0';\n sink;\n source;\n log;\n _streamId;\n _streams;\n _init;\n _source;\n closeController;\n rateLimiter;\n closeTimeout;\n logger;\n constructor(components, init) {\n init = init ?? {};\n this.log = components.logger.forComponent('libp2p:mplex');\n this.logger = components.logger;\n this._streamId = 0;\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n };\n this._init = init;\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT;\n /**\n * An iterable sink\n */\n this.sink = this._createSink();\n /**\n * An iterable source\n */\n this._source = pushable({\n objectMode: true,\n onEnd: () => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy();\n }\n for (const stream of this._streams.receivers.values()) {\n stream.destroy();\n }\n }\n });\n this.source = pipe(this._source, source => encode(source));\n /**\n * Close controller\n */\n this.closeController = new AbortController();\n this.rateLimiter = new RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n });\n }\n /**\n * Returns a Map of streams and their ids\n */\n get streams() {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams = [];\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream);\n }\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream);\n }\n return streams;\n }\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream(name) {\n if (this.closeController.signal.aborted) {\n throw new MuxerClosedError('Muxer already closed');\n }\n const id = this._streamId++;\n name = name == null ? id.toString() : name.toString();\n const registry = this._streams.initiators;\n return this._newStream({ id, name, type: 'initiator', registry });\n }\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close(options) {\n if (this.closeController.signal.aborted) {\n return;\n }\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout);\n try {\n // try to gracefully close all streams\n await Promise.all(this.streams.map(async (s) => s.close({\n signal\n })));\n this._source.end();\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n });\n this.closeController.abort();\n }\n catch (err) {\n this.abort(err);\n }\n }\n abort(err) {\n if (this.closeController.signal.aborted) {\n return;\n }\n this.streams.forEach(s => { s.abort(err); });\n this.closeController.abort(err);\n }\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream(options) {\n const { id, name } = options;\n const registry = this._streams.receivers;\n return this._newStream({ id, name, type: 'receiver', registry });\n }\n _newStream(options) {\n const { id, name, type, registry } = options;\n this.log('new %s stream %s', type, id);\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new TooManyOutboundProtocolStreamsError('Too many outbound streams open');\n }\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`);\n }\n const send = async (msg) => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg));\n }\n this._source.push(msg);\n };\n const onEnd = () => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);\n registry.delete(id);\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream);\n }\n };\n const stream = createStream({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });\n registry.set(id, stream);\n return stream;\n }\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink() {\n const sink = async (source) => {\n const abortListener = () => {\n closeSource(source, this.log);\n };\n this.closeController.signal.addEventListener('abort', abortListener);\n try {\n const decoder = new Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg);\n }\n }\n this._source.end();\n }\n catch (err) {\n this.log('error in sink', err);\n this._source.end(err); // End the source with an error\n }\n finally {\n this.closeController.signal.removeEventListener('abort', abortListener);\n }\n };\n return sink;\n }\n async _handleIncoming(message) {\n const { id, type } = message;\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message));\n }\n // Create a new stream?\n if (message.type === MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open');\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: MessageTypes.RESET_RECEIVER\n });\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1);\n }\n catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'));\n return;\n }\n return;\n }\n const stream = this._newReceiverStream({ id, name: uint8ArrayToString(message.data instanceof Uint8Array ? message.data : message.data.subarray()) });\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream);\n }\n return;\n }\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;\n const stream = list.get(id);\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, MessageTypeNames[type]);\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1);\n }\n catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'));\n return;\n }\n return;\n }\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE;\n try {\n switch (type) {\n case MessageTypes.MESSAGE_INITIATOR:\n case MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === MessageTypes.MESSAGE_INITIATOR ? MessageTypes.RESET_RECEIVER : MessageTypes.RESET_INITIATOR\n });\n // Inform the stream consumer they are not fast enough\n throw new StreamInputBufferError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers');\n }\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data);\n break;\n case MessageTypes.CLOSE_INITIATOR:\n case MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite();\n break;\n case MessageTypes.RESET_INITIATOR:\n case MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset();\n break;\n default:\n this.log('unknown message type %s', type);\n }\n }\n catch (err) {\n this.log.error('error while processing message', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=mplex.js.map","/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\nimport { serviceCapabilities } from '@libp2p/interface';\nimport { MplexStreamMuxer } from './mplex.js';\nclass Mplex {\n protocol = '/mplex/6.7.0';\n _init;\n components;\n constructor(components, init = {}) {\n this.components = components;\n this._init = init;\n }\n [Symbol.toStringTag] = '@libp2p/mplex';\n [serviceCapabilities] = [\n '@libp2p/stream-multiplexing'\n ];\n createStreamMuxer(init = {}) {\n return new MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n });\n }\n}\n/**\n * @deprecated mplex is deprecated as it has no flow control. Please use yamux instead.\n */\nexport function mplex(init = {}) {\n return (components) => new Mplex(components, init);\n}\n//# sourceMappingURL=index.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { randomBytes as randB } from '@noble/hashes/utils';\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nexport default function randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new InvalidParametersError('random bytes length must be a Number bigger than 0');\n }\n return randB(length);\n}\n//# sourceMappingURL=random-bytes.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { AbortError, InvalidMessageError, ProtocolError, TimeoutError } from '@libp2p/interface';\nimport first from 'it-first';\nimport { pipe } from 'it-pipe';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { PROTOCOL_PREFIX, PROTOCOL_NAME, PING_LENGTH, PROTOCOL_VERSION, TIMEOUT, MAX_INBOUND_STREAMS, MAX_OUTBOUND_STREAMS } from './constants.js';\nexport class PingService {\n protocol;\n components;\n started;\n timeout;\n maxInboundStreams;\n maxOutboundStreams;\n runOnLimitedConnection;\n log;\n constructor(components, init = {}) {\n this.components = components;\n this.log = components.logger.forComponent('libp2p:ping');\n this.started = false;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? TIMEOUT;\n this.maxInboundStreams = init.maxInboundStreams ?? MAX_INBOUND_STREAMS;\n this.maxOutboundStreams = init.maxOutboundStreams ?? MAX_OUTBOUND_STREAMS;\n this.runOnLimitedConnection = init.runOnLimitedConnection ?? true;\n this.handleMessage = this.handleMessage.bind(this);\n }\n [Symbol.toStringTag] = '@libp2p/ping';\n async start() {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnLimitedConnection: this.runOnLimitedConnection\n });\n this.started = true;\n }\n async stop() {\n await this.components.registrar.unhandle(this.protocol);\n this.started = false;\n }\n isStarted() {\n return this.started;\n }\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage(data) {\n this.log('incoming ping from %p', data.connection.remotePeer);\n const { stream } = data;\n const start = Date.now();\n const signal = AbortSignal.timeout(this.timeout);\n signal.addEventListener('abort', () => {\n stream?.abort(new TimeoutError('ping timeout'));\n });\n void pipe(stream, async function* (source) {\n let received = 0;\n for await (const buf of source) {\n received += buf.byteLength;\n if (received > PING_LENGTH) {\n stream?.abort(new InvalidMessageError('Too much data received'));\n return;\n }\n yield buf;\n }\n }, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);\n stream?.abort(err);\n })\n .finally(() => {\n const ms = Date.now() - start;\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms);\n });\n }\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping(peer, options = {}) {\n this.log('pinging %p', peer);\n const start = Date.now();\n const data = randomBytes(PING_LENGTH);\n const connection = await this.components.connectionManager.openConnection(peer, options);\n let stream;\n let onAbort = () => { };\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnLimitedConnection: this.runOnLimitedConnection\n });\n onAbort = () => {\n stream?.abort(new AbortError());\n };\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true });\n const result = await pipe([data], stream, async (source) => first(source));\n const ms = Date.now() - start;\n if (result == null) {\n throw new ProtocolError(`Did not receive a ping ack after ${ms}ms`);\n }\n if (!uint8ArrayEquals(data, result.subarray())) {\n throw new ProtocolError(`Received wrong ping ack after ${ms}ms`);\n }\n this.log('ping %p complete in %dms', connection.remotePeer, ms);\n return ms;\n }\n catch (err) {\n this.log.error('error while pinging %p', connection.remotePeer, err);\n stream?.abort(err);\n throw err;\n }\n finally {\n options.signal?.removeEventListener('abort', onAbort);\n if (stream != null) {\n await stream.close();\n }\n }\n }\n}\n//# sourceMappingURL=ping.js.map","export const PING_PROTOCOL = '/ipfs/ping/1.0.0';\nexport const PING_LENGTH = 32;\nexport const PROTOCOL_VERSION = '1.0.0';\nexport const PROTOCOL_NAME = 'ping';\nexport const PROTOCOL_PREFIX = 'ipfs';\nexport const TIMEOUT = 10000;\n// See https://github.com/libp2p/specs/blob/d4b5fb0152a6bb86cfd9ea/ping/ping.md?plain=1#L38-L43\n// The dialing peer MUST NOT keep more than one outbound stream for the ping protocol per peer.\n// The listening peer SHOULD accept at most two streams per peer since cross-stream behavior is\n// non-linear and stream writes occur asynchronously. The listening peer may perceive the\n// dialing peer closing and opening the wrong streams (for instance, closing stream B and\n// opening stream A even though the dialing peer is opening stream B and closing stream A).\nexport const MAX_INBOUND_STREAMS = 2;\nexport const MAX_OUTBOUND_STREAMS = 1;\n//# sourceMappingURL=constants.js.map","/**\n * @packageDocumentation\n *\n * Return the first value in an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import first from 'it-first'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const res = first(values)\n *\n * console.info(res) // 0\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import first from 'it-first'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const res = await first(values())\n *\n * console.info(res) // 0\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction first(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n })();\n }\n for (const entry of source) { // eslint-disable-line no-unreachable-loop\n return entry;\n }\n return undefined;\n}\nexport default first;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * The ping service implements the [libp2p ping spec](https://github.com/libp2p/specs/blob/master/ping/ping.md) allowing you to make a latency measurement to a remote peer.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n * import { ping } from '@libp2p/ping'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * services: {\n * ping: ping()\n * }\n * })\n *\n * const rtt = await node.services.ping.ping(multiaddr('/ip4/...'))\n *\n * console.info(rtt)\n * ```\n */\nimport { PingService as PingServiceClass } from './ping.js';\nexport function ping(init = {}) {\n return (components) => new PingServiceClass(components, init);\n}\nexport { PING_PROTOCOL } from './constants.js';\n//# sourceMappingURL=index.js.map","export const transportSymbol = Symbol.for('@libp2p/transport');\nexport function isTransport(other) {\n return other != null && Boolean(other[transportSymbol]);\n}\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nexport var FaultTolerance;\n(function (FaultTolerance) {\n /**\n * should be used for failing in any listen circumstance\n */\n FaultTolerance[FaultTolerance[\"FATAL_ALL\"] = 0] = \"FATAL_ALL\";\n /**\n * should be used for not failing when not listening\n */\n FaultTolerance[FaultTolerance[\"NO_FATAL\"] = 1] = \"NO_FATAL\";\n})(FaultTolerance || (FaultTolerance = {}));\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\nimport { multiaddr, protocols } from '@multiformats/multiaddr';\nconst ASSUME_HTTP_CODES = [\n protocols('tcp').code,\n protocols('dns').code,\n protocols('dnsaddr').code,\n protocols('dns4').code,\n protocols('dns6').code\n];\nfunction extractSNI(ma) {\n return extractTuple('sni', ma)?.[1];\n}\nfunction extractPort(ma) {\n const port = extractTuple('tcp', ma)?.[1];\n if (port == null) {\n return '';\n }\n return `:${port}`;\n}\nfunction extractTuple(name, ma) {\n let code;\n try {\n code = protocols(name).code;\n }\n catch (e) {\n // No support for protocol in multiaddr\n return;\n }\n for (const [proto, value] of ma) {\n if (proto === code && value != null) {\n return [proto, value];\n }\n }\n}\nfunction hasTLS(ma) {\n return ma.some(([proto, _]) => proto === protocols('tls').code);\n}\nfunction interpretNext(headProtoCode, headProtoVal, restMa) {\n const interpreter = interpreters[protocols(headProtoCode).name];\n if (interpreter == null) {\n throw new Error(`Can't interpret protocol ${protocols(headProtoCode).name}`);\n }\n const restVal = interpreter(headProtoVal, restMa);\n if (headProtoCode === protocols('ip6').code) {\n return `[${restVal}]`;\n }\n return restVal;\n}\nconst interpreters = {\n ip4: (value, restMa) => value,\n ip6: (value, restMa) => {\n if (restMa.length === 0) {\n return value;\n }\n return `[${value}]`;\n },\n tcp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n udp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n dnsaddr: (value, restMa) => value,\n dns4: (value, restMa) => value,\n dns6: (value, restMa) => value,\n dns: (value, restMa) => value,\n ipfs: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}`;\n },\n p2p: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}`;\n },\n http: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n const port = extractPort(restMa);\n if (maHasTLS && sni != null) {\n return `https://${sni}${port}`;\n }\n const protocol = maHasTLS ? 'https://' : 'http://';\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n 'http-path': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n const baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n const decodedValue = decodeURIComponent(value);\n return `${baseVal}/${decodedValue}`;\n },\n tls: (value, restMa) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n sni: (value, restMa) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n https: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `https://${baseVal}`;\n },\n ws: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n const port = extractPort(restMa);\n if (maHasTLS && sni != null) {\n return `wss://${sni}${port}`;\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://';\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n wss: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `wss://${baseVal}`;\n }\n};\nexport function multiaddrToUri(input, opts) {\n const ma = multiaddr(input);\n const parts = ma.stringTuples();\n const head = parts.pop();\n if (head == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n const protocol = protocols(head[0]);\n const interpreter = interpreters[protocol.name];\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`);\n }\n let uri = interpreter(head[1] ?? '', parts);\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '');\n if (head[1] === '443') {\n uri = `https://${uri}`;\n }\n else {\n uri = `http://${uri}`;\n }\n }\n if (uri.startsWith('http://') || uri.startsWith('https://') || uri.startsWith('ws://') || uri.startsWith('wss://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString();\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1);\n }\n }\n return uri;\n}\n//# sourceMappingURL=index.js.map","export default async (socket) => {\n // if the socket is closing or closed, return end\n if (socket.readyState >= 2) {\n throw new Error('socket closed');\n }\n // if open, return\n if (socket.readyState === 1) {\n return;\n }\n await new Promise((resolve, reject) => {\n function cleanup() {\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('error', handleErr);\n }\n function handleOpen() {\n cleanup();\n resolve();\n }\n function handleErr(event) {\n cleanup();\n reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`));\n }\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('error', handleErr);\n });\n};\n//# sourceMappingURL=ready.js.map","import ready from './ready.js';\nexport default (socket, options) => {\n options = options ?? {};\n options.closeOnEnd = options.closeOnEnd !== false;\n const sink = async (source) => {\n for await (const data of source) {\n try {\n await ready(socket);\n }\n catch (err) {\n if (err.message === 'socket closed')\n break;\n throw err;\n }\n // the ready promise resolved without error but the socket was closing so\n // exit the loop and don't send data\n if (socket.readyState === socket.CLOSING || socket.readyState === socket.CLOSED) {\n break;\n }\n socket.send(data);\n }\n if (options.closeOnEnd != null && socket.readyState <= 1) {\n await new Promise((resolve, reject) => {\n socket.addEventListener('close', event => {\n if (event.wasClean || event.code === 1006) {\n resolve();\n }\n else {\n const err = Object.assign(new Error('ws error'), { event });\n reject(err);\n }\n });\n setTimeout(() => { socket.close(); });\n });\n }\n };\n return sink;\n};\n//# sourceMappingURL=sink.js.map","import { EventIterator } from 'event-iterator';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\n// copied from github.com/feross/buffer\n// Some ArrayBuffers are not passing the instanceof check, so we need to do a bit more work :(\nfunction isArrayBuffer(obj) {\n return (obj instanceof ArrayBuffer) ||\n (obj?.constructor?.name === 'ArrayBuffer' && typeof obj?.byteLength === 'number');\n}\nexport default (socket) => {\n socket.binaryType = 'arraybuffer';\n const connected = async () => {\n await new Promise((resolve, reject) => {\n if (isConnected) {\n resolve();\n return;\n }\n if (connError != null) {\n reject(connError);\n return;\n }\n const cleanUp = (cont) => {\n socket.removeEventListener('open', onOpen);\n socket.removeEventListener('error', onError);\n cont();\n };\n const onOpen = () => { cleanUp(resolve); };\n const onError = (event) => {\n cleanUp(() => { reject(event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`)); });\n };\n socket.addEventListener('open', onOpen);\n socket.addEventListener('error', onError);\n });\n };\n const source = (async function* () {\n const messages = new EventIterator(({ push, stop, fail }) => {\n const onMessage = (event) => {\n let data = null;\n if (typeof event.data === 'string') {\n data = uint8ArrayFromString(event.data);\n }\n if (isArrayBuffer(event.data)) {\n data = new Uint8Array(event.data);\n }\n if (event.data instanceof Uint8Array) {\n data = event.data;\n }\n if (data == null) {\n return;\n }\n push(data);\n };\n const onError = (event) => { fail(event.error ?? new Error('Socket error')); };\n socket.addEventListener('message', onMessage);\n socket.addEventListener('error', onError);\n socket.addEventListener('close', stop);\n return () => {\n socket.removeEventListener('message', onMessage);\n socket.removeEventListener('error', onError);\n socket.removeEventListener('close', stop);\n };\n }, { highWaterMark: Infinity });\n await connected();\n for await (const chunk of messages) {\n yield isArrayBuffer(chunk) ? new Uint8Array(chunk) : chunk;\n }\n }());\n let isConnected = socket.readyState === 1;\n let connError;\n socket.addEventListener('open', () => {\n isConnected = true;\n connError = null;\n });\n socket.addEventListener('close', () => {\n isConnected = false;\n connError = null;\n });\n socket.addEventListener('error', event => {\n if (!isConnected) {\n connError = event.error ?? new Error(`connect ECONNREFUSED ${socket.url}`);\n }\n });\n return Object.assign(source, {\n connected\n });\n};\n//# sourceMappingURL=source.js.map","/* eslint-env browser */\nexport default WebSocket;\n//# sourceMappingURL=web-socket.browser.js.map","const map = { 'http:': 'ws:', 'https:': 'wss:' };\nconst defaultProtocol = 'ws:';\nexport default (url, location) => {\n if (url.startsWith('//')) {\n url = `${location?.protocol ?? defaultProtocol}${url}`;\n }\n if (url.startsWith('/') && location != null) {\n const proto = location.protocol ?? defaultProtocol;\n const host = location.host;\n const port = location.port != null && host?.endsWith(`:${location.port}`) !== true ? `:${location.port}` : '';\n url = `${proto}//${host}${port}${url}`;\n }\n const wsUrl = new URL(url);\n for (const [httpProto, wsProto] of Object.entries(map)) {\n if (wsUrl.protocol === httpProto) {\n wsUrl.protocol = wsProto;\n }\n }\n return wsUrl;\n};\n//# sourceMappingURL=ws-url.js.map","// load websocket library if we are not in the browser\nimport duplex from './duplex.js';\nimport WebSocket from './web-socket.js';\nimport wsurl from './ws-url.js';\nexport function connect(addr, opts) {\n const location = typeof window === 'undefined' ? undefined : window.location;\n opts = opts ?? {};\n const url = wsurl(addr, location);\n // it's necessary to stringify the URL object otherwise react-native crashes\n const socket = new WebSocket(url.toString(), opts.websocket);\n return duplex(socket, opts);\n}\n//# sourceMappingURL=client.js.map","import sink from './sink.js';\nimport source from './source.js';\nexport default (socket, options) => {\n options = options ?? {};\n const connectedSource = source(socket);\n let remoteAddress = options.remoteAddress;\n let remotePort = options.remotePort;\n if (socket.url != null) {\n // only client->server sockets have urls, server->client connections do not\n try {\n const url = new URL(socket.url);\n remoteAddress = url.hostname;\n remotePort = parseInt(url.port, 10);\n }\n catch { }\n }\n if (remoteAddress == null || remotePort == null) {\n throw new Error('Remote connection did not have address and/or port');\n }\n const duplex = {\n sink: sink(socket, options),\n source: connectedSource,\n connected: async () => { await connectedSource.connected(); },\n close: async () => {\n if (socket.readyState === socket.CONNECTING || socket.readyState === socket.OPEN) {\n await new Promise((resolve) => {\n socket.addEventListener('close', () => {\n resolve();\n });\n socket.close();\n });\n }\n },\n destroy: () => {\n if (socket.terminate != null) {\n socket.terminate();\n }\n else {\n socket.close();\n }\n },\n remoteAddress,\n remotePort,\n socket\n };\n return duplex;\n};\n//# sourceMappingURL=duplex.js.map","/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nexport class CustomProgressEvent extends Event {\n type;\n detail;\n constructor(type, detail) {\n super(type);\n this.type = type;\n // @ts-expect-error detail may be undefined\n this.detail = detail;\n }\n}\n//# sourceMappingURL=index.js.map","import { WebSocketsSecure, WebSockets, DNS } from '@multiformats/multiaddr-matcher';\nexport function all(multiaddrs) {\n return multiaddrs.filter((ma) => {\n return WebSocketsSecure.exactMatch(ma) || WebSockets.exactMatch(ma);\n });\n}\nexport function wss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n return WebSocketsSecure.exactMatch(ma);\n });\n}\nexport function dnsWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n return DNS.matches(ma) && WebSocketsSecure.exactMatch(ma);\n });\n}\nexport function dnsWsOrWss(multiaddrs) {\n return multiaddrs.filter((ma) => {\n return DNS.matches(ma) && (WebSocketsSecure.exactMatch(ma) || WebSockets.exactMatch(ma));\n });\n}\n//# sourceMappingURL=filters.js.map","/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/dns4/example.com/tcp/9090/tls/ws')\n * await node.dial(ma)\n * ```\n */\nimport { transportSymbol, serviceCapabilities, ConnectionFailedError } from '@libp2p/interface';\nimport { multiaddrToUri as toUri } from '@multiformats/multiaddr-to-uri';\nimport { connect } from 'it-ws/client';\nimport pDefer from 'p-defer';\nimport { CustomProgressEvent } from 'progress-events';\nimport { raceSignal } from 'race-signal';\nimport * as filters from './filters.js';\nimport { createListener } from './listener.js';\nimport { socketToMaConn } from './socket-to-conn.js';\nclass WebSockets {\n log;\n init;\n logger;\n metrics;\n components;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:websockets');\n this.logger = components.logger;\n this.components = components;\n this.init = init;\n if (components.metrics != null) {\n this.metrics = {\n dialerEvents: components.metrics.registerCounterGroup('libp2p_websockets_dialer_events_total', {\n label: 'event',\n help: 'Total count of WebSockets dialer events by type'\n })\n };\n }\n }\n [transportSymbol] = true;\n [Symbol.toStringTag] = '@libp2p/websockets';\n [serviceCapabilities] = [\n '@libp2p/transport'\n ];\n async dial(ma, options) {\n this.log('dialing %s', ma);\n options = options ?? {};\n const socket = await this._connect(ma, options);\n const maConn = socketToMaConn(socket, ma, {\n logger: this.logger,\n metrics: this.metrics?.dialerEvents\n });\n this.log('new outbound connection %s', maConn.remoteAddr);\n const conn = await options.upgrader.upgradeOutbound(maConn, options);\n this.log('outbound connection %s upgraded', maConn.remoteAddr);\n return conn;\n }\n async _connect(ma, options) {\n options?.signal?.throwIfAborted();\n const cOpts = ma.toOptions();\n this.log('dialing %s:%s', cOpts.host, cOpts.port);\n const errorPromise = pDefer();\n const rawSocket = connect(toUri(ma), this.init);\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new ConnectionFailedError(`Could not connect to ${ma.toString()}`);\n this.log.error('connection error:', err);\n this.metrics?.dialerEvents.increment({ error: true });\n errorPromise.reject(err);\n });\n try {\n options.onProgress?.(new CustomProgressEvent('websockets:open-connection'));\n await raceSignal(Promise.race([rawSocket.connected(), errorPromise.promise]), options.signal);\n }\n catch (err) {\n if (options.signal?.aborted === true) {\n this.metrics?.dialerEvents.increment({ abort: true });\n }\n rawSocket.close()\n .catch(err => {\n this.log.error('error closing raw socket', err);\n });\n throw err;\n }\n this.log('connected %s', ma);\n this.metrics?.dialerEvents.increment({ connect: true });\n return rawSocket;\n }\n /**\n * Creates a WebSockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener(options) {\n return createListener({\n logger: this.logger,\n events: this.components.events,\n metrics: this.components.metrics\n }, {\n ...this.init,\n ...options\n });\n }\n /**\n * Takes a list of `Multiaddr`s and returns only valid WebSockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n listenFilter(multiaddrs) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs];\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs);\n }\n return filters.all(multiaddrs);\n }\n /**\n * Filter check for all Multiaddrs that this transport can dial\n */\n dialFilter(multiaddrs) {\n return this.listenFilter(multiaddrs);\n }\n}\nexport function webSockets(init = {}) {\n return (components) => {\n return new WebSockets(components, init);\n };\n}\n//# sourceMappingURL=index.js.map","import { AbortError } from '@libp2p/interface';\nimport { CLOSE_TIMEOUT } from './constants.js';\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nexport function socketToMaConn(stream, remoteAddr, options) {\n const log = options.logger.forComponent('libp2p:websockets:maconn');\n const metrics = options.metrics;\n const metricPrefix = options.metricPrefix ?? '';\n const maConn = {\n log,\n async sink(source) {\n try {\n await stream.sink((async function* () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf;\n }\n else {\n yield buf.subarray();\n }\n }\n })());\n }\n catch (err) {\n if (err.type !== 'aborted') {\n log.error(err);\n }\n }\n },\n source: stream.source,\n remoteAddr,\n timeline: { open: Date.now() },\n async close(options = {}) {\n const start = Date.now();\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n options = {\n ...options,\n signal\n };\n }\n const listener = () => {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s after %dms, destroying it manually', host, port, Date.now() - start);\n this.abort(new AbortError('Socket close timeout'));\n };\n options.signal?.addEventListener('abort', listener);\n try {\n await stream.close();\n }\n catch (err) {\n log.error('error closing WebSocket gracefully', err);\n this.abort(err);\n }\n finally {\n options.signal?.removeEventListener('abort', listener);\n maConn.timeline.close = Date.now();\n }\n },\n abort(err) {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s due to error', host, port, err);\n stream.destroy();\n maConn.timeline.close = Date.now();\n // ws WebSocket.terminate does not accept an Error arg to emit an 'error'\n // event on destroy like other node streams so we can't update a metric\n // with an event listener\n // https://github.com/websockets/ws/issues/1752#issuecomment-622380981\n metrics?.increment({ [`${metricPrefix}error`]: true });\n }\n };\n stream.socket.addEventListener('close', () => {\n metrics?.increment({ [`${metricPrefix}close`]: true });\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now();\n }\n }, { once: true });\n return maConn;\n}\n//# sourceMappingURL=socket-to-conn.js.map","// Time to wait for a connection to close gracefully before destroying it manually\nexport const CLOSE_TIMEOUT = 500;\n//# sourceMappingURL=constants.js.map","export function createListener() {\n throw new Error('WebSocket Servers can not be created in the browser!');\n}\n//# sourceMappingURL=listener.browser.js.map","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import lowerBound from './lower-bound.js';\nexport default class PriorityQueue {\n #queue = [];\n enqueue(run, options) {\n options = {\n priority: 0,\n ...options,\n };\n const element = {\n priority: options.priority,\n id: options.id,\n run,\n };\n if (this.size === 0 || this.#queue[this.size - 1].priority >= options.priority) {\n this.#queue.push(element);\n return;\n }\n const index = lowerBound(this.#queue, element, (a, b) => b.priority - a.priority);\n this.#queue.splice(index, 0, element);\n }\n setPriority(id, priority) {\n const index = this.#queue.findIndex((element) => element.id === id);\n if (index === -1) {\n throw new ReferenceError(`No promise function with the id \"${id}\" exists in the queue.`);\n }\n const [item] = this.#queue.splice(index, 1);\n this.enqueue(item.run, { priority, id });\n }\n dequeue() {\n const item = this.#queue.shift();\n return item?.run;\n }\n filter(options) {\n return this.#queue.filter((element) => element.priority === options.priority).map((element) => element.run);\n }\n get size() {\n return this.#queue.length;\n }\n}\n","// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nexport default function lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n","import { EventEmitter } from 'eventemitter3';\nimport pTimeout, { TimeoutError } from 'p-timeout';\nimport PriorityQueue from './priority-queue.js';\n/**\nPromise queue with concurrency control.\n*/\nexport default class PQueue extends EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n // Use to assign a unique identifier to a promise function, if not explicitly specified\n #idAssigner = 1n;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: PriorityQueue,\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n /**\n Updates the priority of a promise function by its id, affecting its execution order. Requires a defined concurrency limit to take effect.\n\n For example, this can be used to prioritize a promise function to run earlier.\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 0, id: '🦀'});\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦄', {priority: 1});\n\n queue.setPriority('🦀', 2);\n ```\n\n In this case, the promise function with `id: '🦀'` runs second.\n\n You can also deprioritize a promise function to delay its execution:\n\n ```js\n import PQueue from 'p-queue';\n\n const queue = new PQueue({concurrency: 1});\n\n queue.add(async () => '🦄', {priority: 1});\n queue.add(async () => '🦀', {priority: 1, id: '🦀'});\n queue.add(async () => '🦄');\n queue.add(async () => '🦄', {priority: 0});\n\n queue.setPriority('🦀', -1);\n ```\n Here, the promise function with `id: '🦀'` executes last.\n */\n setPriority(id, priority) {\n this.#queue.setPriority(id, priority);\n }\n async add(function_, options = {}) {\n // In case `id` is not defined.\n options.id ??= (this.#idAssigner++).toString();\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = pTimeout(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n","import { RecordType } from '../index.js';\nexport function getTypes(types) {\n const DEFAULT_TYPES = [\n RecordType.A\n ];\n if (types == null) {\n return DEFAULT_TYPES;\n }\n if (Array.isArray(types)) {\n if (types.length === 0) {\n return DEFAULT_TYPES;\n }\n return types;\n }\n return [\n types\n ];\n}\n//# sourceMappingURL=get-types.js.map","import { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nimport { RecordType } from '../index.js';\n/**\n * This TTL will be used if the remote service does not return one\n */\nexport const DEFAULT_TTL = 60;\nexport function toDNSResponse(obj) {\n return {\n Status: obj.Status ?? 0,\n TC: obj.TC ?? obj.flag_tc ?? false,\n RD: obj.RD ?? obj.flag_rd ?? false,\n RA: obj.RA ?? obj.flag_ra ?? false,\n AD: obj.AD ?? obj.flag_ad ?? false,\n CD: obj.CD ?? obj.flag_cd ?? false,\n Question: (obj.Question ?? obj.questions ?? []).map((question) => {\n return {\n name: question.name,\n type: RecordType[question.type]\n };\n }),\n Answer: (obj.Answer ?? obj.answers ?? []).map((answer) => {\n return {\n name: answer.name,\n type: RecordType[answer.type],\n TTL: (answer.TTL ?? answer.ttl ?? DEFAULT_TTL),\n data: answer.data instanceof Uint8Array ? uint8ArrayToString(answer.data) : answer.data\n };\n })\n };\n}\n//# sourceMappingURL=to-dns-response.js.map","/* eslint-env browser */\nimport PQueue from 'p-queue';\nimport { CustomProgressEvent } from 'progress-events';\nimport { RecordType } from '../index.js';\nimport { getTypes } from '../utils/get-types.js';\nimport { toDNSResponse } from '../utils/to-dns-response.js';\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nexport const DEFAULT_QUERY_CONCURRENCY = 4;\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nexport function dnsJsonOverHttps(url, init = {}) {\n const httpQueue = new PQueue({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n });\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams();\n searchParams.set('name', fqdn);\n getTypes(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', RecordType[type]);\n });\n options.onProgress?.(new CustomProgressEvent('dns:query', { detail: fqdn }));\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`);\n }\n const response = toDNSResponse(await res.json());\n options.onProgress?.(new CustomProgressEvent('dns:response', { detail: response }));\n return response;\n }, {\n signal: options.signal\n });\n if (response == null) {\n throw new Error('No DNS response received');\n }\n return response;\n };\n}\n//# sourceMappingURL=dns-json-over-https.js.map","/**\n * @packageDocumentation\n *\n * Query DNS records using `node:dns`, DNS over HTTP and/or DNSJSON over HTTP.\n *\n * A list of publicly accessible servers can be found [here](https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers).\n *\n * @example Using the default resolver\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve A records with a 5s timeout\n * const result = await dns.query('google.com', {\n * signal: AbortSignal.timeout(5000)\n * })\n * ```\n *\n * @example Using per-TLD resolvers\n *\n * ```TypeScript\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * // will only be used to resolve `.com` addresses\n * 'com.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n *\n * // this can also be an array, resolvers will be shuffled and tried in\n * // series\n * 'net.': [\n * dnsJsonOverHttps('https://dns.google/resolve'),\n * dnsJsonOverHttps('https://dns.pub/dns-query')\n * ],\n *\n * // will only be used to resolve all other addresses\n * '.': dnsJsonOverHttps('https://dnsforge.de/dns-query'),\n * }\n * })\n * ```\n *\n * @example Query for specific record types\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // resolve only TXT records\n * const result = await dns.query('google.com', {\n * types: [\n * RecordType.TXT\n * ]\n * })\n * ```\n *\n * ## Caching\n *\n * Individual Aanswers are cached so. If you make a request, for which all\n * record types are cached, all values will be pulled from the cache.\n *\n * If any of the record types are not cached, a new request will be resolved as\n * if none of the records were cached, and the cache will be updated to include\n * the new results.\n *\n * @example Ignoring the cache\n *\n * ```TypeScript\n * import { dns, RecordType } from '@multiformats/dns'\n *\n * const resolver = dns()\n *\n * // do not used cached results, always resolve a new query\n * const result = await dns.query('google.com', {\n * cached: false\n * })\n * ```\n */\nimport { DNS as DNSClass } from './dns.js';\n/**\n * A subset of DNS Record Types\n *\n * @see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4.\n */\nexport var RecordType;\n(function (RecordType) {\n RecordType[RecordType[\"A\"] = 1] = \"A\";\n RecordType[RecordType[\"CNAME\"] = 5] = \"CNAME\";\n RecordType[RecordType[\"TXT\"] = 16] = \"TXT\";\n RecordType[RecordType[\"AAAA\"] = 28] = \"AAAA\";\n})(RecordType || (RecordType = {}));\n/**\n * The default maximum amount of recursion allowed during a query\n */\nexport const MAX_RECURSIVE_DEPTH = 32;\nexport function dns(init = {}) {\n return new DNSClass(init);\n}\n//# sourceMappingURL=index.js.map","import hashlru from 'hashlru';\nimport { RecordType } from '../index.js';\nimport { DEFAULT_TTL, toDNSResponse } from './to-dns-response.js';\n/**\n * Time Aware Least Recent Used Cache\n *\n * @see https://arxiv.org/pdf/1801.00390\n */\nclass CachedAnswers {\n lru;\n constructor(maxSize) {\n this.lru = hashlru(maxSize);\n }\n get(fqdn, types) {\n let foundAllAnswers = true;\n const answers = [];\n for (const type of types) {\n const cached = this.getAnswers(fqdn, type);\n if (cached.length === 0) {\n foundAllAnswers = false;\n break;\n }\n answers.push(...cached);\n }\n if (foundAllAnswers) {\n return toDNSResponse({ answers });\n }\n }\n getAnswers(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n const answers = this.lru.get(key);\n if (answers != null) {\n const cachedAnswers = answers\n .filter((entry) => {\n return entry.expires > Date.now();\n })\n .map(({ expires, value }) => ({\n ...value,\n TTL: Math.round((expires - Date.now()) / 1000),\n type: RecordType[value.type]\n }));\n if (cachedAnswers.length === 0) {\n this.lru.remove(key);\n }\n // @ts-expect-error hashlru stringifies stored types which turns enums\n // into strings, we convert back into enums above but tsc doesn't know\n return cachedAnswers;\n }\n return [];\n }\n add(domain, answer) {\n const key = `${domain.toLowerCase()}-${answer.type}`;\n const answers = this.lru.get(key) ?? [];\n answers.push({\n expires: Date.now() + ((answer.TTL ?? DEFAULT_TTL) * 1000),\n value: answer\n });\n this.lru.set(key, answers);\n }\n remove(domain, type) {\n const key = `${domain.toLowerCase()}-${type}`;\n this.lru.remove(key);\n }\n clear() {\n this.lru.clear();\n }\n}\n/**\n * Avoid sending multiple queries for the same hostname by caching results\n */\nexport function cache(size) {\n return new CachedAnswers(size);\n}\n//# sourceMappingURL=cache.js.map","import { CustomProgressEvent } from 'progress-events';\nimport { defaultResolver } from './resolvers/default.js';\nimport { cache } from './utils/cache.js';\nimport { getTypes } from './utils/get-types.js';\nconst DEFAULT_ANSWER_CACHE_SIZE = 1000;\nexport class DNS {\n resolvers;\n cache;\n constructor(init) {\n this.resolvers = {};\n this.cache = cache(init.cacheSize ?? DEFAULT_ANSWER_CACHE_SIZE);\n Object.entries(init.resolvers ?? {}).forEach(([tld, resolver]) => {\n if (!Array.isArray(resolver)) {\n resolver = [resolver];\n }\n // convert `com` -> `com.`\n if (!tld.endsWith('.')) {\n tld = `${tld}.`;\n }\n this.resolvers[tld] = resolver;\n });\n // configure default resolver if none specified\n if (this.resolvers['.'] == null) {\n this.resolvers['.'] = defaultResolver();\n }\n }\n /**\n * Queries DNS resolvers for the passed record types for the passed domain.\n *\n * If cached records exist for all desired types they will be returned\n * instead.\n *\n * Any new responses will be added to the cache for subsequent requests.\n */\n async query(domain, options = {}) {\n const types = getTypes(options.types);\n const cached = options.cached !== false ? this.cache.get(domain, types) : undefined;\n if (cached != null) {\n options.onProgress?.(new CustomProgressEvent('dns:cache', { detail: cached }));\n return cached;\n }\n const tld = `${domain.split('.').pop()}.`;\n const resolvers = (this.resolvers[tld] ?? this.resolvers['.']).sort(() => {\n return (Math.random() > 0.5) ? -1 : 1;\n });\n const errors = [];\n for (const resolver of resolvers) {\n // skip further resolutions if the user aborted the signal\n if (options.signal?.aborted === true) {\n break;\n }\n try {\n const result = await resolver(domain, {\n ...options,\n types\n });\n for (const answer of result.Answer) {\n this.cache.add(domain, answer);\n }\n return result;\n }\n catch (err) {\n errors.push(err);\n options.onProgress?.(new CustomProgressEvent('dns:error', { detail: err }));\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateError(errors, `DNS lookup of ${domain} ${types} failed`);\n }\n}\n//# sourceMappingURL=dns.js.map","import { dnsJsonOverHttps } from './dns-json-over-https.js';\nexport function defaultResolver() {\n return [\n dnsJsonOverHttps('https://cloudflare-dns.com/dns-query'),\n dnsJsonOverHttps('https://dns.google/resolve')\n ];\n}\n//# sourceMappingURL=default.browser.js.map","import { dns, RecordType } from '@multiformats/dns';\nimport { multiaddr } from '../index.js';\nimport { getProtocol } from '../protocols-table.js';\nconst MAX_RECURSIVE_DEPTH = 32;\nconst { code: dnsaddrCode } = getProtocol('dnsaddr');\nclass RecursionLimitError extends Error {\n constructor(message = 'Max recursive depth reached') {\n super(message);\n this.name = 'RecursionLimitError';\n }\n}\nexport const dnsaddrResolver = async function dnsaddrResolver(ma, options = {}) {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH;\n if (recursionLimit === 0) {\n throw new RecursionLimitError('Max recursive depth reached');\n }\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? [];\n const resolver = options?.dns ?? dns();\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n RecordType.TXT\n ]\n });\n const peerId = ma.getPeerId();\n const output = [];\n for (const answer of result.Answer) {\n const addr = answer.data\n .replace(/[\"']/g, '')\n .trim()\n .split('=')[1];\n if (addr == null) {\n continue;\n }\n if (peerId != null && !addr.includes(peerId)) {\n continue;\n }\n const ma = multiaddr(addr);\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n });\n output.push(...resolved.map(ma => ma.toString()));\n }\n else {\n output.push(ma.toString());\n }\n }\n return output;\n};\n//# sourceMappingURL=dnsaddr.js.map","/**\n * Thin ESM wrapper for CJS named exports.\n *\n * Ref: https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1\n */\n\nimport mergeOptions from './index.js';\nexport default mergeOptions;\n","import { FaultTolerance, InvalidParametersError } from '@libp2p/interface';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport mergeOptions from 'merge-options';\nconst DefaultConfig = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n },\n transportManager: {\n faultTolerance: FaultTolerance.FATAL_ALL\n }\n};\nexport async function validateConfig(opts) {\n const resultingOptions = mergeOptions(DefaultConfig, opts);\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new InvalidParametersError('Private network is enforced, but no protector was provided');\n }\n return resultingOptions;\n}\n//# sourceMappingURL=config.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map","/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nexport const peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map","// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\nexport default ms;\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n","/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n/**\n * This is the web browser implementation of `debug()`.\n */\nimport humanize from 'ms';\nimport setup from './common.js';\nconst storage = localstorage();\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n }\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false;\n }\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + humanize(this.diff);\n if (!this.useColors) {\n return;\n }\n const c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit');\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0;\n let lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, (match) => {\n if (match === '%%') {\n return;\n }\n index++;\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { });\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save(namespaces) {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces);\n }\n else {\n storage?.removeItem('debug');\n }\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load() {\n let r;\n try {\n r = storage?.getItem('debug');\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG;\n }\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\nfunction setupFormatters(formatters) {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v) {\n try {\n return JSON.stringify(v);\n }\n catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n };\n}\nexport default setup({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log });\n//# sourceMappingURL=browser.js.map","/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\nimport humanize from 'ms';\nexport default function setup(env) {\n createDebug.debug = createDebug;\n createDebug.default = createDebug;\n createDebug.coerce = coerce;\n createDebug.disable = disable;\n createDebug.enable = enable;\n createDebug.enabled = enabled;\n createDebug.humanize = humanize;\n createDebug.destroy = destroy;\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key];\n });\n /**\n * The currently active debug mode names, and names to skip.\n */\n createDebug.names = [];\n createDebug.skips = [];\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {};\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor(namespace) {\n let hash = 0;\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n }\n createDebug.selectColor = selectColor;\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug(namespace) {\n let prevTime;\n let enableOverride = null;\n let namespacesCache;\n let enabledCache;\n function debug(...args) {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return;\n }\n const self = debug;\n // Set `diff` timestamp\n const curr = Number(new Date());\n const ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n args[0] = createDebug.coerce(args[0]);\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O');\n }\n // Apply any `formatters` transformations\n let index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%';\n }\n index++;\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format];\n if (typeof formatter === 'function') {\n const val = args[index];\n match = formatter.call(self, val);\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args);\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log;\n logFn.apply(self, args);\n }\n debug.namespace = namespace;\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors();\n debug.color = createDebug.selectColor(namespace);\n debug.extend = extend;\n debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride;\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces;\n enabledCache = createDebug.enabled(namespace);\n }\n return enabledCache;\n },\n set: v => {\n enableOverride = v;\n }\n });\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug);\n }\n // @ts-expect-error some properties are added dynamically\n return debug;\n }\n function extend(namespace, delimiter) {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n newDebug.log = this.log;\n return newDebug;\n }\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable(namespaces) {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces);\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces;\n createDebug.names = [];\n createDebug.skips = [];\n let i;\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n const len = split.length;\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue;\n }\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n }\n else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n }\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable() {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',');\n createDebug.enable('');\n return namespaces;\n }\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled(name) {\n if (name[name.length - 1] === '*') {\n return true;\n }\n let i;\n let len;\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Convert regexp to namespace\n */\n function toNamespace(regexp) {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*');\n }\n /**\n * Coerce `val`.\n */\n function coerce(val) {\n if (val instanceof Error) {\n return val.stack ?? val.message;\n }\n return val;\n }\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy() {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n }\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters);\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load());\n // @ts-expect-error some properties are added dynamically\n return createDebug;\n}\n//# sourceMappingURL=common.js.map","/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n/**\n * Module dependencies.\n */\nimport weald from './node.js';\nexport default weald;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * A logger for libp2p based on [weald](https://www.npmjs.com/package/weald), a TypeScript port of the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\nimport { base32 } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64 } from 'multiformats/bases/base64';\nimport debug from 'weald';\nimport { truncatePeerId } from './utils.js';\n// Add a formatter for converting to a base58 string\ndebug.formatters.b = (v) => {\n return v == null ? 'undefined' : base58btc.baseEncode(v);\n};\n// Add a formatter for converting to a base32 string\ndebug.formatters.t = (v) => {\n return v == null ? 'undefined' : base32.baseEncode(v);\n};\n// Add a formatter for converting to a base64 string\ndebug.formatters.m = (v) => {\n return v == null ? 'undefined' : base64.baseEncode(v);\n};\n// Add a formatter for stringifying peer ids\ndebug.formatters.p = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying CIDs\ndebug.formatters.c = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Datastore keys\ndebug.formatters.k = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Multiaddrs\ndebug.formatters.a = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Errors\ndebug.formatters.e = (v) => {\n return v == null ? 'undefined' : notEmpty(v.stack) ?? notEmpty(v.message) ?? v.toString();\n};\nfunction createDisabledLogger(namespace) {\n const logger = () => { };\n logger.enabled = false;\n logger.color = '';\n logger.diff = 0;\n logger.log = () => { };\n logger.namespace = namespace;\n logger.destroy = () => true;\n logger.extend = () => logger;\n return logger;\n}\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nexport function peerLogger(peerId, options = {}) {\n return prefixLogger(truncatePeerId(peerId, options));\n}\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nexport function prefixLogger(prefix) {\n return {\n forComponent(name) {\n return logger(`${prefix}:${name}`);\n }\n };\n}\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function defaultLogger() {\n return {\n forComponent(name) {\n return logger(name);\n }\n };\n}\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nexport function logger(name) {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`);\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug.enabled(`${name}:trace`) && debug.names.map((r) => r.toString()).find((n) => n.includes(':trace')) != null) {\n trace = debug(`${name}:trace`);\n }\n return Object.assign(debug(name), {\n error: debug(`${name}:error`),\n trace\n });\n}\nexport function disable() {\n debug.disable();\n}\nexport function enable(namespaces) {\n debug.enable(namespaces);\n}\nexport function enabled(namespaces) {\n return debug.enabled(namespaces);\n}\nfunction notEmpty(str) {\n if (str == null) {\n return;\n }\n str = str.trim();\n if (str.length === 0) {\n return;\n }\n return str;\n}\n//# sourceMappingURL=index.js.map","import { peerIdFromMultihash } from '@libp2p/peer-id';\nimport { base58btc } from 'multiformats/bases/base58';\nimport * as Digest from 'multiformats/hashes/digest';\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nexport function mapIterable(iter, map) {\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n const next = iter.next();\n const val = next.value;\n if (next.done === true || val == null) {\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n return {\n done: false,\n value: map(val)\n };\n }\n };\n return iterator;\n}\nexport function peerIdFromString(str) {\n const multihash = Digest.decode(base58btc.decode(`z${str}`));\n return peerIdFromMultihash(multihash);\n}\n//# sourceMappingURL=util.js.map","import { mapIterable, peerIdFromString } from './util.js';\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nexport class PeerSet {\n set;\n constructor(set) {\n this.set = new Set();\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString());\n }\n }\n }\n get size() {\n return this.set.size;\n }\n [Symbol.iterator]() {\n return this.values();\n }\n add(peer) {\n this.set.add(peer.toString());\n }\n clear() {\n this.set.clear();\n }\n delete(peer) {\n this.set.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.set.entries(), (val) => {\n const peerId = peerIdFromString(val[0]);\n return [peerId, peerId];\n });\n }\n forEach(predicate) {\n this.set.forEach((str) => {\n const peerId = peerIdFromString(str);\n predicate(peerId, peerId, this);\n });\n }\n has(peer) {\n return this.set.has(peer.toString());\n }\n values() {\n return mapIterable(this.set.values(), (val) => {\n return peerIdFromString(val);\n });\n }\n intersection(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n difference(other) {\n const output = new PeerSet();\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n union(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n output.add(peerId);\n }\n for (const peerId of this) {\n output.add(peerId);\n }\n return output;\n }\n}\nexport function peerSet() {\n return new PeerSet();\n}\n//# sourceMappingURL=set.js.map","const events = {};\nconst observable = (worker) => {\n worker.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n if (worker.port != null) {\n worker.port.addEventListener('message', (event) => {\n observable.dispatchEvent('message', worker, event);\n });\n }\n};\nobservable.addEventListener = (type, fn) => {\n if (events[type] == null) {\n events[type] = [];\n }\n events[type].push(fn);\n};\nobservable.removeEventListener = (type, fn) => {\n if (events[type] == null) {\n return;\n }\n events[type] = events[type]\n .filter(listener => listener === fn);\n};\nobservable.dispatchEvent = function (type, worker, event) {\n if (events[type] == null) {\n return;\n }\n events[type].forEach(fn => fn(worker, event));\n};\nexport default observable;\n//# sourceMappingURL=index.js.map","export const WORKER_REQUEST_READ_LOCK = 'lock:worker:request-read';\nexport const WORKER_RELEASE_READ_LOCK = 'lock:worker:release-read';\nexport const MASTER_GRANT_READ_LOCK = 'lock:master:grant-read';\nexport const WORKER_REQUEST_WRITE_LOCK = 'lock:worker:request-write';\nexport const WORKER_RELEASE_WRITE_LOCK = 'lock:worker:release-write';\nexport const MASTER_GRANT_WRITE_LOCK = 'lock:master:grant-write';\n//# sourceMappingURL=constants.js.map","import observer from 'observable-webworkers';\nimport { WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK } from './constants.js';\nimport { nanoid } from './utils.js';\nconst handleWorkerLockRequest = (emitter, masterEvent, requestType, releaseType, grantType) => {\n return (worker, event) => {\n if (event.data.type !== requestType) {\n return;\n }\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async () => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n });\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event) => {\n if (event?.data == null) {\n return;\n }\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener);\n resolve();\n }\n };\n worker.addEventListener('message', releaseEventListener);\n });\n }\n }\n }));\n };\n};\nconst makeWorkerLockRequest = (name, requestType, grantType, releaseType) => {\n return async () => {\n const id = nanoid();\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n });\n return new Promise((resolve) => {\n const listener = (event) => {\n if (event?.data == null) {\n return;\n }\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n };\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener);\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n });\n });\n }\n };\n globalThis.addEventListener('message', listener);\n });\n };\n};\nconst defaultOptions = {\n singleProcess: false\n};\nexport default (options) => {\n options = Object.assign({}, defaultOptions, options);\n const isPrimary = Boolean(globalThis.document) || options.singleProcess;\n if (isPrimary) {\n const emitter = new EventTarget();\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', WORKER_REQUEST_READ_LOCK, WORKER_RELEASE_READ_LOCK, MASTER_GRANT_READ_LOCK));\n observer.addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', WORKER_REQUEST_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK));\n return emitter;\n }\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_READ_LOCK, MASTER_GRANT_READ_LOCK, WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, WORKER_REQUEST_WRITE_LOCK, MASTER_GRANT_WRITE_LOCK, WORKER_RELEASE_WRITE_LOCK)\n };\n};\n//# sourceMappingURL=browser.js.map","export const nanoid = (size = 21) => {\n return Math.random().toString().substring(2);\n};\n//# sourceMappingURL=utils.js.map","/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\nimport PQueue from 'p-queue';\nimport pTimeout from 'p-timeout';\nimport impl from './node.js';\nconst mutexes = {};\nlet implementation;\nasync function createReleaseable(queue, options) {\n let res;\n const p = new Promise((resolve) => {\n res = resolve;\n });\n void queue.add(async () => pTimeout((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve();\n });\n });\n })(), {\n milliseconds: options.timeout\n }));\n return p;\n}\nconst createMutex = (name, options) => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n };\n }\n const masterQueue = new PQueue({ concurrency: 1 });\n let readQueue;\n return {\n async readLock() {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options);\n }\n // Create a new read queue\n readQueue = new PQueue({\n concurrency: options.concurrency,\n autoStart: false\n });\n const localReadQueue = readQueue;\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options);\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start();\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null;\n }\n });\n });\n return readPromise;\n },\n async writeLock() {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null;\n return createReleaseable(masterQueue, options);\n }\n };\n};\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n};\nexport default function createMortice(options) {\n const opts = Object.assign({}, defaultOptions, options);\n if (implementation == null) {\n implementation = impl(opts);\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].readLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n implementation.addEventListener('requestWriteLock', async (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].writeLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n }\n }\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts);\n }\n return mutexes[opts.name];\n}\n//# sourceMappingURL=index.js.map","/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\nimport { decodeMessage, encodeMessage, MaxLengthError, MaxSizeError, message } from 'protons-runtime';\nimport { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nexport var Peer;\n(function (Peer) {\n let Peer$metadataEntry;\n (function (Peer$metadataEntry) {\n let _codec;\n Peer$metadataEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if ((obj.value != null && obj.value.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.value);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n key: '',\n value: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.string();\n break;\n }\n case 2: {\n obj.value = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$metadataEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$metadataEntry.codec());\n };\n Peer$metadataEntry.decode = (buf, opts) => {\n return decodeMessage(buf, Peer$metadataEntry.codec(), opts);\n };\n })(Peer$metadataEntry = Peer.Peer$metadataEntry || (Peer.Peer$metadataEntry = {}));\n let Peer$tagsEntry;\n (function (Peer$tagsEntry) {\n let _codec;\n Peer$tagsEntry.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.key != null && obj.key !== '')) {\n w.uint32(10);\n w.string(obj.key);\n }\n if (obj.value != null) {\n w.uint32(18);\n Tag.codec().encode(obj.value, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n key: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.key = reader.string();\n break;\n }\n case 2: {\n obj.value = Tag.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.value\n });\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer$tagsEntry.encode = (obj) => {\n return encodeMessage(obj, Peer$tagsEntry.codec());\n };\n Peer$tagsEntry.decode = (buf, opts) => {\n return decodeMessage(buf, Peer$tagsEntry.codec(), opts);\n };\n })(Peer$tagsEntry = Peer.Peer$tagsEntry || (Peer.Peer$tagsEntry = {}));\n let _codec;\n Peer.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(10);\n Address.codec().encode(value, w);\n }\n }\n if (obj.protocols != null) {\n for (const value of obj.protocols) {\n w.uint32(18);\n w.string(value);\n }\n }\n if (obj.publicKey != null) {\n w.uint32(34);\n w.bytes(obj.publicKey);\n }\n if (obj.peerRecordEnvelope != null) {\n w.uint32(42);\n w.bytes(obj.peerRecordEnvelope);\n }\n if (obj.metadata != null && obj.metadata.size !== 0) {\n for (const [key, value] of obj.metadata.entries()) {\n w.uint32(50);\n Peer.Peer$metadataEntry.codec().encode({ key, value }, w);\n }\n }\n if (obj.tags != null && obj.tags.size !== 0) {\n for (const [key, value] of obj.tags.entries()) {\n w.uint32(58);\n Peer.Peer$tagsEntry.codec().encode({ key, value }, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n addresses: [],\n protocols: [],\n metadata: new Map(),\n tags: new Map()\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.addresses != null && obj.addresses.length === opts.limits.addresses) {\n throw new MaxLengthError('Decode error - map field \"addresses\" had too many elements');\n }\n obj.addresses.push(Address.codec().decode(reader, reader.uint32(), {\n limits: opts.limits?.addresses$\n }));\n break;\n }\n case 2: {\n if (opts.limits?.protocols != null && obj.protocols.length === opts.limits.protocols) {\n throw new MaxLengthError('Decode error - map field \"protocols\" had too many elements');\n }\n obj.protocols.push(reader.string());\n break;\n }\n case 4: {\n obj.publicKey = reader.bytes();\n break;\n }\n case 5: {\n obj.peerRecordEnvelope = reader.bytes();\n break;\n }\n case 6: {\n if (opts.limits?.metadata != null && obj.metadata.size === opts.limits.metadata) {\n throw new MaxSizeError('Decode error - map field \"metadata\" had too many elements');\n }\n const entry = Peer.Peer$metadataEntry.codec().decode(reader, reader.uint32());\n obj.metadata.set(entry.key, entry.value);\n break;\n }\n case 7: {\n if (opts.limits?.tags != null && obj.tags.size === opts.limits.tags) {\n throw new MaxSizeError('Decode error - map field \"tags\" had too many elements');\n }\n const entry = Peer.Peer$tagsEntry.codec().decode(reader, reader.uint32(), {\n limits: {\n value: opts.limits?.tags$value\n }\n });\n obj.tags.set(entry.key, entry.value);\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Peer.encode = (obj) => {\n return encodeMessage(obj, Peer.codec());\n };\n Peer.decode = (buf, opts) => {\n return decodeMessage(buf, Peer.codec(), opts);\n };\n})(Peer || (Peer = {}));\nexport var Address;\n(function (Address) {\n let _codec;\n Address.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (obj.isCertified != null) {\n w.uint32(16);\n w.bool(obj.isCertified);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n multiaddr: uint8ArrayAlloc(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.multiaddr = reader.bytes();\n break;\n }\n case 2: {\n obj.isCertified = reader.bool();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Address.encode = (obj) => {\n return encodeMessage(obj, Address.codec());\n };\n Address.decode = (buf, opts) => {\n return decodeMessage(buf, Address.codec(), opts);\n };\n})(Address || (Address = {}));\nexport var Tag;\n(function (Tag) {\n let _codec;\n Tag.codec = () => {\n if (_codec == null) {\n _codec = message((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.value != null && obj.value !== 0)) {\n w.uint32(8);\n w.uint32(obj.value);\n }\n if (obj.expiry != null) {\n w.uint32(16);\n w.uint64(obj.expiry);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n value: 0\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.value = reader.uint32();\n break;\n }\n case 2: {\n obj.expiry = reader.uint64();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Tag.encode = (obj) => {\n return encodeMessage(obj, Tag.codec());\n };\n Tag.decode = (buf, opts) => {\n return decodeMessage(buf, Tag.codec(), opts);\n };\n})(Tag || (Tag = {}));\n//# sourceMappingURL=peer.js.map","import { publicKeyFromProtobuf } from '@libp2p/crypto/keys';\nimport { peerIdFromPublicKey } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { Peer as PeerPB } from '../pb/peer.js';\nexport function bytesToPeer(peerId, buf) {\n const peer = PeerPB.decode(buf);\n if (peer.publicKey != null && peerId.publicKey == null) {\n const publicKey = publicKeyFromProtobuf(peer.publicKey);\n peerId = peerIdFromPublicKey(publicKey);\n }\n const tags = new Map();\n // remove any expired tags\n const now = BigInt(Date.now());\n for (const [key, tag] of peer.tags.entries()) {\n if (tag.expiry != null && tag.expiry < now) {\n continue;\n }\n tags.set(key, tag);\n }\n return {\n ...peer,\n id: peerId,\n addresses: peer.addresses.map(({ multiaddr: ma, isCertified }) => {\n return {\n multiaddr: multiaddr(ma),\n isCertified: isCertified ?? false\n };\n }),\n metadata: peer.metadata,\n peerRecordEnvelope: peer.peerRecordEnvelope ?? undefined,\n tags\n };\n}\n//# sourceMappingURL=bytes-to-peer.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst pathSepS = '/';\nconst pathSepB = new TextEncoder().encode(pathSepS);\nconst pathSep = pathSepB[0];\n/**\n * A Key represents the unique identifier of an object.\n * Our Key scheme is inspired by file systems and Google App Engine key model.\n * Keys are meant to be unique across a system. Keys are hierarchical,\n * incorporating more and more specific namespaces. Thus keys can be deemed\n * 'children' or 'ancestors' of other keys:\n * - `new Key('/Comedy')`\n * - `new Key('/Comedy/MontyPython')`\n * Also, every namespace can be parametrized to embed relevant object\n * information. For example, the Key `name` (most specific namespace) could\n * include the object type:\n * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')`\n * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')`\n *\n */\nexport class Key {\n _buf;\n /**\n * @param {string | Uint8Array} s\n * @param {boolean} [clean]\n */\n constructor(s, clean) {\n if (typeof s === 'string') {\n this._buf = uint8ArrayFromString(s);\n }\n else if (s instanceof Uint8Array) {\n this._buf = s;\n }\n else {\n throw new Error('Invalid key, should be String of Uint8Array');\n }\n if (clean == null) {\n clean = true;\n }\n if (clean) {\n this.clean();\n }\n if (this._buf.byteLength === 0 || this._buf[0] !== pathSep) {\n throw new Error('Invalid key');\n }\n }\n /**\n * Convert to the string representation\n *\n * @param {import('uint8arrays/to-string').SupportedEncodings} [encoding='utf8'] - The encoding to use.\n * @returns {string}\n */\n toString(encoding = 'utf8') {\n return uint8ArrayToString(this._buf, encoding);\n }\n /**\n * Return the Uint8Array representation of the key\n *\n * @returns {Uint8Array}\n */\n uint8Array() {\n return this._buf;\n }\n /**\n * Return string representation of the key\n *\n * @returns {string}\n */\n get [Symbol.toStringTag]() {\n return `Key(${this.toString()})`;\n }\n /**\n * Constructs a key out of a namespace array.\n *\n * @param {Array} list - The array of namespaces\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.withNamespaces(['one', 'two'])\n * // => Key('/one/two')\n * ```\n */\n static withNamespaces(list) {\n return new Key(list.join(pathSepS));\n }\n /**\n * Returns a randomly (uuid) generated key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * Key.random()\n * // => Key('/344502982398')\n * ```\n */\n static random() {\n return new Key(Math.random().toString().substring(2));\n }\n /**\n * @param {*} other\n */\n static asKey(other) {\n if (other instanceof Uint8Array || typeof other === 'string') {\n // we can create a key from this\n return new Key(other);\n }\n if (typeof other.uint8Array === 'function') {\n // this is an older version or may have crossed the esm/cjs boundary\n return new Key(other.uint8Array());\n }\n return null;\n }\n /**\n * Cleanup the current key\n *\n * @returns {void}\n */\n clean() {\n if (this._buf == null || this._buf.byteLength === 0) {\n this._buf = pathSepB;\n }\n if (this._buf[0] !== pathSep) {\n const bytes = new Uint8Array(this._buf.byteLength + 1);\n bytes.fill(pathSep, 0, 1);\n bytes.set(this._buf, 1);\n this._buf = bytes;\n }\n // normalize does not remove trailing slashes\n while (this._buf.byteLength > 1 && this._buf[this._buf.byteLength - 1] === pathSep) {\n this._buf = this._buf.subarray(0, -1);\n }\n }\n /**\n * Check if the given key is sorted lower than ourself.\n *\n * @param {Key} key - The other Key to check against\n * @returns {boolean}\n */\n less(key) {\n const list1 = this.list();\n const list2 = key.list();\n for (let i = 0; i < list1.length; i++) {\n if (list2.length < i + 1) {\n return false;\n }\n const c1 = list1[i];\n const c2 = list2[i];\n if (c1 < c2) {\n return true;\n }\n else if (c1 > c2) {\n return false;\n }\n }\n return list1.length < list2.length;\n }\n /**\n * Returns the key with all parts in reversed order.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse()\n * // => Key('/Actor:JohnCleese/MontyPython/Comedy')\n * ```\n */\n reverse() {\n return Key.withNamespaces(this.list().slice().reverse());\n }\n /**\n * Returns the `namespaces` making up this Key.\n *\n * @returns {Array}\n */\n namespaces() {\n return this.list();\n }\n /** Returns the \"base\" namespace of this key.\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace()\n * // => 'Actor:JohnCleese'\n * ```\n */\n baseNamespace() {\n const ns = this.namespaces();\n return ns[ns.length - 1];\n }\n /**\n * Returns the `list` representation of this key.\n *\n * @returns {Array}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').list()\n * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese']\n * ```\n */\n list() {\n return this.toString().split(pathSepS).slice(1);\n }\n /**\n * Returns the \"type\" of this key (value of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').type()\n * // => 'Actor'\n * ```\n */\n type() {\n return namespaceType(this.baseNamespace());\n }\n /**\n * Returns the \"name\" of this key (field of last namespace).\n *\n * @returns {string}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').name()\n * // => 'JohnCleese'\n * ```\n */\n name() {\n return namespaceValue(this.baseNamespace());\n }\n /**\n * Returns an \"instance\" of this type key (appends value to namespace).\n *\n * @param {string} s - The string to append.\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse')\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n instance(s) {\n return new Key(this.toString() + ':' + s);\n }\n /**\n * Returns the \"path\" of this key (parent + type).\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython/Actor:JohnCleese').path()\n * // => Key('/Comedy/MontyPython/Actor')\n * ```\n */\n path() {\n let p = this.parent().toString();\n if (!p.endsWith(pathSepS)) {\n p += pathSepS;\n }\n p += this.type();\n return new Key(p);\n }\n /**\n * Returns the `parent` Key of this Key.\n *\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key(\"/Comedy/MontyPython/Actor:JohnCleese\").parent()\n * // => Key(\"/Comedy/MontyPython\")\n * ```\n */\n parent() {\n const list = this.list();\n if (list.length === 1) {\n return new Key(pathSepS);\n }\n return new Key(list.slice(0, -1).join(pathSepS));\n }\n /**\n * Returns the `child` Key of this Key.\n *\n * @param {Key} key - The child Key to add\n * @returns {Key}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese'))\n * // => Key('/Comedy/MontyPython/Actor:JohnCleese')\n * ```\n */\n child(key) {\n if (this.toString() === pathSepS) {\n return key;\n }\n else if (key.toString() === pathSepS) {\n return this;\n }\n return new Key(this.toString() + key.toString(), false);\n }\n /**\n * Returns whether this key is a prefix of `other`\n *\n * @param {Key} other - The other key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython')\n * // => true\n * ```\n */\n isAncestorOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return other.toString().startsWith(this.toString());\n }\n /**\n * Returns whether this key is a contains another as prefix.\n *\n * @param {Key} other - The other Key to test against\n * @returns {boolean}\n *\n * @example\n * ```js\n * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy')\n * // => true\n * ```\n */\n isDecendantOf(other) {\n if (other.toString() === this.toString()) {\n return false;\n }\n return this.toString().startsWith(other.toString());\n }\n /**\n * Checks if this key has only one namespace.\n *\n * @returns {boolean}\n */\n isTopLevel() {\n return this.list().length === 1;\n }\n /**\n * Concats one or more Keys into one new Key.\n *\n * @param {Array} keys - The array of keys to concatenate\n * @returns {Key}\n */\n concat(...keys) {\n return Key.withNamespaces([...this.namespaces(), ...flatten(keys.map(key => key.namespaces()))]);\n }\n}\n/**\n * The first component of a namespace. `foo` in `foo:bar`\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceType(ns) {\n const parts = ns.split(':');\n if (parts.length < 2) {\n return '';\n }\n return parts.slice(0, -1).join(':');\n}\n/**\n * The last component of a namespace, `baz` in `foo:bar:baz`.\n *\n * @param {string} ns\n * @returns {string}\n */\nfunction namespaceValue(ns) {\n const parts = ns.split(':');\n return parts[parts.length - 1];\n}\n/**\n * Flatten array of arrays (only one level)\n *\n * @template T\n * @param {Array} arr\n * @returns {T[]}\n */\nfunction flatten(arr) {\n return ([]).concat(...arr);\n}\n//# sourceMappingURL=key.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { isPeerId } from '@libp2p/interface';\nimport { Key } from 'interface-datastore/key';\nexport const NAMESPACE_COMMON = '/peers/';\nexport function peerIdToDatastoreKey(peerId) {\n if (!isPeerId(peerId) || peerId.type == null) {\n throw new InvalidParametersError('Invalid PeerId');\n }\n const b32key = peerId.toCID().toString();\n return new Key(`${NAMESPACE_COMMON}${b32key}`);\n}\n//# sourceMappingURL=peer-id-to-datastore-key.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { isMultiaddr, multiaddr } from '@multiformats/multiaddr';\nexport async function dedupeFilterAndSortAddresses(peerId, filter, addresses) {\n const addressMap = new Map();\n for (const addr of addresses) {\n if (addr == null) {\n continue;\n }\n if (addr.multiaddr instanceof Uint8Array) {\n addr.multiaddr = multiaddr(addr.multiaddr);\n }\n if (!isMultiaddr(addr.multiaddr)) {\n throw new InvalidParametersError('Multiaddr was invalid');\n }\n if (!(await filter(peerId, addr.multiaddr))) {\n continue;\n }\n const isCertified = addr.isCertified ?? false;\n const maStr = addr.multiaddr.toString();\n const existingAddr = addressMap.get(maStr);\n if (existingAddr != null) {\n addr.isCertified = existingAddr.isCertified || isCertified;\n }\n else {\n addressMap.set(maStr, {\n multiaddr: addr.multiaddr,\n isCertified\n });\n }\n }\n return [...addressMap.values()]\n .sort((a, b) => {\n return a.multiaddr.toString().localeCompare(b.multiaddr.toString());\n })\n .map(({ isCertified, multiaddr }) => ({\n isCertified,\n multiaddr: multiaddr.bytes\n }));\n}\n//# sourceMappingURL=dedupe-addresses.js.map","import { publicKeyToProtobuf } from '@libp2p/crypto/keys';\nimport { InvalidParametersError } from '@libp2p/interface';\nimport { dedupeFilterAndSortAddresses } from './dedupe-addresses.js';\nexport async function toPeerPB(peerId, data, strategy, options) {\n if (data == null) {\n throw new InvalidParametersError('Invalid PeerData');\n }\n if (data.publicKey != null && peerId.publicKey != null && !data.publicKey.equals(peerId.publicKey)) {\n throw new InvalidParametersError('publicKey bytes do not match peer id publicKey bytes');\n }\n const existingPeer = options.existingPeer;\n if (existingPeer != null && !peerId.equals(existingPeer.id)) {\n throw new InvalidParametersError('peer id did not match existing peer id');\n }\n let addresses = existingPeer?.addresses ?? [];\n let protocols = new Set(existingPeer?.protocols ?? []);\n let metadata = existingPeer?.metadata ?? new Map();\n let tags = existingPeer?.tags ?? new Map();\n let peerRecordEnvelope = existingPeer?.peerRecordEnvelope;\n // when patching, we replace the original fields with passed values\n if (strategy === 'patch') {\n if (data.multiaddrs != null || data.addresses != null) {\n addresses = [];\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n }\n if (data.protocols != null) {\n protocols = new Set(data.protocols);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n metadata = createSortedMap(metadataEntries, {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n tags = createSortedMap(tagsEntries, {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n // when merging, we join the original fields with passed values\n if (strategy === 'merge') {\n if (data.multiaddrs != null) {\n addresses.push(...data.multiaddrs.map(multiaddr => ({\n isCertified: false,\n multiaddr\n })));\n }\n if (data.addresses != null) {\n addresses.push(...data.addresses);\n }\n if (data.protocols != null) {\n protocols = new Set([...protocols, ...data.protocols]);\n }\n if (data.metadata != null) {\n const metadataEntries = data.metadata instanceof Map ? [...data.metadata.entries()] : Object.entries(data.metadata);\n for (const [key, value] of metadataEntries) {\n if (value == null) {\n metadata.delete(key);\n }\n else {\n metadata.set(key, value);\n }\n }\n metadata = createSortedMap([...metadata.entries()], {\n validate: validateMetadata\n });\n }\n if (data.tags != null) {\n const tagsEntries = data.tags instanceof Map ? [...data.tags.entries()] : Object.entries(data.tags);\n const mergedTags = new Map(tags);\n for (const [key, value] of tagsEntries) {\n if (value == null) {\n mergedTags.delete(key);\n }\n else {\n mergedTags.set(key, value);\n }\n }\n tags = createSortedMap([...mergedTags.entries()], {\n validate: validateTag,\n map: mapTag\n });\n }\n if (data.peerRecordEnvelope != null) {\n peerRecordEnvelope = data.peerRecordEnvelope;\n }\n }\n let publicKey;\n if (existingPeer?.id.publicKey != null) {\n publicKey = publicKeyToProtobuf(existingPeer.id.publicKey);\n }\n else if (data.publicKey != null) {\n publicKey = publicKeyToProtobuf(data.publicKey);\n }\n else if (peerId.publicKey != null) {\n publicKey = publicKeyToProtobuf(peerId.publicKey);\n }\n const output = {\n addresses: await dedupeFilterAndSortAddresses(peerId, options.addressFilter ?? (async () => true), addresses),\n protocols: [...protocols.values()].sort((a, b) => {\n return a.localeCompare(b);\n }),\n metadata,\n tags,\n publicKey,\n peerRecordEnvelope\n };\n // Ed25519 and secp256k1 have their public key embedded in them so no need to duplicate it\n if (peerId.type !== 'RSA') {\n delete output.publicKey;\n }\n return output;\n}\n/**\n * In JS maps are ordered by insertion order so create a new map with the\n * keys inserted in alphabetical order.\n */\nfunction createSortedMap(entries, options) {\n const output = new Map();\n for (const [key, value] of entries) {\n if (value == null) {\n continue;\n }\n options.validate(key, value);\n }\n for (const [key, value] of entries.sort(([a], [b]) => {\n return a.localeCompare(b);\n })) {\n if (value != null) {\n output.set(key, options.map?.(key, value) ?? value);\n }\n }\n return output;\n}\nfunction validateMetadata(key, value) {\n if (typeof key !== 'string') {\n throw new InvalidParametersError('Metadata key must be a string');\n }\n if (!(value instanceof Uint8Array)) {\n throw new InvalidParametersError('Metadata value must be a Uint8Array');\n }\n}\nfunction validateTag(key, tag) {\n if (typeof key !== 'string') {\n throw new InvalidParametersError('Tag name must be a string');\n }\n if (tag.value != null) {\n if (parseInt(`${tag.value}`, 10) !== tag.value) {\n throw new InvalidParametersError('Tag value must be an integer');\n }\n if (tag.value < 0 || tag.value > 100) {\n throw new InvalidParametersError('Tag value must be between 0-100');\n }\n }\n if (tag.ttl != null) {\n if (parseInt(`${tag.ttl}`, 10) !== tag.ttl) {\n throw new InvalidParametersError('Tag ttl must be an integer');\n }\n if (tag.ttl < 0) {\n throw new InvalidParametersError('Tag ttl must be between greater than 0');\n }\n }\n}\nfunction mapTag(key, tag) {\n let expiry;\n if (tag.expiry != null) {\n expiry = tag.expiry;\n }\n if (tag.ttl != null) {\n expiry = BigInt(Date.now() + Number(tag.ttl));\n }\n return {\n value: tag.value ?? 0,\n expiry\n };\n}\n//# sourceMappingURL=to-peer-pb.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport { peerIdFromCID } from '@libp2p/peer-id';\nimport mortice, {} from 'mortice';\nimport { base32 } from 'multiformats/bases/base32';\nimport { CID } from 'multiformats/cid';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nimport { Peer as PeerPB } from './pb/peer.js';\nimport { bytesToPeer } from './utils/bytes-to-peer.js';\nimport { NAMESPACE_COMMON, peerIdToDatastoreKey } from './utils/peer-id-to-datastore-key.js';\nimport { toPeerPB } from './utils/to-peer-pb.js';\nfunction decodePeer(key, value) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2];\n const buf = CID.parse(base32Str, base32);\n const peerId = peerIdFromCID(buf);\n return bytesToPeer(peerId, value);\n}\nfunction mapQuery(query) {\n if (query == null) {\n return {};\n }\n return {\n prefix: NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value));\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value), decodePeer(b.key, b.value));\n })\n };\n}\nexport class PersistentStore {\n peerId;\n datastore;\n lock;\n addressFilter;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.peerId = components.peerId;\n this.datastore = components.datastore;\n this.addressFilter = init.addressFilter;\n this.lock = mortice({\n name: 'peer-store',\n singleProcess: true\n });\n }\n async has(peerId) {\n return this.datastore.has(peerIdToDatastoreKey(peerId));\n }\n async delete(peerId) {\n if (this.peerId.equals(peerId)) {\n throw new InvalidParametersError('Cannot delete self peer');\n }\n await this.datastore.delete(peerIdToDatastoreKey(peerId));\n }\n async load(peerId) {\n const buf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n return bytesToPeer(peerId, buf);\n }\n async save(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async patch(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async merge(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await toPeerPB(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async *all(query) {\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}))) {\n const peer = decodePeer(key, value);\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue;\n }\n yield peer;\n }\n }\n async #findExistingPeer(peerId) {\n try {\n const existingBuf = await this.datastore.get(peerIdToDatastoreKey(peerId));\n const existingPeer = bytesToPeer(peerId, existingBuf);\n return {\n existingBuf,\n existingPeer\n };\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n this.log.error('invalid peer data found in peer store - %e', err);\n }\n }\n return {};\n }\n async #saveIfDifferent(peerId, peer, existingBuf, existingPeer) {\n const buf = PeerPB.encode(peer);\n if (existingBuf != null && uint8ArrayEquals(buf, existingBuf)) {\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: false\n };\n }\n await this.datastore.put(peerIdToDatastoreKey(peerId), buf);\n return {\n peer: bytesToPeer(peerId, buf),\n previous: existingPeer,\n updated: true\n };\n }\n}\n//# sourceMappingURL=store.js.map","/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\nimport { peerIdFromCID } from '@libp2p/peer-id';\nimport { RecordEnvelope, PeerRecord } from '@libp2p/peer-record';\nimport all from 'it-all';\nimport { PersistentStore } from './store.js';\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nclass PersistentPeerStore {\n store;\n events;\n peerId;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.events = components.events;\n this.peerId = components.peerId;\n this.store = new PersistentStore(components, init);\n }\n [Symbol.toStringTag] = '@libp2p/peer-store';\n async forEach(fn, query) {\n this.log.trace('forEach await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('forEach got read lock');\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer);\n }\n }\n finally {\n this.log.trace('forEach release read lock');\n release();\n }\n }\n async all(query) {\n this.log.trace('all await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('all got read lock');\n try {\n return await all(this.store.all(query));\n }\n finally {\n this.log.trace('all release read lock');\n release();\n }\n }\n async delete(peerId) {\n this.log.trace('delete await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('delete got write lock');\n try {\n await this.store.delete(peerId);\n }\n finally {\n this.log.trace('delete release write lock');\n release();\n }\n }\n async has(peerId) {\n this.log.trace('has await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('has got read lock');\n try {\n return await this.store.has(peerId);\n }\n finally {\n this.log.trace('has release read lock');\n release();\n }\n }\n async get(peerId) {\n this.log.trace('get await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('get got read lock');\n try {\n return await this.store.load(peerId);\n }\n finally {\n this.log.trace('get release read lock');\n release();\n }\n }\n async save(id, data) {\n this.log.trace('save await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('save got write lock');\n try {\n const result = await this.store.save(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('save release write lock');\n release();\n }\n }\n async patch(id, data) {\n this.log.trace('patch await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('patch got write lock');\n try {\n const result = await this.store.patch(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('patch release write lock');\n release();\n }\n }\n async merge(id, data) {\n this.log.trace('merge await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('merge got write lock');\n try {\n const result = await this.store.merge(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('merge release write lock');\n release();\n }\n }\n async consumePeerRecord(buf, expectedPeer) {\n const envelope = await RecordEnvelope.openAndCertify(buf, PeerRecord.DOMAIN);\n const peerId = peerIdFromCID(envelope.publicKey.toCID());\n if (expectedPeer?.equals(peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, peerId);\n return false;\n }\n const peerRecord = PeerRecord.createFromProtobuf(envelope.payload);\n let peer;\n try {\n peer = await this.get(peerId);\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n throw err;\n }\n }\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope);\n const storedRecord = PeerRecord.createFromProtobuf(storedEnvelope.payload);\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n return false;\n }\n }\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n });\n return true;\n }\n #emitIfUpdated(id, result) {\n if (!result.updated) {\n return;\n }\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result });\n }\n else {\n this.events.safeDispatchEvent('peer:update', { detail: result });\n }\n }\n}\nexport function persistentPeerStore(components, init = {}) {\n return new PersistentPeerStore(components, init);\n}\n//# sourceMappingURL=index.js.map","export class OpenFailedError extends Error {\n static name = 'OpenFailedError';\n static code = 'ERR_OPEN_FAILED';\n name = OpenFailedError.name;\n code = OpenFailedError.code;\n constructor(message = 'Open failed') {\n super(message);\n }\n}\nexport class CloseFailedError extends Error {\n static name = 'CloseFailedError';\n static code = 'ERR_CLOSE_FAILED';\n name = CloseFailedError.name;\n code = CloseFailedError.code;\n constructor(message = 'Close failed') {\n super(message);\n }\n}\nexport class PutFailedError extends Error {\n static name = 'PutFailedError';\n static code = 'ERR_PUT_FAILED';\n name = PutFailedError.name;\n code = PutFailedError.code;\n constructor(message = 'Put failed') {\n super(message);\n }\n}\nexport class GetFailedError extends Error {\n static name = 'GetFailedError';\n static code = 'ERR_GET_FAILED';\n name = GetFailedError.name;\n code = GetFailedError.code;\n constructor(message = 'Get failed') {\n super(message);\n }\n}\nexport class DeleteFailedError extends Error {\n static name = 'DeleteFailedError';\n static code = 'ERR_DELETE_FAILED';\n name = DeleteFailedError.name;\n code = DeleteFailedError.code;\n constructor(message = 'Delete failed') {\n super(message);\n }\n}\nexport class HasFailedError extends Error {\n static name = 'HasFailedError';\n static code = 'ERR_HAS_FAILED';\n name = HasFailedError.name;\n code = HasFailedError.code;\n constructor(message = 'Has failed') {\n super(message);\n }\n}\nexport class NotFoundError extends Error {\n static name = 'NotFoundError';\n static code = 'ERR_NOT_FOUND';\n name = NotFoundError.name;\n code = NotFoundError.code;\n constructor(message = 'Not Found') {\n super(message);\n }\n}\nexport class AbortError extends Error {\n static name = 'AbortError';\n static code = 'ERR_ABORTED';\n name = AbortError.name;\n code = AbortError.code;\n constructor(message = 'Aborted') {\n super(message);\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * @packageDocumentation\n *\n * Mostly useful for tests or when you want to be explicit about consuming an iterable without doing anything with any yielded values.\n *\n * @example\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * drain(values)\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import drain from 'it-drain'\n *\n * const values = async function * {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * await drain(values())\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction drain(source) {\n if (isAsyncIterable(source)) {\n return (async () => {\n for await (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n })();\n }\n else {\n for (const _ of source) { } // eslint-disable-line no-unused-vars,no-empty,@typescript-eslint/no-unused-vars\n }\n}\nexport default drain;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\nimport peek from 'it-peekable';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction filter(source, fn) {\n let index = 0;\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n // if mapping function returns a promise we have to return an async generator\n const peekable = peek(source);\n const { value, done } = peekable.next();\n if (done === true) {\n return (function* () { }());\n }\n const res = fn(value, index++);\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function* () {\n if (await res) {\n yield value;\n }\n for await (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n const func = fn;\n return (function* () {\n if (res === true) {\n yield value;\n }\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry;\n }\n }\n })();\n}\nexport default filter;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Lets you look at the contents of an async iterator and decide what to do\n *\n * @example\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const it = peekable(value)\n *\n * const first = it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info([...it])\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import peekable from 'it-peekable'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const it = peekable(values())\n *\n * const first = await it.peek()\n *\n * console.info(first) // 0\n *\n * it.push(first)\n *\n * console.info(await all(it))\n * // [ 0, 1, 2, 3, 4 ]\n * ```\n */\nfunction peekable(iterable) {\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n const [iterator, symbol] = iterable[Symbol.asyncIterator] != null\n // @ts-expect-error can't use Symbol.asyncIterator to index iterable since it might be Iterable\n ? [iterable[Symbol.asyncIterator](), Symbol.asyncIterator]\n // @ts-expect-error can't use Symbol.iterator to index iterable since it might be AsyncIterable\n : [iterable[Symbol.iterator](), Symbol.iterator];\n const queue = [];\n // @ts-expect-error can't use symbol to index peekable\n return {\n peek: () => {\n return iterator.next();\n },\n push: (value) => {\n queue.push(value);\n },\n next: () => {\n if (queue.length > 0) {\n return {\n done: false,\n value: queue.shift()\n };\n }\n return iterator.next();\n },\n [symbol]() {\n return this;\n }\n };\n}\nexport default peekable;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * Consumes all values from an (async)iterable and returns them sorted by the passed sort function.\n *\n * @example\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * // This can also be an iterator, generator, etc\n * const values = ['foo', 'bar']\n *\n * const arr = all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import sort from 'it-sort'\n * import all from 'it-all'\n *\n * const sorter = (a, b) => {\n * return a.localeCompare(b)\n * }\n *\n * const values = async function * () {\n * yield * ['foo', 'bar']\n * }\n *\n * const arr = await all(sort(values, sorter))\n *\n * console.info(arr) // 'bar', 'foo'\n * ```\n */\nimport all from 'it-all';\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction sort(source, sorter) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n const arr = await all(source);\n yield* arr.sort(sorter);\n })();\n }\n return (function* () {\n const arr = all(source);\n yield* arr.sort(sorter);\n })();\n}\nexport default sort;\n//# sourceMappingURL=index.js.map","/**\n * @packageDocumentation\n *\n * For when you only want a few values out of an (async)iterable.\n *\n * @example\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const arr = all(take(values, 2))\n *\n * console.info(arr) // 0, 1\n * ```\n *\n * Async sources must be awaited:\n *\n * ```javascript\n * import take from 'it-take'\n * import all from 'it-all'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const arr = await all(take(values(), 2))\n *\n * console.info(arr) // 0, 1\n * ```\n */\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction take(source, limit) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for await (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n }\n return (function* () {\n let items = 0;\n if (limit < 1) {\n return;\n }\n for (const entry of source) {\n yield entry;\n items++;\n if (items === limit) {\n return;\n }\n }\n })();\n}\nexport default take;\n//# sourceMappingURL=index.js.map","import drain from 'it-drain';\nimport filter from 'it-filter';\nimport sort from 'it-sort';\nimport take from 'it-take';\nexport class BaseDatastore {\n put(key, val, options) {\n return Promise.reject(new Error('.put is not implemented'));\n }\n get(key, options) {\n return Promise.reject(new Error('.get is not implemented'));\n }\n has(key, options) {\n return Promise.reject(new Error('.has is not implemented'));\n }\n delete(key, options) {\n return Promise.reject(new Error('.delete is not implemented'));\n }\n async *putMany(source, options = {}) {\n for await (const { key, value } of source) {\n await this.put(key, value, options);\n yield key;\n }\n }\n async *getMany(source, options = {}) {\n for await (const key of source) {\n yield {\n key,\n value: await this.get(key, options)\n };\n }\n }\n async *deleteMany(source, options = {}) {\n for await (const key of source) {\n await this.delete(key, options);\n yield key;\n }\n }\n batch() {\n let puts = [];\n let dels = [];\n return {\n put(key, value) {\n puts.push({ key, value });\n },\n delete(key) {\n dels.push(key);\n },\n commit: async (options) => {\n await drain(this.putMany(puts, options));\n puts = [];\n await drain(this.deleteMany(dels, options));\n dels = [];\n }\n };\n }\n /**\n * Extending classes should override `query` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_all(q, options) {\n throw new Error('._all is not implemented');\n }\n /**\n * Extending classes should override `queryKeys` or implement this method\n */\n // eslint-disable-next-line require-yield\n async *_allKeys(q, options) {\n throw new Error('._allKeys is not implemented');\n }\n query(q, options) {\n let it = this._all(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (e) => e.key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n let i = 0;\n const offset = q.offset;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n queryKeys(q, options) {\n let it = this._allKeys(q, options);\n if (q.prefix != null) {\n const prefix = q.prefix;\n it = filter(it, (key) => key.toString().startsWith(prefix));\n }\n if (Array.isArray(q.filters)) {\n it = q.filters.reduce((it, f) => filter(it, f), it);\n }\n if (Array.isArray(q.orders)) {\n it = q.orders.reduce((it, f) => sort(it, f), it);\n }\n if (q.offset != null) {\n const offset = q.offset;\n let i = 0;\n it = filter(it, () => i++ >= offset);\n }\n if (q.limit != null) {\n it = take(it, q.limit);\n }\n return it;\n }\n}\n//# sourceMappingURL=base.js.map","import { Key } from 'interface-datastore/key';\nimport { NotFoundError } from 'interface-store';\nimport { BaseDatastore } from './base.js';\nexport class MemoryDatastore extends BaseDatastore {\n data;\n constructor() {\n super();\n this.data = new Map();\n }\n put(key, val) {\n this.data.set(key.toString(), val);\n return key;\n }\n get(key) {\n const result = this.data.get(key.toString());\n if (result == null) {\n throw new NotFoundError();\n }\n return result;\n }\n has(key) {\n return this.data.has(key.toString());\n }\n delete(key) {\n this.data.delete(key.toString());\n }\n *_all() {\n for (const [key, value] of this.data.entries()) {\n yield { key: new Key(key), value };\n }\n }\n *_allKeys() {\n for (const key of this.data.keys()) {\n yield new Key(key);\n }\n }\n}\n//# sourceMappingURL=memory.js.map","import { peerIdFromString } from '@libp2p/peer-id';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { debounce } from './utils.js';\nconst defaultAddressFilter = (addrs) => addrs;\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId(ma, peerId) {\n const observedPeerIdStr = ma.getPeerId();\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = peerIdFromString(observedPeerIdStr);\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate(multiaddr(`/p2p/${peerId.toString()}`));\n }\n }\n return ma;\n}\nexport class DefaultAddressManager {\n log;\n components;\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n listen;\n announce;\n observed;\n announceFilter;\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor(components, init = {}) {\n const { listen = [], announce = [] } = init;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:address-manager');\n this.listen = listen.map(ma => ma.toString());\n this.announce = new Set(announce.map(ma => ma.toString()));\n this.observed = new Map();\n this.announceFilter = init.announceFilter ?? defaultAddressFilter;\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = debounce(this._updatePeerStoreAddresses.bind(this), 1000);\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses();\n });\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses();\n });\n }\n [Symbol.toStringTag] = '@libp2p/address-manager';\n _updatePeerStoreAddresses() {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat([...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => multiaddr(str))).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`);\n }\n return ma;\n });\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err); });\n }\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs() {\n return Array.from(this.listen).map((a) => multiaddr(a));\n }\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs() {\n return Array.from(this.announce).map((a) => multiaddr(a));\n }\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs() {\n return Array.from(this.observed).map(([a]) => multiaddr(a));\n }\n /**\n * Add peer observed addresses\n */\n addObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return;\n }\n this.observed.set(addrString, {\n confident: false\n });\n }\n confirmObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n };\n const startingConfidence = metadata.confident;\n this.observed.set(addrString, {\n confident: true\n });\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses();\n }\n }\n removeObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n this.observed.delete(addrString);\n }\n getAddresses() {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString());\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString());\n }\n // add observed addresses we are confident in\n addrs = addrs.concat(Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma));\n // dedupe multiaddrs\n const addrSet = new Set(addrs);\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => multiaddr(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma;\n }\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma;\n }\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`);\n });\n }\n}\n//# sourceMappingURL=index.js.map","export function debounce(func, wait) {\n let timeout;\n return function () {\n const later = function () {\n timeout = undefined;\n func();\n };\n clearTimeout(timeout);\n timeout = setTimeout(later, wait);\n };\n}\n//# sourceMappingURL=utils.js.map","export function isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nexport async function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nexport async function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map","export var messages;\n(function (messages) {\n messages[\"NOT_STARTED_YET\"] = \"The libp2p node is not started yet\";\n messages[\"NOT_FOUND\"] = \"Not found\";\n})(messages || (messages = {}));\nexport class MissingServiceError extends Error {\n constructor(message = 'Missing service') {\n super(message);\n this.name = 'MissingServiceError';\n }\n}\nexport class UnmetServiceDependenciesError extends Error {\n constructor(message = 'Unmet service dependencies') {\n super(message);\n this.name = 'UnmetServiceDependenciesError';\n }\n}\nexport class NoContentRoutersError extends Error {\n constructor(message = 'No content routers available') {\n super(message);\n this.name = 'NoContentRoutersError';\n }\n}\nexport class NoPeerRoutersError extends Error {\n constructor(message = 'No peer routers available') {\n super(message);\n this.name = 'NoPeerRoutersError';\n }\n}\nexport class QueriedForSelfError extends Error {\n constructor(message = 'Should not try to find self') {\n super(message);\n this.name = 'QueriedForSelfError';\n }\n}\nexport class UnhandledProtocolError extends Error {\n constructor(message = 'Unhandled protocol error') {\n super(message);\n this.name = 'UnhandledProtocolError';\n }\n}\nexport class DuplicateProtocolHandlerError extends Error {\n constructor(message = 'Duplicate protocol handler error') {\n super(message);\n this.name = 'DuplicateProtocolHandlerError';\n }\n}\nexport class DialDeniedError extends Error {\n constructor(message = 'Dial denied error') {\n super(message);\n this.name = 'DialDeniedError';\n }\n}\nexport class NoValidAddressesError extends Error {\n constructor(message = 'No valid addresses') {\n super(message);\n this.name = 'NoValidAddressesError';\n }\n}\nexport class ConnectionInterceptedError extends Error {\n constructor(message = 'Connection intercepted') {\n super(message);\n this.name = 'ConnectionInterceptedError';\n }\n}\nexport class ConnectionDeniedError extends Error {\n constructor(message = 'Connection denied') {\n super(message);\n this.name = 'ConnectionDeniedError';\n }\n}\nexport class MuxerUnavailableError extends Error {\n constructor(message = 'Stream is not multiplexed') {\n super(message);\n this.name = 'MuxerUnavailableError';\n }\n}\nexport class EncryptionFailedError extends Error {\n constructor(message = 'Encryption failed') {\n super(message);\n this.name = 'EncryptionFailedError';\n }\n}\nexport class TransportUnavailableError extends Error {\n constructor(message = 'Transport unavailable') {\n super(message);\n this.name = 'TransportUnavailableError';\n }\n}\n//# sourceMappingURL=errors.js.map","import { serviceCapabilities, serviceDependencies } from '@libp2p/interface';\nimport { isStartable } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nimport { MissingServiceError, UnmetServiceDependenciesError } from './errors.js';\nclass DefaultComponents {\n components = {};\n _started = false;\n constructor(init = {}) {\n this.components = {};\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value;\n }\n if (this.components.logger == null) {\n this.components.logger = defaultLogger();\n }\n }\n isStarted() {\n return this._started;\n }\n async _invokeStartableMethod(methodName) {\n await Promise.all(Object.values(this.components)\n .filter(obj => isStartable(obj))\n .map(async (startable) => {\n await startable[methodName]?.();\n }));\n }\n async beforeStart() {\n await this._invokeStartableMethod('beforeStart');\n }\n async start() {\n await this._invokeStartableMethod('start');\n this._started = true;\n }\n async afterStart() {\n await this._invokeStartableMethod('afterStart');\n }\n async beforeStop() {\n await this._invokeStartableMethod('beforeStop');\n }\n async stop() {\n await this._invokeStartableMethod('stop');\n this._started = false;\n }\n async afterStop() {\n await this._invokeStartableMethod('afterStop');\n }\n}\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n];\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n];\nexport function defaultComponents(init = {}) {\n const components = new DefaultComponents(init);\n const proxy = new Proxy(components, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop];\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new MissingServiceError(`${prop} not set`);\n }\n return service;\n }\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value;\n }\n else {\n Reflect.set(target, prop, value);\n }\n return true;\n }\n });\n // @ts-expect-error component keys are proxied\n return proxy;\n}\nexport function checkServiceDependencies(components) {\n const serviceCapabilities = {};\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceCapabilities(service)) {\n serviceCapabilities[capability] = true;\n }\n }\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceDependencies(service)) {\n if (serviceCapabilities[capability] !== true) {\n throw new UnmetServiceDependenciesError(`Service \"${getServiceName(service)}\" required capability \"${capability}\" but it was not provided by any component, you may need to add additional configuration when creating your node.`);\n }\n }\n }\n}\nfunction getServiceCapabilities(service) {\n if (Array.isArray(service?.[serviceCapabilities])) {\n return service[serviceCapabilities];\n }\n return [];\n}\nfunction getServiceDependencies(service) {\n if (Array.isArray(service?.[serviceDependencies])) {\n return service[serviceDependencies];\n }\n return [];\n}\nfunction getServiceName(service) {\n return service?.[Symbol.toStringTag] ?? service?.toString() ?? 'unknown';\n}\n//# sourceMappingURL=components.js.map","import { isPrivateIp } from '@libp2p/utils/private-ip';\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nexport function connectionGater(gater = {}) {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr) => {\n const tuples = multiaddr.stringTuples();\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean(isPrivateIp(`${tuples[0][1]}`));\n }\n return false;\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n };\n}\n//# sourceMappingURL=connection-gater.browser.js.map","import { mapIterable } from './util.js';\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nexport class PeerMap {\n map;\n constructor(map) {\n this.map = new Map();\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), { key, value });\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n clear() {\n this.map.clear();\n }\n delete(peer) {\n return this.map.delete(peer.toString());\n }\n entries() {\n return mapIterable(this.map.entries(), (val) => {\n return [val[1].key, val[1].value];\n });\n }\n forEach(fn) {\n this.map.forEach((value, key) => {\n fn(value.value, value.key, this);\n });\n }\n get(peer) {\n return this.map.get(peer.toString())?.value;\n }\n has(peer) {\n return this.map.has(peer.toString());\n }\n set(peer, value) {\n this.map.set(peer.toString(), { key: peer, value });\n }\n keys() {\n return mapIterable(this.map.values(), (val) => {\n return val.key;\n });\n }\n values() {\n return mapIterable(this.map.values(), (val) => val.value);\n }\n get size() {\n return this.map.size;\n }\n}\nexport function peerMap() {\n return new PeerMap();\n}\n//# sourceMappingURL=map.js.map","import { InvalidMultiaddrError, InvalidParametersError, isPeerId } from '@libp2p/interface';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { isMultiaddr } from '@multiformats/multiaddr';\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nexport function getPeerAddress(peer) {\n if (isPeerId(peer)) {\n return { peerId: peer, multiaddrs: [] };\n }\n if (!Array.isArray(peer)) {\n peer = [peer];\n }\n let peerId;\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId();\n peerId = peerIdStr == null ? undefined : peerIdFromString(peerIdStr);\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!isMultiaddr(ma)) {\n throw new InvalidMultiaddrError('Invalid multiaddr');\n }\n const maPeerIdStr = ma.getPeerId();\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id');\n }\n }\n else {\n const maPeerId = peerIdFromString(maPeerIdStr);\n if (peerId?.equals(maPeerId) !== true) {\n throw new InvalidParametersError('Multiaddrs must all have the same peer id or have no peer id');\n }\n }\n });\n }\n return {\n peerId,\n multiaddrs: peer\n };\n}\n//# sourceMappingURL=get-peer.js.map","/**\n * Close the passed stream, falling back to aborting the stream if closing\n * cleanly fails.\n */\nexport async function safelyCloseStream(stream, options) {\n try {\n await stream?.close(options);\n }\n catch (err) {\n stream?.abort(err);\n }\n}\n/**\n * These are speculative protocols that are run automatically on connection open\n * so are usually not the reason the connection was opened.\n *\n * Consequently when requested it should be safe to close connections that only\n * have these protocol streams open.\n */\nconst DEFAULT_CLOSABLE_PROTOCOLS = [\n // identify\n '/ipfs/id/1.0.0',\n // identify-push\n '/ipfs/id/push/1.0.0',\n // autonat\n '/libp2p/autonat/1.0.0',\n // dcutr\n '/libp2p/dcutr'\n];\n/**\n * Close the passed connection if it has no streams, or only closable protocol\n * streams, falling back to aborting the connection if closing it cleanly fails.\n */\nexport async function safelyCloseConnectionIfUnused(connection, options) {\n const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? [];\n const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS;\n // if the connection has protocols not in the closable protocols list, do not\n // close the connection\n if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {\n return;\n }\n try {\n await connection?.close(options);\n }\n catch (err) {\n connection?.abort(err);\n }\n}\n//# sourceMappingURL=close.js.map","import { PeerMap } from '@libp2p/peer-collections';\nimport { safelyCloseConnectionIfUnused } from '@libp2p/utils/close';\nimport { MAX_CONNECTIONS } from './constants.js';\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n allow: []\n};\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nexport class ConnectionPruner {\n maxConnections;\n connectionManager;\n peerStore;\n allow;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n this.allow = init.allow ?? defaultOptions.allow;\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner');\n this.maybePruneConnections = this.maybePruneConnections.bind(this);\n }\n start() {\n this.events.addEventListener('connection:open', this.maybePruneConnections);\n }\n stop() {\n this.events.removeEventListener('connection:open', this.maybePruneConnections);\n }\n maybePruneConnections() {\n this._maybePruneConnections()\n .catch(err => {\n this.log.error('error while pruning connections %e', err);\n });\n }\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async _maybePruneConnections() {\n const connections = this.connectionManager.getConnections();\n const numConnections = connections.length;\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections);\n if (numConnections <= this.maxConnections) {\n return;\n }\n const peerValues = new PeerMap();\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer;\n if (peerValues.has(remotePeer)) {\n continue;\n }\n peerValues.set(remotePeer, 0);\n try {\n const peer = await this.peerStore.get(remotePeer);\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n this.log.error('error loading peer tags', err);\n }\n }\n }\n const sortedConnections = this.sortConnections(connections, peerValues);\n // close some connections\n const toPrune = Math.max(numConnections - this.maxConnections, 0);\n const toClose = [];\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer);\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString());\n });\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection);\n }\n if (toClose.length === toPrune) {\n break;\n }\n }\n // close connections\n await Promise.all(toClose.map(async (connection) => {\n await safelyCloseConnectionIfUnused(connection, {\n signal: AbortSignal.timeout(1000)\n });\n }));\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose });\n }\n sortConnections(connections, peerValues) {\n return connections\n // sort by connection age, newest to oldest\n .sort((a, b) => {\n const connectionALifespan = a.timeline.open;\n const connectionBLifespan = b.timeline.open;\n if (connectionALifespan < connectionBLifespan) {\n return 1;\n }\n if (connectionALifespan > connectionBLifespan) {\n return -1;\n }\n return 0;\n })\n // sort by direction, incoming first then outgoing\n .sort((a, b) => {\n if (a.direction === 'outbound' && b.direction === 'inbound') {\n return 1;\n }\n if (a.direction === 'inbound' && b.direction === 'outbound') {\n return -1;\n }\n return 0;\n })\n // sort by number of streams, lowest to highest\n .sort((a, b) => {\n if (a.streams.length > b.streams.length) {\n return 1;\n }\n if (a.streams.length < b.streams.length) {\n return -1;\n }\n return 0;\n })\n // sort by tag value, lowest to highest\n .sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0;\n const peerBValue = peerValues.get(b.remotePeer) ?? 0;\n if (peerAValue > peerBValue) {\n return 1;\n }\n if (peerAValue < peerBValue) {\n return -1;\n }\n return 0;\n });\n }\n}\n//# sourceMappingURL=connection-pruner.js.map","export * from './constants.defaults.js';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxConnections\n */\nexport const MAX_CONNECTIONS = 100;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelDials\n */\nexport const MAX_PARALLEL_DIALS = 50;\n//# sourceMappingURL=constants.browser.js.map","/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#dialTimeout\n */\nexport const DIAL_TIMEOUT = 5e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#upgradeTimeout\n */\nexport const UPGRADE_TIMEOUT = 3e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#protocolNegotiationTimeout\n */\nexport const PROTOCOL_NEGOTIATION_TIMEOUT = 2e3;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxPeerAddrsToDial\n */\nexport const MAX_PEER_ADDRS_TO_DIAL = 25;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#inboundConnectionThreshold\n */\nexport const INBOUND_CONNECTION_THRESHOLD = 5;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxIncomingPendingConnections\n */\nexport const MAX_INCOMING_PENDING_CONNECTIONS = 10;\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxParallelReconnects\n */\nexport const MAX_PARALLEL_RECONNECTS = 5;\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempt failed with the timestamp\n * stored as a string.\n *\n * Used to insure we do not endlessly try to auto dial peers we have recently\n * failed to dial.\n */\nexport const LAST_DIAL_FAILURE_KEY = 'last-dial-failure';\n/**\n * Store as part of the peer store metadata for a given peer, the value for this\n * key is a timestamp of the last time a dial attempt succeeded with the\n * timestamp stored as a string.\n */\nexport const LAST_DIAL_SUCCESS_KEY = 'last-dial-success';\n/**\n * @see https://libp2p.github.io/js-libp2p/interfaces/index._internal_.ConnectionManagerConfig.html#maxDialQueueLength\n */\nexport const MAX_DIAL_QUEUE_LENGTH = 500;\n//# sourceMappingURL=constants.defaults.js.map","/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n/**\n * An abort error class that extends error\n */\nexport class AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nexport async function raceEvent(emitter, eventName, signal, opts) {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n if (signal?.aborted === true) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n function removeListeners() {\n signal?.removeEventListener('abort', abortListener);\n emitter.removeEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.removeEventListener(opts.errorEvent, errorEventListener);\n }\n }\n const eventListener = (evt) => {\n try {\n if (opts?.filter?.(evt) === false) {\n return;\n }\n }\n catch (err) {\n removeListeners();\n reject(err);\n return;\n }\n removeListeners();\n resolve(evt);\n };\n const errorEventListener = (evt) => {\n removeListeners();\n reject(evt.detail);\n };\n const abortListener = () => {\n removeListeners();\n reject(error);\n };\n signal?.addEventListener('abort', abortListener);\n emitter.addEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.addEventListener(opts.errorEvent, errorEventListener);\n }\n });\n}\n//# sourceMappingURL=index.js.map","import { AbortError } from '@libp2p/interface';\nimport pDefer from 'p-defer';\nexport class JobRecipient {\n deferred;\n signal;\n constructor(signal) {\n this.signal = signal;\n this.deferred = pDefer();\n this.onAbort = this.onAbort.bind(this);\n this.signal?.addEventListener('abort', this.onAbort);\n }\n onAbort() {\n this.deferred.reject(this.signal?.reason ?? new AbortError());\n }\n cleanup() {\n this.signal?.removeEventListener('abort', this.onAbort);\n }\n}\n//# sourceMappingURL=recipient.js.map","import { AbortError, setMaxListeners } from '@libp2p/interface';\nimport { raceSignal } from 'race-signal';\nimport { JobRecipient } from './recipient.js';\n/**\n * Returns a random string\n */\nfunction randomId() {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`;\n}\nexport class Job {\n id;\n fn;\n options;\n recipients;\n status;\n timeline;\n controller;\n constructor(fn, options) {\n this.id = randomId();\n this.status = 'queued';\n this.fn = fn;\n this.options = options;\n this.recipients = [];\n this.timeline = {\n created: Date.now()\n };\n this.controller = new AbortController();\n setMaxListeners(Infinity, this.controller.signal);\n this.onAbort = this.onAbort.bind(this);\n }\n abort(err) {\n this.controller.abort(err);\n }\n onAbort() {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true);\n }, true);\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new AbortError());\n this.cleanup();\n }\n }\n async join(options = {}) {\n const recipient = new JobRecipient(options.signal);\n this.recipients.push(recipient);\n options.signal?.addEventListener('abort', this.onAbort);\n return recipient.deferred.promise;\n }\n async run() {\n this.status = 'running';\n this.timeline.started = Date.now();\n try {\n this.controller.signal.throwIfAborted();\n const result = await raceSignal(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal);\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result);\n });\n this.status = 'complete';\n }\n catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err);\n });\n this.status = 'errored';\n }\n finally {\n this.timeline.finished = Date.now();\n this.cleanup();\n }\n }\n cleanup() {\n this.recipients.forEach(recipient => {\n recipient.cleanup();\n recipient.signal?.removeEventListener('abort', this.onAbort);\n });\n }\n}\n//# sourceMappingURL=job.js.map","import { AbortError, TypedEventEmitter } from '@libp2p/interface';\nimport { pushable } from 'it-pushable';\nimport { raceEvent } from 'race-event';\nimport { QueueFullError } from '../errors.js';\nimport { Job } from './job.js';\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nexport class Queue extends TypedEventEmitter {\n concurrency;\n maxSize;\n queue;\n pending;\n sort;\n constructor(init = {}) {\n super();\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY;\n this.maxSize = init.maxSize ?? Number.POSITIVE_INFINITY;\n this.pending = 0;\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n };\n }\n });\n }\n this.sort = init.sort;\n this.queue = [];\n }\n tryToStartAnother() {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty');\n });\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle');\n });\n }\n return false;\n }\n if (this.pending < this.concurrency) {\n let job;\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j;\n break;\n }\n }\n if (job == null) {\n return false;\n }\n this.safeDispatchEvent('active');\n this.pending++;\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n this.pending--;\n this.tryToStartAnother();\n this.safeDispatchEvent('next');\n });\n return true;\n }\n return false;\n }\n enqueue(job) {\n this.queue.push(job);\n if (this.sort != null) {\n this.queue.sort(this.sort);\n }\n }\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options) {\n options?.signal?.throwIfAborted();\n if (this.size === this.maxSize) {\n throw new QueueFullError();\n }\n const job = new Job(fn, options);\n this.enqueue(job);\n this.safeDispatchEvent('add');\n this.tryToStartAnother();\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result });\n this.safeDispatchEvent('success', { detail: { job, result } });\n return result;\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n }\n this.safeDispatchEvent('error', { detail: err });\n this.safeDispatchEvent('failure', { detail: { job, error: err } });\n throw err;\n });\n }\n /**\n * Clear the queue\n */\n clear() {\n this.queue.splice(0, this.queue.length);\n }\n /**\n * Abort all jobs in the queue and clear it\n */\n abort() {\n this.queue.forEach(job => {\n job.abort(new AbortError());\n });\n this.clear();\n }\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty(options) {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return;\n }\n await raceEvent(this, 'empty', options?.signal);\n }\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan(limit, options) {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return;\n }\n await raceEvent(this, 'next', options?.signal, {\n filter: () => this.size < limit\n });\n }\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle(options) {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return;\n }\n await raceEvent(this, 'idle', options?.signal);\n }\n /**\n * Size of the queue including running items\n */\n get size() {\n return this.queue.length;\n }\n /**\n * The number of queued items waiting to run.\n */\n get queued() {\n return this.queue.length - this.pending;\n }\n /**\n * The number of items currently running.\n */\n get running() {\n return this.pending;\n }\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async *toGenerator(options) {\n options?.signal?.throwIfAborted();\n const stream = pushable({\n objectMode: true\n });\n const cleanup = (err) => {\n if (err != null) {\n this.abort();\n }\n else {\n this.clear();\n }\n stream.end(err);\n };\n const onQueueJobComplete = (evt) => {\n if (evt.detail != null) {\n stream.push(evt.detail);\n }\n };\n const onQueueError = (evt) => {\n cleanup(evt.detail);\n };\n const onQueueIdle = () => {\n cleanup();\n };\n // clear the queue and throw if the query is aborted\n const onSignalAbort = () => {\n cleanup(new AbortError('Queue aborted'));\n };\n // add listeners\n this.addEventListener('completed', onQueueJobComplete);\n this.addEventListener('error', onQueueError);\n this.addEventListener('idle', onQueueIdle);\n options?.signal?.addEventListener('abort', onSignalAbort);\n try {\n yield* stream;\n }\n finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete);\n this.removeEventListener('error', onQueueError);\n this.removeEventListener('idle', onQueueIdle);\n options?.signal?.removeEventListener('abort', onSignalAbort);\n // empty the queue for when the user has broken out of a loop early\n cleanup();\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { Queue } from './queue/index.js';\nexport class PriorityQueue extends Queue {\n constructor(init = {}) {\n super({\n ...init,\n sort: (a, b) => {\n if (a.options.priority > b.options.priority) {\n return -1;\n }\n if (a.options.priority < b.options.priority) {\n return 1;\n }\n return 0;\n }\n });\n }\n}\n//# sourceMappingURL=priority-queue.js.map","/**\n * Takes an array of AbortSignals and returns a single signal.\n * If any signals are aborted, the returned signal will be aborted.\n */\nexport function anySignal(signals) {\n const controller = new globalThis.AbortController();\n function onAbort() {\n controller.abort();\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n for (const signal of signals) {\n if (signal?.aborted === true) {\n onAbort();\n break;\n }\n if (signal?.addEventListener != null) {\n signal.addEventListener('abort', onAbort);\n }\n }\n function clear() {\n for (const signal of signals) {\n if (signal?.removeEventListener != null) {\n signal.removeEventListener('abort', onAbort);\n }\n }\n }\n const signal = controller.signal;\n signal.clear = clear;\n return signal;\n}\n//# sourceMappingURL=index.js.map","import { isPrivate } from '@libp2p/utils/multiaddr/is-private';\nimport { Circuit, WebSockets, WebSocketsSecure, WebRTC, WebRTCDirect, WebTransport, TCP } from '@multiformats/multiaddr-matcher';\n/**\n * Sorts addresses by order of reliability, where they have presented the fewest\n * problems:\n *\n * TCP -> WebSockets/Secure -> WebRTC -> WebRTCDirect -> WebTransport\n */\n// eslint-disable-next-line complexity\nexport function reliableTransportsFirst(a, b) {\n const isATCP = TCP.exactMatch(a.multiaddr);\n const isBTCP = TCP.exactMatch(b.multiaddr);\n if (isATCP && !isBTCP) {\n return -1;\n }\n if (!isATCP && isBTCP) {\n return 1;\n }\n const isAWebSocketSecure = WebSocketsSecure.exactMatch(a.multiaddr);\n const isBWebSocketSecure = WebSocketsSecure.exactMatch(b.multiaddr);\n if (isAWebSocketSecure && !isBWebSocketSecure) {\n return -1;\n }\n if (!isAWebSocketSecure && isBWebSocketSecure) {\n return 1;\n }\n const isAWebSocket = WebSockets.exactMatch(a.multiaddr);\n const isBWebSocket = WebSockets.exactMatch(b.multiaddr);\n if (isAWebSocket && !isBWebSocket) {\n return -1;\n }\n if (!isAWebSocket && isBWebSocket) {\n return 1;\n }\n const isAWebRTC = WebRTC.exactMatch(a.multiaddr);\n const isBWebRTC = WebRTC.exactMatch(b.multiaddr);\n if (isAWebRTC && !isBWebRTC) {\n return -1;\n }\n if (!isAWebRTC && isBWebRTC) {\n return 1;\n }\n const isAWebRTCDirect = WebRTCDirect.exactMatch(a.multiaddr);\n const isBWebRTCDirect = WebRTCDirect.exactMatch(b.multiaddr);\n if (isAWebRTCDirect && !isBWebRTCDirect) {\n return -1;\n }\n if (!isAWebRTCDirect && isBWebRTCDirect) {\n return 1;\n }\n const isAWebTransport = WebTransport.exactMatch(a.multiaddr);\n const isBWebTransport = WebTransport.exactMatch(b.multiaddr);\n if (isAWebTransport && !isBWebTransport) {\n return -1;\n }\n if (!isAWebTransport && isBWebTransport) {\n return 1;\n }\n // ... everything else\n return 0;\n}\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nexport function publicAddressesFirst(a, b) {\n const isAPrivate = isPrivate(a.multiaddr);\n const isBPrivate = isPrivate(b.multiaddr);\n if (isAPrivate && !isBPrivate) {\n return 1;\n }\n else if (!isAPrivate && isBPrivate) {\n return -1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nexport function certifiedAddressesFirst(a, b) {\n if (a.isCertified && !b.isCertified) {\n return -1;\n }\n else if (!a.isCertified && b.isCertified) {\n return 1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * end of the array.\n */\nexport function circuitRelayAddressesLast(a, b) {\n const isACircuit = Circuit.exactMatch(a.multiaddr);\n const isBCircuit = Circuit.exactMatch(b.multiaddr);\n if (isACircuit && !isBCircuit) {\n return 1;\n }\n else if (!isACircuit && isBCircuit) {\n return -1;\n }\n return 0;\n}\nexport function defaultAddressSorter(addresses) {\n return addresses\n .sort(reliableTransportsFirst)\n .sort(certifiedAddressesFirst)\n .sort(circuitRelayAddressesLast)\n .sort(publicAddressesFirst);\n}\n//# sourceMappingURL=address-sorter.js.map","/* eslint-disable max-depth */\nimport { TimeoutError, DialError, setMaxListeners, AbortError } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { PriorityQueue } from '@libp2p/utils/priority-queue';\nimport { resolvers, multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { Circuit } from '@multiformats/multiaddr-matcher';\nimport { anySignal } from 'any-signal';\nimport { CustomProgressEvent } from 'progress-events';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { DialDeniedError, NoValidAddressesError } from '../errors.js';\nimport { getPeerAddress } from '../get-peer.js';\nimport { defaultAddressSorter } from './address-sorter.js';\nimport { DIAL_TIMEOUT, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL, LAST_DIAL_FAILURE_KEY, MAX_DIAL_QUEUE_LENGTH, LAST_DIAL_SUCCESS_KEY } from './constants.js';\nimport { resolveMultiaddrs } from './utils.js';\nimport { DEFAULT_DIAL_PRIORITY } from './index.js';\nconst defaultOptions = {\n maxParallelDials: MAX_PARALLEL_DIALS,\n maxDialQueueLength: MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: dnsaddrResolver\n }\n};\nexport class DialQueue {\n queue;\n components;\n addressSorter;\n maxPeerAddrsToDial;\n maxDialQueueLength;\n dialTimeout;\n shutDownController;\n connections;\n log;\n constructor(components, init = {}) {\n this.addressSorter = init.addressSorter;\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial;\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength;\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout;\n this.connections = init.connections ?? new PeerMap();\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue');\n this.components = components;\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n resolvers.set(key, value);\n }\n // controls dial concurrency\n this.queue = new PriorityQueue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n });\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n if (event.detail.name !== AbortError.name) {\n this.log.error('error in dial queue - %e', event.detail);\n }\n });\n }\n start() {\n this.shutDownController = new AbortController();\n setMaxListeners(Infinity, this.shutDownController.signal);\n }\n /**\n * Clears any pending dials\n */\n stop() {\n this.shutDownController.abort();\n this.queue.abort();\n }\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial(peerIdOrMultiaddr, options = {}) {\n const { peerId, multiaddrs } = getPeerAddress(peerIdOrMultiaddr);\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false;\n }\n if (conn.remotePeer.equals(peerId)) {\n return true;\n }\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr);\n });\n });\n if (existingConnection?.status === 'open') {\n this.log('already connected to %a', existingConnection.remoteAddr);\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true;\n }\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs;\n if (addresses == null) {\n return false;\n }\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true;\n }\n }\n return false;\n });\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId);\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString());\n }\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-in-dial-queue'));\n return existingDial.join(options);\n }\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new DialError('Dial queue is full');\n }\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()));\n options.onProgress?.(new CustomProgressEvent('dial-queue:add-to-dial-queue'));\n return this.queue.add(async (options) => {\n options?.onProgress?.(new CustomProgressEvent('dial-queue:start-dial'));\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal);\n let addrsToDial;\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n });\n options?.onProgress?.(new CustomProgressEvent('dial-queue:calculated-addresses', addrsToDial));\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr);\n });\n }\n catch (err) {\n signal.clear();\n throw err;\n }\n try {\n let dialed = 0;\n const errors = [];\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId);\n throw new DialError('Peer had more than maxPeerAddrsToDial');\n }\n dialed++;\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n });\n this.log('dial to %a succeeded', address.multiaddr);\n // record the successful dial and the address\n try {\n await this.components.peerStore.merge(conn.remotePeer, {\n multiaddrs: [\n conn.remoteAddr\n ],\n metadata: {\n [LAST_DIAL_SUCCESS_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n return conn;\n }\n catch (err) {\n this.log.error('dial failed to %a', address.multiaddr, err);\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.merge(peerId, {\n metadata: {\n [LAST_DIAL_FAILURE_KEY]: uint8ArrayFromString(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n }\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new TimeoutError(err.message);\n }\n errors.push(err);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new AggregateError(errors, 'All multiaddr dials failed');\n }\n finally {\n // clean up abort signals/controllers\n signal.clear();\n }\n }, {\n peerId,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal,\n onProgress: options.onProgress\n });\n }\n createDialAbortController(userSignal) {\n // let any signal abort the dial\n const signal = anySignal([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ]);\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, signal);\n return signal;\n }\n // eslint-disable-next-line complexity\n async calculateMultiaddrs(peerId, multiaddrs = new Set(), options = {}) {\n const addrs = [...multiaddrs].map(ma => ({\n multiaddr: multiaddr(ma),\n isCertified: false\n }));\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new DialError('Tried to dial self');\n }\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new DialDeniedError('The dial request is blocked by gater.allowDialPeer');\n }\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId);\n try {\n const peer = await this.components.peerStore.get(peerId);\n addrs.push(...peer.addresses);\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n throw err;\n }\n }\n }\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId);\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId);\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })));\n }\n catch (err) {\n if (err.name !== 'NoPeerRoutersError') {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err);\n }\n }\n }\n }\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(addrs.map(async (addr) => {\n const result = await resolveMultiaddrs(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n });\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr;\n }\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }));\n })))\n .flat();\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`;\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop();\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr;\n }\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n };\n }\n return addr;\n });\n }\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.dialTransportForMultiaddr(addr.multiaddr) == null) {\n return false;\n }\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId();\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId);\n }\n return true;\n });\n // deduplicate addresses\n const dedupedAddrs = new Map();\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString();\n const existing = dedupedAddrs.get(maStr);\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false;\n continue;\n }\n dedupedAddrs.set(maStr, addr);\n }\n const dedupedMultiaddrs = [...dedupedAddrs.values()];\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new NoValidAddressesError('The dial request has no valid addresses');\n }\n const gatedAdrs = [];\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue;\n }\n gatedAdrs.push(addr);\n }\n const sortedGatedAddrs = this.addressSorter == null ? defaultAddressSorter(gatedAdrs) : gatedAdrs.sort(this.addressSorter);\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new DialDeniedError('The connection gater denied all addresses in the dial request');\n }\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()));\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()));\n return sortedGatedAddrs;\n }\n async isDialable(multiaddr, options = {}) {\n if (!Array.isArray(multiaddr)) {\n multiaddr = [multiaddr];\n }\n try {\n const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options);\n if (options.runOnLimitedConnection === false) {\n // return true if any resolved multiaddrs are not relay addresses\n return addresses.find(addr => {\n return !Circuit.matches(addr.multiaddr);\n }) != null;\n }\n return true;\n }\n catch (err) {\n this.log.trace('error calculating if multiaddr(s) were dialable', err);\n }\n return false;\n }\n}\n//# sourceMappingURL=dial-queue.js.map","import { resolvers } from '@multiformats/multiaddr';\n/**\n * Recursively resolve DNSADDR multiaddrs\n */\nexport async function resolveMultiaddrs(ma, options) {\n // check multiaddr resolvers\n let resolvable = false;\n for (const key of resolvers.keys()) {\n resolvable = ma.protoNames().includes(key);\n if (resolvable) {\n break;\n }\n }\n // return multiaddr if it is not resolvable\n if (!resolvable) {\n return [ma];\n }\n const output = await ma.resolve(options);\n options.log('resolved %s to', ma, output.map(ma => ma.toString()));\n return output;\n}\n//# sourceMappingURL=utils.js.map","/**\n * When a peer that is tagged with this prefix disconnects, we will attempt to\n * redial it, up to a limit.\n *\n * To allow multiple components to add/remove their own keep-alive tags without\n * accidentally overwriting those of other components, attach a unique suffix to\n * the tag, e.g. `keep-alive-circuit-relay` or `keep-alive-kad-dht`, etc.\n */\nexport const KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map","import { Queue } from './queue/index.js';\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nexport class PeerQueue extends Queue {\n has(peerId) {\n return this.find(peerId) != null;\n }\n find(peerId) {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId);\n });\n }\n}\n//# sourceMappingURL=peer-queue.js.map","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Load failed', // Safari 17+\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\t// We do an extra check for Safari 17+ as it has a very generic error message.\n\t// Network errors in Safari have no stack.\n\tif (error.message === 'Load failed') {\n\t\treturn error.stack === undefined;\n\t}\n\n\treturn errorMessages.has(error.message);\n}\n","import retry from 'retry';\nimport isNetworkError from 'is-network-error';\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nexport default async function pRetry(input, options) {\n\treturn new Promise((resolve, reject) => {\n\t\toptions = {...options};\n\t\toptions.onFailedAttempt ??= () => {};\n\t\toptions.shouldRetry ??= () => true;\n\t\toptions.retries ??= 10;\n\n\t\tconst operation = retry.operation(options);\n\n\t\tconst abortHandler = () => {\n\t\t\toperation.stop();\n\t\t\treject(options.signal?.reason);\n\t\t};\n\n\t\tif (options.signal && !options.signal.aborted) {\n\t\t\toptions.signal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tconst cleanUp = () => {\n\t\t\toptions.signal?.removeEventListener('abort', abortHandler);\n\t\t\toperation.stop();\n\t\t};\n\n\t\toperation.attempt(async attemptNumber => {\n\t\t\ttry {\n\t\t\t\tconst result = await input(attemptNumber);\n\t\t\t\tcleanUp();\n\t\t\t\tresolve(result);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof AbortError) {\n\t\t\t\t\t\tthrow error.originalError;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof TypeError && !isNetworkError(error)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\n\t\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\t\tif (!(await options.shouldRetry(error))) {\n\t\t\t\t\t\toperation.stop();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\n\t\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\t\tthrow operation.mainError();\n\t\t\t\t\t}\n\t\t\t\t} catch (finalError) {\n\t\t\t\t\tdecorateErrorWithCounts(finalError, attemptNumber, options);\n\t\t\t\t\tcleanUp();\n\t\t\t\t\treject(finalError);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n","import { KEEP_ALIVE } from '@libp2p/interface';\nimport { PeerQueue } from '@libp2p/utils/peer-queue';\nimport pRetry from 'p-retry';\nimport { MAX_PARALLEL_RECONNECTS } from './constants.js';\n/**\n * When peers tagged with `KEEP_ALIVE` disconnect, this component attempts to\n * redial them\n */\nexport class ReconnectQueue {\n log;\n queue;\n started;\n peerStore;\n retries;\n retryInterval;\n backoffFactor;\n connectionManager;\n events;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:reconnect-queue');\n this.peerStore = components.peerStore;\n this.connectionManager = components.connectionManager;\n this.queue = new PeerQueue({\n concurrency: init.maxParallelReconnects ?? MAX_PARALLEL_RECONNECTS,\n metricName: 'libp2p_reconnect_queue',\n metrics: components.metrics\n });\n this.started = false;\n this.retries = init.retries ?? 5;\n this.backoffFactor = init.backoffFactor;\n this.retryInterval = init.retryInterval;\n this.events = components.events;\n components.events.addEventListener('peer:disconnect', (evt) => {\n this.maybeReconnect(evt.detail)\n .catch(err => {\n this.log.error('failed to maybe reconnect to %p - %e', evt.detail, err);\n });\n });\n }\n async maybeReconnect(peerId) {\n if (!this.started) {\n return;\n }\n const peer = await this.peerStore.get(peerId);\n if (!hasKeepAliveTag(peer)) {\n return;\n }\n if (this.queue.has(peerId)) {\n return;\n }\n this.queue.add(async (options) => {\n await pRetry(async (attempt) => {\n if (!this.started) {\n return;\n }\n try {\n await this.connectionManager.openConnection(peerId, {\n signal: options?.signal\n });\n }\n catch (err) {\n this.log('reconnecting to %p attempt %d of %d failed - %e', peerId, attempt, this.retries, err);\n throw err;\n }\n }, {\n signal: options?.signal,\n retries: this.retries,\n factor: this.backoffFactor,\n minTimeout: this.retryInterval\n });\n }, {\n peerId\n })\n .catch(async (err) => {\n this.log.error('failed to reconnect to %p - %e', peerId, err);\n const tags = {};\n [...peer.tags.keys()].forEach(key => {\n if (key.startsWith(KEEP_ALIVE)) {\n tags[key] = undefined;\n }\n });\n await this.peerStore.merge(peerId, {\n tags\n });\n this.events.safeDispatchEvent('peer:reconnect-failure', {\n detail: peerId\n });\n })\n .catch(async (err) => {\n this.log.error('failed to remove keep-alive tag from %p - %e', peerId, err);\n });\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers = await this.peerStore.all({\n filters: [\n (peer) => hasKeepAliveTag(peer)\n ]\n });\n await Promise.all(keepAlivePeers.map(async (peer) => {\n await this.connectionManager.openConnection(peer.id)\n .catch(err => {\n this.log.error(err);\n });\n }));\n })\n .catch(err => {\n this.log.error(err);\n });\n }\n stop() {\n this.started = false;\n this.queue.abort();\n }\n}\nfunction hasKeepAliveTag(peer) {\n for (const tag of peer.tags.keys()) {\n if (tag.startsWith(KEEP_ALIVE)) {\n return true;\n }\n }\n return false;\n}\n//# sourceMappingURL=reconnect-queue.js.map","import { ConnectionClosedError, InvalidMultiaddrError, InvalidParametersError, InvalidPeerIdError, NotStartedError, start, stop } from '@libp2p/interface';\nimport { PeerMap } from '@libp2p/peer-collections';\nimport { RateLimiter } from '@libp2p/utils/rate-limiter';\nimport { multiaddr } from '@multiformats/multiaddr';\nimport { dnsaddrResolver } from '@multiformats/multiaddr/resolvers';\nimport { CustomProgressEvent } from 'progress-events';\nimport { getPeerAddress } from '../get-peer.js';\nimport { ConnectionPruner } from './connection-pruner.js';\nimport { DIAL_TIMEOUT, INBOUND_CONNECTION_THRESHOLD, MAX_CONNECTIONS, MAX_DIAL_QUEUE_LENGTH, MAX_INCOMING_PENDING_CONNECTIONS, MAX_PARALLEL_DIALS, MAX_PEER_ADDRS_TO_DIAL } from './constants.js';\nimport { DialQueue } from './dial-queue.js';\nimport { ReconnectQueue } from './reconnect-queue.js';\nexport const DEFAULT_DIAL_PRIORITY = 50;\nconst defaultOptions = {\n maxConnections: MAX_CONNECTIONS,\n inboundConnectionThreshold: INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: MAX_INCOMING_PENDING_CONNECTIONS\n};\n/**\n * Responsible for managing known connections.\n */\nexport class DefaultConnectionManager {\n started;\n connections;\n allow;\n deny;\n maxIncomingPendingConnections;\n incomingPendingConnections;\n outboundPendingConnections;\n maxConnections;\n dialQueue;\n reconnectQueue;\n connectionPruner;\n inboundConnectionRateLimiter;\n peerStore;\n metrics;\n events;\n log;\n peerId;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n if (this.maxConnections < 1) {\n throw new InvalidParametersError('Connection Manager maxConnections must be greater than 0');\n }\n /**\n * Map of connections per peer\n */\n this.connections = new PeerMap();\n this.started = false;\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.metrics = components.metrics;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager');\n this.onConnect = this.onConnect.bind(this);\n this.onDisconnect = this.onDisconnect.bind(this);\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => multiaddr(ma));\n this.deny = (init.deny ?? []).map(ma => multiaddr(ma));\n this.incomingPendingConnections = 0;\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections;\n this.outboundPendingConnections = 0;\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n });\n // controls what happens when we have too many connections\n this.connectionPruner = new ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n });\n this.dialQueue = new DialQueue(components, {\n addressSorter: init.addressSorter,\n maxParallelDials: init.maxParallelDials ?? MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: dnsaddrResolver\n },\n connections: this.connections\n });\n this.reconnectQueue = new ReconnectQueue({\n events: components.events,\n peerStore: components.peerStore,\n logger: components.logger,\n connectionManager: this\n }, {\n retries: init.reconnectRetries,\n retryInterval: init.reconnectRetryInterval,\n backoffFactor: init.reconnectBackoffFactor,\n maxParallelReconnects: init.maxParallelReconnects\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-manager';\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start() {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n 'inbound pending': this.incomingPendingConnections,\n outbound: 0,\n 'outbound pending': this.outboundPendingConnections\n };\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n metric[conn.direction]++;\n }\n }\n return metric;\n }\n });\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n metric[key] = (metric[key] ?? 0) + 1;\n }\n }\n }\n return metric;\n }\n });\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams = {};\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n streams[key] = (streams[key] ?? 0) + 1;\n }\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? [];\n allStreams[protocol].push(count);\n }\n }\n }\n const metric = {};\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b);\n const index = Math.floor(counts.length * 0.9);\n metric[protocol] = counts[index];\n }\n return metric;\n }\n });\n this.events.addEventListener('connection:open', this.onConnect);\n this.events.addEventListener('connection:close', this.onDisconnect);\n await start(this.dialQueue, this.reconnectQueue, this.connectionPruner);\n this.started = true;\n this.log('started');\n }\n /**\n * Stops the Connection Manager\n */\n async stop() {\n this.events.removeEventListener('connection:open', this.onConnect);\n this.events.removeEventListener('connection:close', this.onDisconnect);\n await stop(this.reconnectQueue, this.dialQueue, this.connectionPruner);\n // Close all connections we're tracking\n const tasks = [];\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n })());\n }\n }\n this.log('closing %d connections', tasks.length);\n await Promise.all(tasks);\n this.connections.clear();\n this.log('stopped');\n }\n onConnect(evt) {\n void this._onConnect(evt).catch(err => {\n this.log.error(err);\n });\n }\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close();\n return;\n }\n if (connection.status !== 'open') {\n // this can happen when the remote closes the connection immediately after\n // opening\n return;\n }\n const peerId = connection.remotePeer;\n const isNewPeer = !this.connections.has(peerId);\n const storedConns = this.connections.get(peerId) ?? [];\n storedConns.push(connection);\n this.connections.set(peerId, storedConns);\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n });\n }\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer });\n }\n }\n /**\n * Removes the connection from tracking\n */\n onDisconnect(evt) {\n const { detail: connection } = evt;\n const peerId = connection.remotePeer;\n const peerConns = this.connections.get(peerId) ?? [];\n // remove closed connection\n const filteredPeerConns = peerConns.filter(conn => conn.id !== connection.id);\n // update peer connections\n this.connections.set(peerId, filteredPeerConns);\n if (filteredPeerConns.length === 0) {\n // trigger disconnect event if no connections remain\n this.log('onDisconnect remove all connections for peer %p', peerId);\n this.connections.delete(peerId);\n // broadcast disconnect event\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer });\n }\n }\n getConnections(peerId) {\n if (peerId != null) {\n return this.connections.get(peerId) ?? [];\n }\n let conns = [];\n for (const c of this.connections.values()) {\n conns = conns.concat(c);\n }\n return conns;\n }\n getConnectionsMap() {\n return this.connections;\n }\n async openConnection(peerIdOrMultiaddr, options = {}) {\n if (!this.started) {\n throw new NotStartedError('Not started');\n }\n this.outboundPendingConnections++;\n try {\n options.signal?.throwIfAborted();\n const { peerId } = getPeerAddress(peerIdOrMultiaddr);\n if (this.peerId.equals(peerId)) {\n throw new InvalidPeerIdError('Can not dial self');\n }\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId);\n const existingConnection = this.getConnections(peerId)\n .find(conn => conn.limits == null);\n if (existingConnection != null) {\n this.log('had an existing non-limited connection to %p', peerId);\n options.onProgress?.(new CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n }\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n });\n if (connection.status !== 'open') {\n throw new ConnectionClosedError('Remote closed connection during opening');\n }\n let peerConnections = this.connections.get(connection.remotePeer);\n if (peerConnections == null) {\n peerConnections = [];\n this.connections.set(connection.remotePeer, peerConnections);\n }\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false;\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true;\n }\n // make sure we don't already have a connection to this multiaddr\n if (options.force !== true && conn.id !== connection.id && conn.remoteAddr.equals(connection.remoteAddr)) {\n connection.abort(new InvalidMultiaddrError('Duplicate multiaddr connection'));\n // return the existing connection\n return conn;\n }\n }\n if (!trackedConnection) {\n peerConnections.push(connection);\n }\n return connection;\n }\n finally {\n this.outboundPendingConnections--;\n }\n }\n async closeConnections(peerId, options = {}) {\n const connections = this.connections.get(peerId) ?? [];\n await Promise.all(connections.map(async (connection) => {\n try {\n await connection.close(options);\n }\n catch (err) {\n connection.abort(err);\n }\n }));\n }\n async acceptIncomingConnection(maConn) {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr);\n return false;\n }\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (allowConnection) {\n this.incomingPendingConnections++;\n return true;\n }\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr);\n return false;\n }\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address;\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1);\n }\n catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host);\n return false;\n }\n }\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++;\n return true;\n }\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr);\n return false;\n }\n afterUpgradeInbound() {\n this.incomingPendingConnections--;\n }\n getDialQueue() {\n const statusMap = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n };\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => multiaddr(ma))\n };\n });\n }\n async isDialable(multiaddr, options = {}) {\n return this.dialQueue.isDialable(multiaddr, options);\n }\n}\n//# sourceMappingURL=index.js.map","/**\n * Implements exponential moving average. Ported from `moving-average`.\n *\n * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * @see https://www.npmjs.com/package/moving-average\n */\nexport class MovingAverage {\n movingAverage;\n variance;\n deviation;\n forecast;\n timespan;\n previousTime;\n constructor(timespan) {\n this.timespan = timespan;\n this.movingAverage = 0;\n this.variance = 0;\n this.deviation = 0;\n this.forecast = 0;\n }\n alpha(t, pt) {\n return 1 - (Math.exp(-(t - pt) / this.timespan));\n }\n push(value, time = Date.now()) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime);\n const diff = value - this.movingAverage;\n const incr = a * diff;\n this.movingAverage = a * value + (1 - a) * this.movingAverage;\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr);\n this.deviation = Math.sqrt(this.variance);\n // calculate forecast\n this.forecast = this.movingAverage + a * diff;\n }\n else {\n this.movingAverage = value;\n }\n this.previousTime = time;\n }\n}\n//# sourceMappingURL=moving-average.js.map","import { setMaxListeners } from '@libp2p/interface';\nimport { anySignal } from 'any-signal';\nimport { MovingAverage } from './moving-average.js';\nexport const DEFAULT_TIMEOUT_MULTIPLIER = 1.2;\nexport const DEFAULT_FAILURE_MULTIPLIER = 2;\nexport const DEFAULT_MIN_TIMEOUT = 2000;\nexport class AdaptiveTimeout {\n success;\n failure;\n next;\n metric;\n timeoutMultiplier;\n failureMultiplier;\n minTimeout;\n constructor(init = {}) {\n this.success = new MovingAverage(init.interval ?? 5000);\n this.failure = new MovingAverage(init.interval ?? 5000);\n this.next = new MovingAverage(init.interval ?? 5000);\n this.failureMultiplier = init.failureMultiplier ?? DEFAULT_FAILURE_MULTIPLIER;\n this.timeoutMultiplier = init.timeoutMultiplier ?? DEFAULT_TIMEOUT_MULTIPLIER;\n this.minTimeout = init.minTimeout ?? DEFAULT_MIN_TIMEOUT;\n if (init.metricName != null) {\n this.metric = init.metrics?.registerMetricGroup(init.metricName);\n }\n }\n getTimeoutSignal(options = {}) {\n // calculate timeout for individual peers based on moving average of\n // previous successful requests\n const timeout = Math.max(Math.round(this.next.movingAverage * (options.timeoutFactor ?? this.timeoutMultiplier)), this.minTimeout);\n const sendTimeout = AbortSignal.timeout(timeout);\n const timeoutSignal = anySignal([options.signal, sendTimeout]);\n setMaxListeners(Infinity, timeoutSignal, sendTimeout);\n timeoutSignal.start = Date.now();\n timeoutSignal.timeout = timeout;\n return timeoutSignal;\n }\n cleanUp(signal) {\n const time = Date.now() - signal.start;\n if (signal.aborted) {\n this.failure.push(time);\n this.next.push(time * this.failureMultiplier);\n this.metric?.update({\n failureMovingAverage: this.failure.movingAverage,\n failureDeviation: this.failure.deviation,\n failureForecast: this.failure.forecast,\n failureVariance: this.failure.variance,\n failure: time\n });\n }\n else {\n this.success.push(time);\n this.next.push(time);\n this.metric?.update({\n successMovingAverage: this.success.movingAverage,\n successDeviation: this.success.deviation,\n successForecast: this.success.forecast,\n successVariance: this.success.variance,\n success: time\n });\n }\n }\n}\n//# sourceMappingURL=adaptive-timeout.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { serviceCapabilities, setMaxListeners } from '@libp2p/interface';\nimport { AdaptiveTimeout } from '@libp2p/utils/adaptive-timeout';\nimport { byteStream } from 'it-byte-stream';\nconst DEFAULT_PING_INTERVAL_MS = 10000;\nconst PROTOCOL_VERSION = '1.0.0';\nconst PROTOCOL_NAME = 'ping';\nconst PROTOCOL_PREFIX = 'ipfs';\nconst PING_LENGTH = 32;\nconst DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE = true;\nexport class ConnectionMonitor {\n protocol;\n components;\n log;\n heartbeatInterval;\n pingIntervalMs;\n abortController;\n timeout;\n abortConnectionOnPingFailure;\n constructor(components, init = {}) {\n this.components = components;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.log = components.logger.forComponent('libp2p:connection-monitor');\n this.pingIntervalMs = init.pingInterval ?? DEFAULT_PING_INTERVAL_MS;\n this.abortConnectionOnPingFailure = init.abortConnectionOnPingFailure ?? DEFAULT_ABORT_CONNECTION_ON_PING_FAILURE;\n this.timeout = new AdaptiveTimeout({\n ...(init.pingTimeout ?? {}),\n metrics: components.metrics,\n metricName: 'libp2p_connection_monitor_ping_time_milliseconds'\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-monitor';\n [serviceCapabilities] = [\n '@libp2p/connection-monitor'\n ];\n start() {\n this.abortController = new AbortController();\n setMaxListeners(Infinity, this.abortController.signal);\n this.heartbeatInterval = setInterval(() => {\n this.components.connectionManager.getConnections().forEach(conn => {\n Promise.resolve().then(async () => {\n let start = Date.now();\n try {\n const signal = this.timeout.getTimeoutSignal({\n signal: this.abortController?.signal\n });\n const stream = await conn.newStream(this.protocol, {\n signal,\n runOnLimitedConnection: true\n });\n const bs = byteStream(stream);\n start = Date.now();\n await Promise.all([\n bs.write(randomBytes(PING_LENGTH), {\n signal\n }),\n bs.read(PING_LENGTH, {\n signal\n })\n ]);\n conn.rtt = Date.now() - start;\n await bs.unwrap().close({\n signal\n });\n }\n catch (err) {\n if (err.name !== 'UnsupportedProtocolError') {\n throw err;\n }\n // protocol was unsupported, but that's ok as it means the remote\n // peer was still alive. We ran multistream-select which means two\n // round trips (e.g. 1x for the mss header, then another for the\n // protocol) so divide the time it took by two\n conn.rtt = (Date.now() - start) / 2;\n }\n })\n .catch(err => {\n this.log.error('error during heartbeat', err);\n if (this.abortConnectionOnPingFailure) {\n this.log.error('aborting connection due to ping failure');\n conn.abort(err);\n }\n else {\n this.log('connection ping failed, but not aborting due to abortConnectionOnPingFailure flag');\n }\n });\n });\n }, this.pingIntervalMs);\n }\n stop() {\n this.abortController?.abort();\n if (this.heartbeatInterval != null) {\n clearInterval(this.heartbeatInterval);\n }\n }\n}\n//# sourceMappingURL=connection-monitor.js.map","import { NotStartedError } from '@libp2p/interface';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport merge from 'it-merge';\nimport { NoContentRoutersError } from './errors.js';\nexport class CompoundContentRouting {\n routers;\n started;\n components;\n constructor(components, init) {\n this.routers = init.routers ?? [];\n this.started = false;\n this.components = components;\n }\n [Symbol.toStringTag] = '@libp2p/content-routing';\n isStarted() {\n return this.started;\n }\n async start() {\n this.started = true;\n }\n async stop() {\n this.started = false;\n }\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async *findProviders(key, options = {}) {\n if (this.routers.length === 0) {\n throw new NoContentRoutersError('No content routers available');\n }\n const self = this;\n const seen = new PeerSet();\n for await (const peer of merge(...self.routers.map(router => router.findProviders(key, options)))) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide(key, options = {}) {\n if (this.routers.length === 0) {\n throw new NoContentRoutersError('No content routers available');\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options);\n }));\n }\n /**\n * Store the given key/value pair in the available content routings\n */\n async put(key, value, options) {\n if (!this.isStarted()) {\n throw new NotStartedError();\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options);\n }));\n }\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get(key, options) {\n if (!this.isStarted()) {\n throw new NotStartedError();\n }\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options);\n }));\n }\n}\n//# sourceMappingURL=content-routing.js.map","import { alloc as uint8ArrayAlloc } from 'uint8arrays/alloc';\nimport { equals as uint8ArrayEquals } from 'uint8arrays/equals';\nexport const MAX_FINGERPRINT_SIZE = 64;\nexport class Fingerprint {\n fp;\n h;\n seed;\n constructor(buf, hash, seed, fingerprintSize = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size');\n }\n const fnv = hash.hashV(buf, seed);\n const fp = uint8ArrayAlloc(fingerprintSize);\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i];\n }\n if (fp.length === 0) {\n fp[0] = 7;\n }\n this.fp = fp;\n this.h = hash;\n this.seed = seed;\n }\n hash() {\n return this.h.hash(this.fp, this.seed);\n }\n equals(other) {\n if (!(other?.fp instanceof Uint8Array)) {\n return false;\n }\n return uint8ArrayEquals(this.fp, other.fp);\n }\n}\n//# sourceMappingURL=fingerprint.js.map","export function getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n}\n//# sourceMappingURL=utils.js.map","import { Fingerprint } from './fingerprint.js';\nimport { getRandomInt } from './utils.js';\nexport class Bucket {\n contents;\n constructor(size) {\n this.contents = new Array(size).fill(null);\n }\n has(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n return this.contents.some((fp) => {\n return fingerprint.equals(fp);\n });\n }\n add(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint;\n return true;\n }\n }\n return true;\n }\n swap(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const i = getRandomInt(0, this.contents.length - 1);\n const current = this.contents[i];\n this.contents[i] = fingerprint;\n return current;\n }\n remove(fingerprint) {\n if (!(fingerprint instanceof Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp);\n });\n if (found > -1) {\n this.contents[found] = null;\n return true;\n }\n else {\n return false;\n }\n }\n}\n//# sourceMappingURL=bucket.js.map","// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nexport default function fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n","import fnv1aHash from '@sindresorhus/fnv1a';\nimport mur from 'murmurhash3js-revisited';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nexport const murmur3 = {\n hash: (input, seed) => {\n return mur.x86.hash32(input, seed);\n },\n hashV: (input, seed) => {\n return numberToBuffer(murmur3.hash(input, seed));\n }\n};\nexport const fnv1a = {\n hash: (input) => {\n return Number(fnv1aHash(input, {\n size: 32\n }));\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed));\n }\n};\nexport function numberToBuffer(num) {\n let hex = num.toString(16);\n if (hex.length % 2 === 1) {\n hex = `0${hex}`;\n }\n return uint8ArrayFromString(hex, 'base16');\n}\n//# sourceMappingURL=hashes.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { Bucket } from './bucket.js';\nimport { Fingerprint, MAX_FINGERPRINT_SIZE } from './fingerprint.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nconst maxCuckooCount = 500;\nexport class CuckooFilter {\n bucketSize;\n filterSize;\n fingerprintSize;\n buckets;\n count;\n hash;\n seed;\n constructor(init) {\n this.filterSize = init.filterSize;\n this.bucketSize = init.bucketSize ?? 4;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.count = 0;\n this.buckets = [];\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n if (this.buckets[j] == null) {\n this.buckets[j] = new Bucket(this.bucketSize);\n }\n if (this.buckets[k] == null) {\n this.buckets[k] = new Bucket(this.bucketSize);\n }\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++;\n return true;\n }\n const rand = [j, k];\n let i = rand[getRandomInt(0, rand.length - 1)];\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint);\n if (swapped == null) {\n continue;\n }\n i = (i ^ swapped.hash()) % this.filterSize;\n if (this.buckets[i] == null) {\n this.buckets[i] = new Bucket(this.bucketSize);\n }\n if (this.buckets[i].add(swapped)) {\n this.count++;\n return true;\n }\n else {\n continue;\n }\n }\n return false;\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.has(fingerprint) ?? false;\n if (inJ) {\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n return this.buckets[k]?.has(fingerprint) ?? false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n const fingerprint = new Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false;\n if (inJ) {\n this.count--;\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n const inK = this.buckets[k]?.remove(fingerprint) ?? false;\n if (inK) {\n this.count--;\n }\n return inK;\n }\n get reliable() {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90;\n }\n}\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n};\nfunction calculateBucketSize(errorRate = 0.001) {\n if (errorRate > 0.002) {\n return 2;\n }\n if (errorRate > 0.00001) {\n return 4;\n }\n return 8;\n}\nexport function optimize(maxItems, errorRate = 0.001) {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate);\n const load = MAX_LOAD[bucketSize];\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load);\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), MAX_FINGERPRINT_SIZE);\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n };\n}\nexport function createCuckooFilter(maxItems, errorRate = 0.005) {\n const opts = optimize(maxItems, errorRate);\n return new CuckooFilter(opts);\n}\n//# sourceMappingURL=cuckoo-filter.js.map","import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { CuckooFilter, optimize } from './cuckoo-filter.js';\nimport { fnv1a } from './hashes.js';\nimport { getRandomInt } from './utils.js';\nexport class ScalableCuckooFilter {\n filterSize;\n bucketSize;\n fingerprintSize;\n scale;\n filterSeries;\n hash;\n seed;\n constructor(init) {\n this.bucketSize = init.bucketSize ?? 4;\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.scale = init.scale ?? 2;\n this.hash = init.hash ?? fnv1a;\n this.seed = init.seed ?? getRandomInt(0, Math.pow(2, 10));\n this.filterSeries = [\n new CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ];\n }\n add(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n if (this.has(item)) {\n return true;\n }\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable;\n });\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length);\n current = new CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n });\n this.filterSeries.push(current);\n }\n return current.add(item);\n }\n has(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true;\n }\n }\n return false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = uint8ArrayFromString(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true;\n }\n }\n return false;\n }\n get count() {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count;\n }, 0);\n }\n}\nexport function createScalableCuckooFilter(maxItems, errorRate = 0.001, options) {\n return new ScalableCuckooFilter({\n ...optimize(maxItems, errorRate),\n ...(options ?? {})\n });\n}\n//# sourceMappingURL=scalable-cuckoo-filter.js.map","/**\n * @packageDocumentation\n *\n * Takes an (async) iterable that emits promise-returning functions, invokes them in parallel up to the concurrency limit and emits the results as they become available, optionally in the same order as the input\n *\n * @example\n *\n * ```javascript\n * import parallel from 'it-parallel'\n * import all from 'it-all'\n * import delay from 'delay'\n *\n * // This can also be an iterator, async iterator, generator, etc\n * const input = [\n * async () => {\n * console.info('start 1')\n * await delay(500)\n *\n * console.info('end 1')\n * return 1\n * },\n * async () => {\n * console.info('start 2')\n * await delay(200)\n *\n * console.info('end 2')\n * return 2\n * },\n * async () => {\n * console.info('start 3')\n * await delay(100)\n *\n * console.info('end 3')\n * return 3\n * }\n * ]\n *\n * const result = await all(parallel(input, {\n * concurrency: 2\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [2, 3, 1]\n * ```\n *\n * If order is important, pass `ordered: true` as an option:\n *\n * ```javascript\n * const result = await all(parallel(input, {\n * concurrency: 2,\n * ordered: true\n * }))\n *\n * // output:\n * // start 1\n * // start 2\n * // end 2\n * // start 3\n * // end 3\n * // end 1\n *\n * console.info(result) // [1, 2, 3]\n * ```\n */\nimport defer from 'p-defer';\nconst CustomEvent = globalThis.CustomEvent ?? Event;\n/**\n * Takes an (async) iterator that emits promise-returning functions,\n * invokes them in parallel and emits the results as they become available but\n * in the same order as the input\n */\nexport default async function* parallel(source, options = {}) {\n let concurrency = options.concurrency ?? Infinity;\n if (concurrency < 1) {\n concurrency = Infinity;\n }\n const ordered = options.ordered == null ? false : options.ordered;\n const emitter = new EventTarget();\n const ops = [];\n let slotAvailable = defer();\n let resultAvailable = defer();\n let sourceFinished = false;\n let sourceErr;\n let opErred = false;\n emitter.addEventListener('task-complete', () => {\n resultAvailable.resolve();\n });\n void Promise.resolve().then(async () => {\n try {\n for await (const task of source) {\n if (ops.length === concurrency) {\n slotAvailable = defer();\n await slotAvailable.promise;\n }\n if (opErred) {\n break;\n }\n const op = {\n done: false\n };\n ops.push(op);\n task()\n .then(result => {\n op.done = true;\n op.ok = true;\n op.value = result;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }, err => {\n op.done = true;\n op.err = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n });\n }\n sourceFinished = true;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n catch (err) {\n sourceErr = err;\n emitter.dispatchEvent(new CustomEvent('task-complete'));\n }\n });\n function valuesAvailable() {\n if (ordered) {\n return ops[0]?.done;\n }\n return Boolean(ops.find(op => op.done));\n }\n function* yieldOrderedValues() {\n while ((ops.length > 0) && ops[0].done) {\n const op = ops[0];\n ops.shift();\n if (op.ok) {\n yield op.value;\n }\n else {\n // allow the source to exit\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n function* yieldUnOrderedValues() {\n // more values can become available while we wait for `yield`\n // to return control to this function\n while (valuesAvailable()) {\n for (let i = 0; i < ops.length; i++) {\n if (ops[i].done) {\n const op = ops[i];\n ops.splice(i, 1);\n i--;\n if (op.ok) {\n yield op.value;\n }\n else {\n opErred = true;\n slotAvailable.resolve();\n throw op.err;\n }\n slotAvailable.resolve();\n }\n }\n }\n }\n while (true) {\n if (!valuesAvailable()) {\n resultAvailable = defer();\n await resultAvailable.promise;\n }\n if (sourceErr != null) {\n // the source threw an error, propagate it\n throw sourceErr;\n }\n if (ordered) {\n yield* yieldOrderedValues();\n }\n else {\n yield* yieldUnOrderedValues();\n }\n if (sourceFinished && ops.length === 0) {\n // not waiting for any results and no more tasks so we are done\n break;\n }\n }\n}\n//# sourceMappingURL=index.js.map","import { NotFoundError } from '@libp2p/interface';\nimport { createScalableCuckooFilter } from '@libp2p/utils/filters';\nimport merge from 'it-merge';\nimport parallel from 'it-parallel';\nimport { NoPeerRoutersError, QueriedForSelfError } from './errors.js';\nexport class DefaultPeerRouting {\n log;\n peerId;\n peerStore;\n routers;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing');\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.routers = init.routers ?? [];\n }\n [Symbol.toStringTag] = '@libp2p/peer-routing';\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer(id, options) {\n if (this.routers.length === 0) {\n throw new NoPeerRoutersError('No peer routers available');\n }\n if (id.toString() === this.peerId.toString()) {\n throw new QueriedForSelfError('Should not try to find self');\n }\n const self = this;\n const source = merge(...this.routers.map(router => (async function* () {\n try {\n yield await router.findPeer(id, options);\n }\n catch (err) {\n self.log.error(err);\n }\n })()));\n for await (const peer of source) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n return peer;\n }\n throw new NotFoundError();\n }\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async *getClosestPeers(key, options = {}) {\n if (this.routers.length === 0) {\n throw new NoPeerRoutersError('No peer routers available');\n }\n const self = this;\n const seen = createScalableCuckooFilter(1024);\n for await (const peer of parallel(async function* () {\n const source = merge(...self.routers.map(router => router.getClosestPeers(key, options)));\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n });\n }\n catch (err) {\n self.log.error('could not find peer multiaddrs', err);\n return;\n }\n }\n return peer;\n };\n }\n }())) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id.toMultihash().bytes)) {\n continue;\n }\n seen.add(peer.id.toMultihash().bytes);\n yield peer;\n }\n }\n}\n//# sourceMappingURL=peer-routing.js.map","import { randomBytes } from '@libp2p/crypto';\nimport { TypedEventEmitter, setMaxListeners } from '@libp2p/interface';\nimport { anySignal } from 'any-signal';\nimport pDefer, {} from 'p-defer';\nimport { raceEvent } from 'race-event';\nimport { raceSignal } from 'race-signal';\nexport class RandomWalk extends TypedEventEmitter {\n peerRouting;\n log;\n walking;\n walkers;\n shutdownController;\n walkController;\n needNext;\n constructor(components) {\n super();\n this.log = components.logger.forComponent('libp2p:random-walk');\n this.peerRouting = components.peerRouting;\n this.walkers = 0;\n this.walking = false;\n // stops any in-progress walks when the node is shut down\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n [Symbol.toStringTag] = '@libp2p/random-walk';\n start() {\n this.shutdownController = new AbortController();\n setMaxListeners(Infinity, this.shutdownController.signal);\n }\n stop() {\n this.shutdownController.abort();\n }\n async *walk(options) {\n if (!this.walking) {\n // start the query that causes walk:peer events to be emitted\n this.startWalk();\n }\n this.walkers++;\n const signal = anySignal([this.shutdownController.signal, options?.signal]);\n setMaxListeners(Infinity, signal);\n try {\n while (true) {\n // if another consumer has paused the query, start it again\n this.needNext?.resolve();\n this.needNext = pDefer();\n // wait for a walk:peer or walk:error event\n const event = await raceEvent(this, 'walk:peer', signal, {\n errorEvent: 'walk:error'\n });\n yield event.detail;\n }\n }\n finally {\n signal.clear();\n this.walkers--;\n // stop the walk if no more consumers are interested\n if (this.walkers === 0) {\n this.walkController?.abort();\n this.walkController = undefined;\n }\n }\n }\n startWalk() {\n this.walking = true;\n // the signal for this controller will be aborted if no more random peers\n // are required\n this.walkController = new AbortController();\n setMaxListeners(Infinity, this.walkController.signal);\n const signal = anySignal([this.walkController.signal, this.shutdownController.signal]);\n setMaxListeners(Infinity, signal);\n const start = Date.now();\n let found = 0;\n Promise.resolve().then(async () => {\n this.log('start walk');\n // find peers until no more consumers are interested\n while (this.walkers > 0) {\n try {\n const data = randomBytes(32);\n let s = Date.now();\n for await (const peer of this.peerRouting.getClosestPeers(data, { signal })) {\n if (signal.aborted) {\n this.log('aborting walk');\n }\n signal.throwIfAborted();\n this.log('found peer %p after %dms for %d walkers', peer.id, Date.now() - s, this.walkers);\n found++;\n this.safeDispatchEvent('walk:peer', {\n detail: peer\n });\n // if we only have one consumer, pause the query until they request\n // another random peer or they signal they are no longer interested\n if (this.walkers === 1 && this.needNext != null) {\n this.log('wait for need next');\n await raceSignal(this.needNext.promise, signal);\n }\n s = Date.now();\n }\n this.log('walk iteration for %b and %d walkers finished, found %d peers', data, this.walkers, found);\n }\n catch (err) {\n this.log.error('randomwalk errored', err);\n this.safeDispatchEvent('walk:error', {\n detail: err\n });\n }\n }\n this.log('no walkers left, ended walk');\n })\n .catch(err => {\n this.log.error('randomwalk errored', err);\n })\n .finally(() => {\n this.log('finished walk, found %d peers after %dms', found, Date.now() - start);\n this.walking = false;\n });\n }\n}\n//# sourceMappingURL=random-walk.js.map","import { InvalidParametersError } from '@libp2p/interface';\nimport merge from 'merge-options';\nimport * as errorsJs from './errors.js';\nexport const DEFAULT_MAX_INBOUND_STREAMS = 32;\nexport const DEFAULT_MAX_OUTBOUND_STREAMS = 64;\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nexport class DefaultRegistrar {\n log;\n topologies;\n handlers;\n components;\n constructor(components) {\n this.log = components.logger.forComponent('libp2p:registrar');\n this.topologies = new Map();\n this.handlers = new Map();\n this.components = components;\n this._onDisconnect = this._onDisconnect.bind(this);\n this._onPeerUpdate = this._onPeerUpdate.bind(this);\n this._onPeerIdentify = this._onPeerIdentify.bind(this);\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect);\n this.components.events.addEventListener('peer:update', this._onPeerUpdate);\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify);\n }\n [Symbol.toStringTag] = '@libp2p/registrar';\n getProtocols() {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort();\n }\n getHandler(protocol) {\n const handler = this.handlers.get(protocol);\n if (handler == null) {\n throw new errorsJs.UnhandledProtocolError(`No handler registered for protocol ${protocol}`);\n }\n return handler;\n }\n getTopologies(protocol) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n return [];\n }\n return [\n ...topologies.values()\n ];\n }\n /**\n * Registers the `handler` for each protocol\n */\n async handle(protocol, handler, opts) {\n if (this.handlers.has(protocol)) {\n throw new errorsJs.DuplicateProtocolHandlerError(`Handler already registered for protocol ${protocol}`);\n }\n const options = merge.bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts);\n this.handlers.set(protocol, {\n handler,\n options\n });\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n });\n }\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle(protocols) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols];\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol);\n });\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n });\n }\n /**\n * Register handlers for a set of multicodecs given\n */\n async register(protocol, topology) {\n if (topology == null) {\n throw new InvalidParametersError('invalid topology');\n }\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`;\n let topologies = this.topologies.get(protocol);\n if (topologies == null) {\n topologies = new Map();\n this.topologies.set(protocol, topologies);\n }\n topologies.set(id, topology);\n return id;\n }\n /**\n * Unregister topology\n */\n unregister(id) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id);\n if (topologies.size === 0) {\n this.topologies.delete(protocol);\n }\n }\n }\n }\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect(evt) {\n const remotePeer = evt.detail;\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(remotePeer) === false) {\n continue;\n }\n topology.filter?.remove(remotePeer);\n topology.onDisconnect?.(remotePeer);\n }\n }\n })\n .catch(err => {\n if (err.name === 'NotFoundError') {\n // peer has not completed identify so they are not in the peer store\n return;\n }\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err);\n });\n }\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate(evt) {\n const { peer, previous } = evt.detail;\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol));\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(peer.id) === false) {\n continue;\n }\n topology.filter?.remove(peer.id);\n topology.onDisconnect?.(peer.id);\n }\n }\n }\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify(evt) {\n const protocols = evt.detail.protocols;\n const connection = evt.detail.connection;\n const peerId = evt.detail.peerId;\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (connection.limits != null && topology.notifyOnLimitedConnection !== true) {\n continue;\n }\n if (topology.filter?.has(peerId) === true) {\n continue;\n }\n topology.filter?.add(peerId);\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n}\n//# sourceMappingURL=registrar.js.map","class TrackedMap extends Map {\n metric;\n constructor(init) {\n super();\n const { name, metrics } = init;\n this.metric = metrics.registerMetric(name);\n this.updateComponentMetric();\n }\n set(key, value) {\n super.set(key, value);\n this.updateComponentMetric();\n return this;\n }\n delete(key) {\n const deleted = super.delete(key);\n this.updateComponentMetric();\n return deleted;\n }\n clear() {\n super.clear();\n this.updateComponentMetric();\n }\n updateComponentMetric() {\n this.metric.update(this.size);\n }\n}\nexport function trackedMap(config) {\n const { name, metrics } = config;\n let map;\n if (metrics != null) {\n map = new TrackedMap({ name, metrics });\n }\n else {\n map = new Map();\n }\n return map;\n}\n//# sourceMappingURL=tracked-map.js.map","import { FaultTolerance, InvalidParametersError, NotStartedError } from '@libp2p/interface';\nimport { trackedMap } from '@libp2p/utils/tracked-map';\nimport { CustomProgressEvent } from 'progress-events';\nimport { NoValidAddressesError, TransportUnavailableError } from './errors.js';\nexport class DefaultTransportManager {\n log;\n components;\n transports;\n listeners;\n faultTolerance;\n started;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:transports');\n this.components = components;\n this.started = false;\n this.transports = new Map();\n this.listeners = trackedMap({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n });\n this.faultTolerance = init.faultTolerance ?? FaultTolerance.FATAL_ALL;\n }\n [Symbol.toStringTag] = '@libp2p/transport-manager';\n /**\n * Adds a `Transport` to the manager\n */\n add(transport) {\n const tag = transport[Symbol.toStringTag];\n if (tag == null) {\n throw new InvalidParametersError('Transport must have a valid tag');\n }\n if (this.transports.has(tag)) {\n throw new InvalidParametersError(`There is already a transport with the tag ${tag}`);\n }\n this.log('adding transport %s', tag);\n this.transports.set(tag, transport);\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, []);\n }\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs();\n await this.listen(addrs);\n }\n /**\n * Stops all listeners\n */\n async stop() {\n const tasks = [];\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n }\n await Promise.all(tasks);\n this.log('all listeners closed');\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, []);\n }\n this.started = false;\n }\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial(ma, options) {\n const transport = this.dialTransportForMultiaddr(ma);\n if (transport == null) {\n throw new TransportUnavailableError(`No transport available for address ${String(ma)}`);\n }\n options?.onProgress?.(new CustomProgressEvent('transport-manager:selected-transport', transport[Symbol.toStringTag]));\n // @ts-expect-error the transport has a typed onProgress option but we\n // can't predict what transport implementation we selected so all we can\n // do is pass the onProgress handler in and hope for the best\n return transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n });\n }\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs() {\n let addrs = [];\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()];\n }\n }\n return addrs;\n }\n /**\n * Returns all the transports instances\n */\n getTransports() {\n return Array.of(...this.transports.values());\n }\n /**\n * Returns all the listener instances\n */\n getListeners() {\n return Array.of(...this.listeners.values()).flat();\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n dialTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.dialFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n listenTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.listenFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen(addrs) {\n if (!this.isStarted()) {\n throw new NotStartedError('Not started');\n }\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only');\n return;\n }\n const couldNotListen = [];\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.listenFilter(addrs);\n const tasks = [];\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr);\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n });\n let listeners = this.listeners.get(key) ?? [];\n if (listeners == null) {\n listeners = [];\n this.listeners.set(key, listeners);\n }\n listeners.push(listener);\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n });\n });\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener);\n // remove the listener\n listeners.splice(index, 1);\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n });\n });\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr));\n }\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key);\n continue;\n }\n const results = await Promise.allSettled(tasks);\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled');\n if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) {\n throw new NoValidAddressesError(`Transport (${key}) could not listen on any available address`);\n }\n }\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`;\n if (this.faultTolerance === FaultTolerance.FATAL_ALL) {\n throw new NoValidAddressesError(message);\n }\n this.log(`libp2p in dial mode only: ${message}`);\n }\n }\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove(key) {\n const listeners = this.listeners.get(key) ?? [];\n this.log.trace('removing transport %s', key);\n // Close any running listeners\n const tasks = [];\n this.log.trace('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n await Promise.all(tasks);\n this.transports.delete(key);\n this.listeners.delete(key);\n }\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll() {\n const tasks = [];\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key));\n }\n await Promise.all(tasks);\n }\n}\n//# sourceMappingURL=transport-manager.js.map","export const PROTOCOL_ID = '/multistream/1.0.0';\n// Conforming to go-libp2p\n// See https://github.com/multiformats/go-multistream/blob/master/multistream.go#L297\nexport const MAX_PROTOCOL_LENGTH = 1024;\n//# sourceMappingURL=constants.js.map","import { InvalidMessageError } from '@libp2p/interface';\nimport {} from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { toString as uint8ArrayToString } from 'uint8arrays/to-string';\nconst NewLine = uint8ArrayFromString('\\n');\n/**\n * `write` encodes and writes a single buffer\n */\nexport async function write(writer, buffer, options) {\n await writer.write(buffer, options);\n}\n/**\n * `writeAll` behaves like `write`, except it encodes an array of items as a single write\n */\nexport async function writeAll(writer, buffers, options) {\n await writer.writeV(buffers, options);\n}\n/**\n * Read a length-prefixed buffer from the passed stream, stripping the final newline character\n */\nexport async function read(reader, options) {\n const buf = await reader.read(options);\n if (buf.byteLength === 0 || buf.get(buf.byteLength - 1) !== NewLine[0]) {\n options.log.error('Invalid mss message - missing newline', buf);\n throw new InvalidMessageError('Missing newline');\n }\n return buf.sublist(0, -1); // Remove newline\n}\n/**\n * Read a length-prefixed string from the passed stream, stripping the final newline character\n */\nexport async function readString(reader, options) {\n const buf = await read(reader, options);\n return uint8ArrayToString(buf.subarray());\n}\n//# sourceMappingURL=multistream.js.map","import { encode } from 'it-length-prefixed';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH, PROTOCOL_ID } from './constants.js';\nimport * as multistream from './multistream.js';\n/**\n * Handle multistream protocol selections for the given list of protocols.\n *\n * Note that after a protocol is handled `listener` can no longer be used.\n *\n * @param stream - A duplex iterable stream to listen on\n * @param protocols - A list of protocols (or single protocol) that this listener is able to speak.\n * @param options - an options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex({\n * async onStream (muxedStream) {\n * // mss.handle(handledProtocols)\n * // Returns selected stream and protocol\n * const { stream, protocol } = await mss.handle(muxedStream, [\n * '/ipfs-dht/1.0.0',\n * '/ipfs-bitswap/1.0.0'\n * ])\n *\n * // Typically here we'd call the handler function that was registered in\n * // libp2p for the given protocol:\n * // e.g. handlers[protocol].handler(stream)\n * //\n * // If protocol was /ipfs-dht/1.0.0 it might do something like this:\n * // try {\n * // await pipe(\n * // dhtStream,\n * // source => (async function * () {\n * // for await (const chunk of source)\n * // // Incoming DHT data -> process and yield to respond\n * // })(),\n * // dhtStream\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * }\n * })\n * ```\n */\nexport async function handle(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n options.log.trace('handle: available protocols %s', protocols);\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH,\n maxLengthLength: 2 // 2 bytes is enough to length-prefix MAX_PROTOCOL_LENGTH\n });\n while (true) {\n options.log.trace('handle: reading incoming string');\n const protocol = await multistream.readString(lp, options);\n options.log.trace('handle: read \"%s\"', protocol);\n if (protocol === PROTOCOL_ID) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${PROTOCOL_ID}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', PROTOCOL_ID, protocol);\n continue;\n }\n if (protocols.includes(protocol)) {\n options.log.trace('handle: respond with \"%s\" for \"%s\"', protocol, protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('handle: responded with \"%s\" for \"%s\"', protocol, protocol);\n return { stream: lp.unwrap(), protocol };\n }\n if (protocol === 'ls') {\n // \\n\\n\\n\n const protos = new Uint8ArrayList(...protocols.map(p => encode.single(uint8ArrayFromString(`${p}\\n`))), uint8ArrayFromString('\\n'));\n options.log.trace('handle: respond with \"%s\" for %s', protocols, protocol);\n await multistream.write(lp, protos, options);\n options.log.trace('handle: responded with \"%s\" for %s', protocols, protocol);\n continue;\n }\n options.log.trace('handle: respond with \"na\" for \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString('na\\n'), options);\n options.log('handle: responded with \"na\" for \"%s\"', protocol);\n }\n}\n//# sourceMappingURL=handle.js.map","import { UnsupportedProtocolError } from '@libp2p/interface';\nimport { lpStream } from 'it-length-prefixed-stream';\nimport pDefer from 'p-defer';\nimport { raceSignal } from 'race-signal';\nimport * as varint from 'uint8-varint';\nimport { Uint8ArrayList } from 'uint8arraylist';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { MAX_PROTOCOL_LENGTH } from './constants.js';\nimport * as multistream from './multistream.js';\nimport { PROTOCOL_ID } from './index.js';\n/**\n * Negotiate a protocol to use from a list of protocols.\n *\n * @param stream - A duplex iterable stream to dial on\n * @param protocols - A list of protocols (or single protocol) to negotiate with. Protocols are attempted in order until a match is made.\n * @param options - An options object containing an AbortSignal and an optional boolean `writeBytes` - if this is true, `Uint8Array`s will be written into `duplex`, otherwise `Uint8ArrayList`s will\n * @returns A stream for the selected protocol and the protocol that was selected from the list of protocols provided to `select`.\n * @example\n *\n * ```TypeScript\n * import { pipe } from 'it-pipe'\n * import * as mss from '@libp2p/multistream-select'\n * import { Mplex } from '@libp2p/mplex'\n *\n * const muxer = new Mplex()\n * const muxedStream = muxer.newStream()\n *\n * // mss.select(protocol(s))\n * // Select from one of the passed protocols (in priority order)\n * // Returns selected stream and protocol\n * const { stream: dhtStream, protocol } = await mss.select(muxedStream, [\n * // This might just be different versions of DHT, but could be different impls\n * '/ipfs-dht/2.0.0', // Most of the time this will probably just be one item.\n * '/ipfs-dht/1.0.0'\n * ])\n *\n * // Typically this stream will be passed back to the caller of libp2p.dialProtocol\n * //\n * // ...it might then do something like this:\n * // try {\n * // await pipe(\n * // [uint8ArrayFromString('Some DHT data')]\n * // dhtStream,\n * // async source => {\n * // for await (const chunk of source)\n * // // DHT response data\n * // }\n * // )\n * // } catch (err) {\n * // // Error in stream\n * // }\n * ```\n */\nexport async function select(stream, protocols, options) {\n protocols = Array.isArray(protocols) ? [...protocols] : [protocols];\n if (protocols.length === 1 && options.negotiateFully === false) {\n return optimisticSelect(stream, protocols[0], options);\n }\n const lp = lpStream(stream, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n const protocol = protocols.shift();\n if (protocol == null) {\n throw new Error('At least one protocol must be specified');\n }\n options.log.trace('select: write [\"%s\", \"%s\"]', PROTOCOL_ID, protocol);\n const p1 = uint8ArrayFromString(`${PROTOCOL_ID}\\n`);\n const p2 = uint8ArrayFromString(`${protocol}\\n`);\n await multistream.writeAll(lp, [p1, p2], options);\n options.log.trace('select: reading multistream-select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n // Read the protocol response if we got the protocolId in return\n if (response === PROTOCOL_ID) {\n options.log.trace('select: reading protocol response');\n response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\"', response);\n }\n // We're done\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n // We haven't gotten a valid ack, try the other protocols\n for (const protocol of protocols) {\n options.log.trace('select: write \"%s\"', protocol);\n await multistream.write(lp, uint8ArrayFromString(`${protocol}\\n`), options);\n options.log.trace('select: reading protocol response');\n const response = await multistream.readString(lp, options);\n options.log.trace('select: read \"%s\" for \"%s\"', response, protocol);\n if (response === protocol) {\n return { stream: lp.unwrap(), protocol };\n }\n }\n throw new UnsupportedProtocolError('protocol selection failed');\n}\n/**\n * Optimistically negotiates a protocol.\n *\n * It *does not* block writes waiting for the other end to respond. Instead, it\n * simply assumes the negotiation went successfully and starts writing data.\n *\n * Use when it is known that the receiver supports the desired protocol.\n */\nfunction optimisticSelect(stream, protocol, options) {\n const originalSink = stream.sink.bind(stream);\n const originalSource = stream.source;\n let negotiated = false;\n let negotiating = false;\n const doneNegotiating = pDefer();\n let sentProtocol = false;\n let sendingProtocol = false;\n const doneSendingProtocol = pDefer();\n let readProtocol = false;\n let readingProtocol = false;\n const doneReadingProtocol = pDefer();\n const lp = lpStream({\n sink: originalSink,\n source: originalSource\n }, {\n ...options,\n maxDataLength: MAX_PROTOCOL_LENGTH\n });\n stream.sink = async (source) => {\n const { sink } = lp.unwrap();\n await sink(async function* () {\n let sentData = false;\n for await (const buf of source) {\n // started reading before the source yielded, wait for protocol send\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n }\n // writing before reading, send the protocol and the first chunk of data\n if (!sentProtocol) {\n sendingProtocol = true;\n options.log.trace('optimistic: write [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n const protocolString = `${protocol}\\n`;\n // send protocols in first chunk of data written to transport\n yield new Uint8ArrayList(Uint8Array.from([19]), // length of PROTOCOL_ID plus newline\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`), varint.encode(protocolString.length), uint8ArrayFromString(protocolString), buf).subarray();\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data(%d)] in sink', PROTOCOL_ID, protocol, buf.byteLength);\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n // read the negotiation response but don't block more sending\n negotiate()\n .catch(err => {\n options.log.error('could not finish optimistic protocol negotiation of %s', protocol, err);\n });\n }\n else {\n yield buf;\n }\n sentData = true;\n }\n // special case - the source passed to the sink has ended but we didn't\n // negotiated the protocol yet so do it now\n if (!sentData) {\n await negotiate();\n }\n }());\n };\n async function negotiate() {\n if (negotiating) {\n options.log.trace('optimistic: already negotiating %s stream', protocol);\n await doneNegotiating.promise;\n return;\n }\n negotiating = true;\n try {\n // we haven't sent the protocol yet, send it now\n if (!sentProtocol) {\n options.log.trace('optimistic: doing send protocol for %s stream', protocol);\n await doSendProtocol();\n }\n // if we haven't read the protocol response yet, do it now\n if (!readProtocol) {\n options.log.trace('optimistic: doing read protocol for %s stream', protocol);\n await doReadProtocol();\n }\n }\n finally {\n negotiating = false;\n negotiated = true;\n doneNegotiating.resolve();\n }\n }\n async function doSendProtocol() {\n if (sendingProtocol) {\n await doneSendingProtocol.promise;\n return;\n }\n sendingProtocol = true;\n try {\n options.log.trace('optimistic: write [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n await lp.writeV([\n uint8ArrayFromString(`${PROTOCOL_ID}\\n`),\n uint8ArrayFromString(`${protocol}\\n`)\n ]);\n options.log.trace('optimistic: wrote [\"%s\", \"%s\", data] in source', PROTOCOL_ID, protocol);\n }\n finally {\n sentProtocol = true;\n sendingProtocol = false;\n doneSendingProtocol.resolve();\n }\n }\n async function doReadProtocol() {\n if (readingProtocol) {\n await doneReadingProtocol.promise;\n return;\n }\n readingProtocol = true;\n try {\n options.log.trace('optimistic: reading multistream select header');\n let response = await multistream.readString(lp, options);\n options.log.trace('optimistic: read multistream select header \"%s\"', response);\n if (response === PROTOCOL_ID) {\n response = await multistream.readString(lp, options);\n }\n options.log.trace('optimistic: read protocol \"%s\", expecting \"%s\"', response, protocol);\n if (response !== protocol) {\n throw new UnsupportedProtocolError('protocol selection failed');\n }\n }\n finally {\n readProtocol = true;\n readingProtocol = false;\n doneReadingProtocol.resolve();\n }\n }\n stream.source = (async function* () {\n // make sure we've done protocol negotiation before we read stream data\n await negotiate();\n options.log.trace('optimistic: reading data from \"%s\" stream', protocol);\n yield* lp.unwrap().source;\n })();\n if (stream.closeRead != null) {\n const originalCloseRead = stream.closeRead.bind(stream);\n stream.closeRead = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the readable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close read', err);\n });\n }\n // protocol has been negotiated, ok to close the readable end\n await originalCloseRead(opts);\n };\n }\n if (stream.closeWrite != null) {\n const originalCloseWrite = stream.closeWrite.bind(stream);\n stream.closeWrite = async (opts) => {\n // we need to read & write to negotiate the protocol so ensure we've done\n // this before closing the writable end of the stream\n if (!negotiated) {\n await negotiate().catch(err => {\n options.log.error('could not negotiate protocol before close write', err);\n });\n }\n // protocol has been negotiated, ok to close the writable end\n await originalCloseWrite(opts);\n };\n }\n if (stream.close != null) {\n const originalClose = stream.close.bind(stream);\n stream.close = async (opts) => {\n // if we are in the process of negotiation, let it finish before closing\n // because we may have unsent early data\n const tasks = [];\n if (sendingProtocol) {\n tasks.push(doneSendingProtocol.promise);\n }\n if (readingProtocol) {\n tasks.push(doneReadingProtocol.promise);\n }\n if (tasks.length > 0) {\n // let the in-flight protocol negotiation finish gracefully\n await raceSignal(Promise.all(tasks), opts?.signal);\n }\n else {\n // no protocol negotiation attempt has occurred so don't start one\n negotiated = true;\n negotiating = false;\n doneNegotiating.resolve();\n }\n // protocol has been negotiated, ok to close the writable end\n await originalClose(opts);\n };\n }\n return {\n stream,\n protocol\n };\n}\n//# sourceMappingURL=select.js.map","export const connectionSymbol = Symbol.for('@libp2p/connection');\nexport function isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map","import { connectionSymbol, setMaxListeners, LimitedConnectionError, ConnectionClosedError, ConnectionClosingError } from '@libp2p/interface';\nconst CLOSE_TIMEOUT = 500;\n/**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\nexport class ConnectionImpl {\n /**\n * Connection identifier.\n */\n id;\n /**\n * Observed multiaddr of the remote peer\n */\n remoteAddr;\n /**\n * Remote peer id\n */\n remotePeer;\n direction;\n timeline;\n multiplexer;\n encryption;\n status;\n limits;\n log;\n /**\n * User provided tags\n *\n */\n tags;\n /**\n * Reference to the new stream function of the multiplexer\n */\n _newStream;\n /**\n * Reference to the close function of the raw connection\n */\n _close;\n _abort;\n /**\n * Reference to the getStreams function of the muxer\n */\n _getStreams;\n /**\n * An implementation of the js-libp2p connection.\n * Any libp2p transport should use an upgrader to return this connection.\n */\n constructor(init) {\n const { remoteAddr, remotePeer, newStream, close, abort, getStreams } = init;\n this.id = `${(parseInt(String(Math.random() * 1e9))).toString(36)}${Date.now()}`;\n this.remoteAddr = remoteAddr;\n this.remotePeer = remotePeer;\n this.direction = init.direction;\n this.status = 'open';\n this.timeline = init.timeline;\n this.multiplexer = init.multiplexer;\n this.encryption = init.encryption;\n this.limits = init.limits;\n this.log = init.logger.forComponent(`libp2p:connection:${this.direction}:${this.id}`);\n if (this.remoteAddr.getPeerId() == null) {\n this.remoteAddr = this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`);\n }\n this._newStream = newStream;\n this._close = close;\n this._abort = abort;\n this._getStreams = getStreams;\n this.tags = [];\n }\n [Symbol.toStringTag] = 'Connection';\n [connectionSymbol] = true;\n /**\n * Get all the streams of the muxer\n */\n get streams() {\n return this._getStreams();\n }\n /**\n * Create a new stream from this connection\n */\n async newStream(protocols, options) {\n if (this.status === 'closing') {\n throw new ConnectionClosingError('the connection is being closed');\n }\n if (this.status === 'closed') {\n throw new ConnectionClosedError('the connection is closed');\n }\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n if (this.limits != null && options?.runOnLimitedConnection !== true) {\n throw new LimitedConnectionError('Cannot open protocol stream on limited connection');\n }\n const stream = await this._newStream(protocols, options);\n stream.direction = 'outbound';\n return stream;\n }\n /**\n * Close the connection\n */\n async close(options = {}) {\n if (this.status === 'closed' || this.status === 'closing') {\n return;\n }\n this.log('closing connection to %a', this.remoteAddr);\n this.status = 'closing';\n if (options.signal == null) {\n const signal = AbortSignal.timeout(CLOSE_TIMEOUT);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n this.log.trace('closing underlying transport');\n // close raw connection\n await this._close(options);\n this.log.trace('updating timeline with close time');\n this.status = 'closed';\n this.timeline.close = Date.now();\n }\n catch (err) {\n this.log.error('error encountered during graceful close of connection to %a', this.remoteAddr, err);\n this.abort(err);\n }\n }\n abort(err) {\n if (this.status === 'closed') {\n return;\n }\n this.log.error('aborting connection to %a due to error', this.remoteAddr, err);\n this.status = 'closing';\n // Abort raw connection\n this._abort(err);\n this.status = 'closed';\n this.timeline.close = Date.now();\n }\n}\nexport function createConnection(init) {\n return new ConnectionImpl(init);\n}\n//# sourceMappingURL=index.js.map","import { InvalidMultiaddrError, TooManyInboundProtocolStreamsError, TooManyOutboundProtocolStreamsError, LimitedConnectionError, setMaxListeners, InvalidPeerIdError } from '@libp2p/interface';\nimport * as mss from '@libp2p/multistream-select';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { anySignal } from 'any-signal';\nimport { CustomProgressEvent } from 'progress-events';\nimport { createConnection } from './connection/index.js';\nimport { PROTOCOL_NEGOTIATION_TIMEOUT, UPGRADE_TIMEOUT } from './connection-manager/constants.js';\nimport { ConnectionDeniedError, ConnectionInterceptedError, EncryptionFailedError, MuxerUnavailableError } from './errors.js';\nimport { DEFAULT_MAX_INBOUND_STREAMS, DEFAULT_MAX_OUTBOUND_STREAMS } from './registrar.js';\nfunction findIncomingStreamLimit(protocol, registrar) {\n try {\n const { options } = registrar.getHandler(protocol);\n return options.maxInboundStreams;\n }\n catch (err) {\n if (err.name !== 'UnhandledProtocolError') {\n throw err;\n }\n }\n return DEFAULT_MAX_INBOUND_STREAMS;\n}\nfunction findOutgoingStreamLimit(protocol, registrar, options = {}) {\n try {\n const { options } = registrar.getHandler(protocol);\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams;\n }\n }\n catch (err) {\n if (err.name !== 'UnhandledProtocolError') {\n throw err;\n }\n }\n return options.maxOutboundStreams ?? DEFAULT_MAX_OUTBOUND_STREAMS;\n}\nfunction countStreams(protocol, direction, connection) {\n let streamCount = 0;\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++;\n }\n });\n return streamCount;\n}\nexport class DefaultUpgrader {\n components;\n connectionEncrypters;\n streamMuxers;\n inboundUpgradeTimeout;\n outboundUpgradeTimeout;\n inboundStreamProtocolNegotiationTimeout;\n outboundStreamProtocolNegotiationTimeout;\n events;\n metrics;\n constructor(components, init) {\n this.components = components;\n this.connectionEncrypters = new Map();\n init.connectionEncrypters.forEach(encrypter => {\n this.connectionEncrypters.set(encrypter.protocol, encrypter);\n });\n this.streamMuxers = new Map();\n init.streamMuxers.forEach(muxer => {\n this.streamMuxers.set(muxer.protocol, muxer);\n });\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? UPGRADE_TIMEOUT;\n this.outboundUpgradeTimeout = init.outboundUpgradeTimeout ?? UPGRADE_TIMEOUT;\n this.inboundStreamProtocolNegotiationTimeout = init.inboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT;\n this.outboundStreamProtocolNegotiationTimeout = init.outboundStreamProtocolNegotiationTimeout ?? PROTOCOL_NEGOTIATION_TIMEOUT;\n this.events = components.events;\n this.metrics = {\n dials: components.metrics?.registerCounterGroup('libp2p_connection_manager_dials_total'),\n errors: components.metrics?.registerCounterGroup('libp2p_connection_manager_dial_errors_total')\n };\n }\n [Symbol.toStringTag] = '@libp2p/upgrader';\n async shouldBlockConnection(method, ...args) {\n const denyOperation = this.components.connectionGater[method];\n if (denyOperation == null) {\n return;\n }\n const result = await denyOperation.apply(this.components.connectionGater, args);\n if (result === true) {\n throw new ConnectionInterceptedError(`The multiaddr connection is blocked by gater.${method}`);\n }\n }\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound(maConn, opts = {}) {\n try {\n this.metrics.dials?.increment({\n inbound: true\n });\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn);\n if (!accept) {\n throw new ConnectionDeniedError('connection denied');\n }\n await this.shouldBlockConnection('denyInboundConnection', maConn);\n const conn = await this._performUpgrade(maConn, 'inbound', opts);\n return conn;\n }\n catch (err) {\n this.metrics.errors?.increment({\n inbound: true\n });\n throw err;\n }\n finally {\n this.components.connectionManager.afterUpgradeInbound();\n }\n }\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound(maConn, opts = {}) {\n try {\n this.metrics.dials?.increment({\n outbound: true\n });\n const idStr = maConn.remoteAddr.getPeerId();\n let remotePeerId;\n if (idStr != null) {\n remotePeerId = peerIdFromString(idStr);\n await this.shouldBlockConnection('denyOutboundConnection', remotePeerId, maConn);\n }\n return await this._performUpgrade(maConn, 'outbound', opts);\n }\n catch (err) {\n this.metrics.errors?.increment({\n outbound: true\n });\n throw err;\n }\n }\n async _performUpgrade(maConn, direction, opts) {\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let muxerFactory;\n let cryptoProtocol;\n const upgradeTimeoutSignal = AbortSignal.timeout(direction === 'inbound' ? this.inboundUpgradeTimeout : this.outboundUpgradeTimeout);\n const signal = anySignal([upgradeTimeoutSignal, opts.signal]);\n setMaxListeners(Infinity, upgradeTimeoutSignal, signal);\n opts.signal = signal;\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log.trace('starting the %s connection upgrade', direction);\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n maConn.log('protecting the %s connection', direction);\n protectedConn = await protector.protect(maConn, opts);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n opts?.onProgress?.(new CustomProgressEvent(`upgrader:encrypt-${direction}-connection`));\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await (direction === 'inbound'\n ? this._encryptInbound(protectedConn, {\n ...opts,\n signal\n })\n : this._encryptOutbound(protectedConn, {\n ...opts,\n signal\n })));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundEncryptedConnection' : 'denyOutboundEncryptedConnection', remotePeer, maConn);\n }\n else {\n const idStr = maConn.remoteAddr.getPeerId();\n if (idStr == null) {\n throw new InvalidMultiaddrError(`${direction} connection that skipped encryption must have a peer id`);\n }\n const remotePeerId = peerIdFromString(idStr);\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n // this can happen if we dial a multiaddr without a peer id, we only find\n // out the identity of the remote after the connection is encrypted\n if (remotePeer.equals(this.components.peerId)) {\n const err = new InvalidPeerIdError('Can not dial self');\n maConn.abort(err);\n throw err;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.streamMuxers.size > 0) {\n opts?.onProgress?.(new CustomProgressEvent(`upgrader:multiplex-${direction}-connection`));\n // Multiplex the connection\n const multiplexed = await (direction === 'inbound'\n ? this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.streamMuxers, opts)\n : this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.streamMuxers, opts));\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade inbound connection %s %a - %e', direction === 'inbound' ? 'from' : 'to', maConn.remoteAddr, err);\n throw err;\n }\n finally {\n signal.clear();\n }\n await this.shouldBlockConnection(direction === 'inbound' ? 'denyInboundUpgradedConnection' : 'denyOutboundUpgradedConnection', remotePeer, maConn);\n maConn.log('successfully upgraded %s connection', direction);\n return this._createConnection({\n cryptoProtocol,\n direction,\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n limits: opts?.limits\n });\n }\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection(opts) {\n const { cryptoProtocol, direction, maConn, upgradedConn, remotePeer, muxerFactory, limits } = opts;\n let muxer;\n let newStream;\n let connection; // eslint-disable-line prefer-const\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return;\n }\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols();\n const signal = AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);\n setMaxListeners(Infinity, signal);\n const { stream, protocol } = await mss.handle(muxedStream, protocols, {\n signal,\n log: muxedStream.log,\n yieldBytes: false\n });\n if (connection == null) {\n return;\n }\n connection.log('incoming stream opened on %s', protocol);\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar);\n const streamCount = countStreams(protocol, 'inbound', connection);\n if (streamCount === incomingLimit) {\n const err = new TooManyInboundProtocolStreamsError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`);\n muxedStream.abort(err);\n throw err;\n }\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n this._onStream({ connection, stream: muxedStream, protocol });\n })\n .catch(async (err) => {\n connection.log.error('error handling incoming stream id %s - %e', muxedStream.id, err);\n if (muxedStream.timeline.close == null) {\n await muxedStream.close();\n }\n });\n }\n });\n newStream = async (protocols, options = {}) => {\n if (muxer == null) {\n throw new MuxerUnavailableError('Connection is not multiplexed');\n }\n connection.log.trace('starting new stream for protocols %s', protocols);\n const muxedStream = await muxer.newStream();\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols);\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols);\n const signal = AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);\n setMaxListeners(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n muxedStream.log.trace('selecting protocol from protocols %s', protocols);\n const { stream, protocol } = await mss.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n });\n muxedStream.log.trace('selected protocol %s', protocol);\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);\n const streamCount = countStreams(protocol, 'outbound', connection);\n if (streamCount >= outgoingLimit) {\n const err = new TooManyOutboundProtocolStreamsError(`Too many outbound protocol streams for protocol \"${protocol}\" - ${streamCount}/${outgoingLimit}`);\n muxedStream.abort(err);\n throw err;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n return muxedStream;\n }\n catch (err) {\n connection.log.error('could not create new outbound stream on connection %s %a for protocols %s - %e', direction === 'inbound' ? 'from' : 'to', opts.maConn.remoteAddr, protocols, err);\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err);\n }\n throw err;\n }\n };\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer - %e', err);\n });\n }\n const _timeline = maConn.timeline;\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close();\n }\n }\n catch (err) {\n connection.log.error('error closing connection after timeline close %e', err);\n }\n finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n });\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event %e', err);\n });\n }\n return Reflect.set(...args);\n }\n });\n maConn.timeline.upgraded = Date.now();\n const errConnectionNotMultiplexed = () => {\n throw new MuxerUnavailableError('Connection is not multiplexed');\n };\n // Create the connection\n connection = createConnection({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n limits,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => {\n return muxer?.streams ?? [];\n },\n close: async (options) => {\n // ensure remaining streams are closed gracefully\n await muxer?.close(options);\n // close the underlying transport\n await maConn.close(options);\n },\n abort: (err) => {\n maConn.abort(err);\n // ensure remaining streams are aborted\n muxer?.abort(err);\n }\n });\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n });\n // @ts-expect-error nah\n connection.__maConnTimeline = _timeline;\n return connection;\n }\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream(opts) {\n const { connection, stream, protocol } = opts;\n const { handler, options } = this.components.registrar.getHandler(protocol);\n if (connection.limits != null && options.runOnLimitedConnection !== true) {\n throw new LimitedConnectionError('Cannot open protocol stream on limited connection');\n }\n handler({ connection, stream });\n }\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound(connection, options) {\n const protocols = Array.from(this.connectionEncrypters.keys());\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n ...options,\n log: connection.log\n });\n const encrypter = this.connectionEncrypters.get(protocol);\n if (encrypter == null) {\n throw new EncryptionFailedError(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting inbound connection to %a using %s', connection.remoteAddr, protocol);\n return {\n ...await encrypter.secureInbound(stream, options),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting inbound connection from %a failed', connection.remoteAddr, err);\n throw new EncryptionFailedError(err.message);\n }\n }\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound(connection, options) {\n const protocols = Array.from(this.connectionEncrypters.keys());\n try {\n connection.log.trace('selecting encrypter from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n ...options,\n log: connection.log,\n yieldBytes: true\n });\n const encrypter = this.connectionEncrypters.get(protocol);\n if (encrypter == null) {\n throw new EncryptionFailedError(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting outbound connection to %a using %s', connection.remoteAddr, protocol);\n return {\n ...await encrypter.secureOutbound(stream, options),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting outbound connection to %a failed', connection.remoteAddr, err);\n throw new EncryptionFailedError(err.message);\n }\n }\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound(connection, muxers, options) {\n const protocols = Array.from(muxers.keys());\n connection.log('outbound selecting muxer %s', protocols);\n try {\n connection.log.trace('selecting stream muxer from %s', protocols);\n const { stream, protocol } = await mss.select(connection, protocols, {\n ...options,\n log: connection.log,\n yieldBytes: true\n });\n connection.log('selected %s as muxer protocol', protocol);\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing outbound connection', err);\n throw new MuxerUnavailableError(String(err));\n }\n }\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound(connection, muxers, options) {\n const protocols = Array.from(muxers.keys());\n connection.log('inbound handling muxers %s', protocols);\n try {\n const { stream, protocol } = await mss.handle(connection, protocols, {\n ...options,\n log: connection.log\n });\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing inbound connection', err);\n throw new MuxerUnavailableError(String(err));\n }\n }\n}\n//# sourceMappingURL=upgrader.js.map","import { publicKeyFromProtobuf } from '@libp2p/crypto/keys';\nimport { contentRoutingSymbol, TypedEventEmitter, setMaxListeners, peerDiscoverySymbol, peerRoutingSymbol, InvalidParametersError } from '@libp2p/interface';\nimport { defaultLogger } from '@libp2p/logger';\nimport { PeerSet } from '@libp2p/peer-collections';\nimport { peerIdFromString } from '@libp2p/peer-id';\nimport { persistentPeerStore } from '@libp2p/peer-store';\nimport { isMultiaddr } from '@multiformats/multiaddr';\nimport { MemoryDatastore } from 'datastore-core/memory';\nimport { concat as uint8ArrayConcat } from 'uint8arrays/concat';\nimport { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';\nimport { DefaultAddressManager } from './address-manager/index.js';\nimport { checkServiceDependencies, defaultComponents } from './components.js';\nimport { connectionGater } from './config/connection-gater.js';\nimport { DefaultConnectionManager } from './connection-manager/index.js';\nimport { ConnectionMonitor } from './connection-monitor.js';\nimport { CompoundContentRouting } from './content-routing.js';\nimport { DefaultPeerRouting } from './peer-routing.js';\nimport { RandomWalk } from './random-walk.js';\nimport { DefaultRegistrar } from './registrar.js';\nimport { DefaultTransportManager } from './transport-manager.js';\nimport { DefaultUpgrader } from './upgrader.js';\nimport * as pkg from './version.js';\nexport class Libp2p extends TypedEventEmitter {\n peerId;\n peerStore;\n contentRouting;\n peerRouting;\n metrics;\n services;\n logger;\n status;\n components;\n log;\n constructor(init) {\n super();\n this.status = 'stopped';\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new TypedEventEmitter();\n const originalDispatch = events.dispatchEvent.bind(events);\n events.dispatchEvent = (evt) => {\n const internalResult = originalDispatch(evt);\n const externalResult = this.dispatchEvent(new CustomEvent(evt.type, { detail: evt.detail }));\n return internalResult || externalResult;\n };\n // This emitter gets listened to a lot\n setMaxListeners(Infinity, events);\n this.peerId = init.peerId;\n this.logger = init.logger ?? defaultLogger();\n this.log = this.logger.forComponent('libp2p');\n // @ts-expect-error {} may not be of type T\n this.services = {};\n // @ts-expect-error defaultComponents is missing component types added later\n const components = this.components = defaultComponents({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: pkg.name,\n version: pkg.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new MemoryDatastore(),\n connectionGater: connectionGater(init.connectionGater),\n dns: init.dns\n });\n this.peerStore = this.configureComponent('peerStore', persistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }));\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components));\n }\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n };\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo });\n }\n });\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components));\n }\n // Set up the Upgrader\n this.components.upgrader = new DefaultUpgrader(this.components, {\n connectionEncrypters: (init.connectionEncrypters ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n streamMuxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout,\n outboundUpgradeTimeout: init.connectionManager?.outboundUpgradeTimeout\n });\n // Setup the transport manager\n this.configureComponent('transportManager', new DefaultTransportManager(this.components, init.transportManager));\n // Create the Connection Manager\n this.configureComponent('connectionManager', new DefaultConnectionManager(this.components, init.connectionManager));\n if (init.connectionMonitor?.enabled !== false) {\n // Create the Connection Monitor if not disabled\n this.configureComponent('connectionMonitor', new ConnectionMonitor(this.components, init.connectionMonitor));\n }\n // Create the Registrar\n this.configureComponent('registrar', new DefaultRegistrar(this.components));\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new DefaultAddressManager(this.components, init.addresses));\n // Peer routers\n const peerRouters = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)));\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new DefaultPeerRouting(this.components, {\n routers: peerRouters\n }));\n // Content routers\n const contentRouters = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)));\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new CompoundContentRouting(this.components, {\n routers: contentRouters\n }));\n // Random walk\n this.configureComponent('randomWalk', new RandomWalk(this.components));\n (init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components));\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n });\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)));\n });\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name];\n const service = createService(this.components);\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name);\n continue;\n }\n this.services[name] = service;\n this.configureComponent(name, service);\n if (service[contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name);\n contentRouters.push(service[contentRoutingSymbol]);\n }\n if (service[peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name);\n peerRouters.push(service[peerRoutingSymbol]);\n }\n if (service[peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name);\n service[peerDiscoverySymbol].addEventListener?.('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n }\n }\n }\n // Ensure all services have their required dependencies\n checkServiceDependencies(components);\n }\n configureComponent(name, component) {\n if (component == null) {\n this.log.error('component %s was null or undefined', name);\n }\n // @ts-expect-error cannot assign props\n this.components[name] = component;\n return component;\n }\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start() {\n if (this.status !== 'stopped') {\n return;\n }\n this.status = 'starting';\n this.log('libp2p is starting');\n try {\n await this.components.beforeStart?.();\n await this.components.start();\n await this.components.afterStart?.();\n this.status = 'started';\n this.safeDispatchEvent('start', { detail: this });\n this.log('libp2p has started');\n }\n catch (err) {\n this.log.error('An error occurred starting libp2p', err);\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started';\n await this.stop();\n throw err;\n }\n }\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop() {\n if (this.status !== 'started') {\n return;\n }\n this.log('libp2p is stopping');\n this.status = 'stopping';\n await this.components.beforeStop?.();\n await this.components.stop();\n await this.components.afterStop?.();\n this.status = 'stopped';\n this.safeDispatchEvent('stop', { detail: this });\n this.log('libp2p has stopped');\n }\n getConnections(peerId) {\n return this.components.connectionManager.getConnections(peerId);\n }\n getDialQueue() {\n return this.components.connectionManager.getDialQueue();\n }\n getPeers() {\n const peerSet = new PeerSet();\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer);\n }\n return Array.from(peerSet);\n }\n async dial(peer, options = {}) {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n });\n }\n async dialProtocol(peer, protocols, options = {}) {\n if (protocols == null) {\n throw new InvalidParametersError('no protocols were provided to open a stream');\n }\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n if (protocols.length === 0) {\n throw new InvalidParametersError('no protocols were provided to open a stream');\n }\n const connection = await this.dial(peer, options);\n return connection.newStream(protocols, options);\n }\n getMultiaddrs() {\n return this.components.addressManager.getAddresses();\n }\n getProtocols() {\n return this.components.registrar.getProtocols();\n }\n async hangUp(peer, options = {}) {\n if (isMultiaddr(peer)) {\n peer = peerIdFromString(peer.getPeerId() ?? '');\n }\n await this.components.connectionManager.closeConnections(peer, options);\n }\n async getPublicKey(peer, options = {}) {\n this.log('getPublicKey %p', peer);\n if (peer.publicKey != null) {\n return peer.publicKey;\n }\n try {\n const peerInfo = await this.peerStore.get(peer);\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey;\n }\n }\n catch (err) {\n if (err.name !== 'NotFoundError') {\n throw err;\n }\n }\n const peerKey = uint8ArrayConcat([\n uint8ArrayFromString('/pk/'),\n peer.toMultihash().bytes\n ]);\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options);\n // ensure the returned key is valid\n const publicKey = publicKeyFromProtobuf(bytes);\n await this.peerStore.patch(peer, {\n publicKey\n });\n return publicKey;\n }\n async handle(protocols, handler, options) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.handle(protocol, handler, options);\n }));\n }\n async unhandle(protocols) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.unhandle(protocol);\n }));\n }\n async register(protocol, topology) {\n return this.components.registrar.register(protocol, topology);\n }\n unregister(id) {\n this.components.registrar.unregister(id);\n }\n async isDialable(multiaddr, options = {}) {\n return this.components.connectionManager.isDialable(multiaddr, options);\n }\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer(evt) {\n const { detail: peer } = evt;\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error('peer discovery mechanism discovered self');\n return;\n }\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err); });\n }\n}\n//# sourceMappingURL=libp2p.js.map","export const version = '2.1.8';\nexport const name = 'libp2p';\n//# sourceMappingURL=version.js.map","/**\n * The ENR tree for the different fleets.\n * SANDBOX and TEST fleets are for The Waku Network.\n */\nexport const enrTree = {\n SANDBOX: \"enrtree://AIRVQ5DDA4FFWLRBCHJWUWOO6X6S4ZTZ5B667LQ6AJU6PEYDLRD5O@sandbox.waku.nodes.status.im\",\n TEST: \"enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im\"\n};\nexport const DEFAULT_BOOTSTRAP_TAG_NAME = \"bootstrap\";\nexport const DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nexport const DEFAULT_BOOTSTRAP_TAG_TTL = 100_000_000;\nexport const DEFAULT_NODE_REQUIREMENTS = {\n store: 1,\n filter: 2,\n lightPush: 2\n};\n//# sourceMappingURL=constants.js.map","/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nimport * as nodeCrypto from 'crypto';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _8n = BigInt(8);\nconst CURVE = Object.freeze({\n a: _0n,\n b: BigInt(7),\n P: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: _1n,\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n});\nconst divNearest = (a, b) => (a + b / _2n) / b;\nconst endo = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar(k) {\n const { n } = CURVE;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000');\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalarEndo: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n};\nconst fieldLen = 32;\nconst groupLen = 32;\nconst hashLen = 32;\nconst compressedLen = fieldLen + 1;\nconst uncompressedLen = 2 * fieldLen + 1;\nexport { CURVE };\nfunction weierstrass(x) {\n const { a, b } = CURVE;\n const x2 = mod(x * x);\n const x3 = mod(x2 * x);\n return mod(x3 + a * x + b);\n}\nconst USE_ENDOMORPHISM = CURVE.a === _0n;\nclass ShaError extends Error {\n constructor(message) {\n super(message);\n }\n}\nfunction assertJacPoint(other) {\n if (!(other instanceof JacobianPoint))\n throw new TypeError('JacobianPoint expected');\n}\nclass JacobianPoint {\n constructor(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n static fromAffine(p) {\n if (!(p instanceof Point)) {\n throw new TypeError('JacobianPoint#fromAffine: expected Point');\n }\n if (p.equals(Point.ZERO))\n return JacobianPoint.ZERO;\n return new JacobianPoint(p.x, p.y, _1n);\n }\n static toAffineBatch(points) {\n const toInv = invertBatch(points.map((p) => p.z));\n return points.map((p, i) => p.toAffine(toInv[i]));\n }\n static normalizeZ(points) {\n return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);\n }\n equals(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n return U1 === U2 && S1 === S2;\n }\n negate() {\n return new JacobianPoint(this.x, mod(-this.y), this.z);\n }\n double() {\n const { x: X1, y: Y1, z: Z1 } = this;\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(B * B);\n const x1b = X1 + B;\n const D = mod(_2n * (mod(x1b * x1b) - A - C));\n const E = mod(_3n * A);\n const F = mod(E * E);\n const X3 = mod(F - _2n * D);\n const Y3 = mod(E * (D - X3) - _8n * C);\n const Z3 = mod(_2n * Y1 * Z1);\n return new JacobianPoint(X3, Y3, Z3);\n }\n add(other) {\n assertJacPoint(other);\n const { x: X1, y: Y1, z: Z1 } = this;\n const { x: X2, y: Y2, z: Z2 } = other;\n if (X2 === _0n || Y2 === _0n)\n return this;\n if (X1 === _0n || Y1 === _0n)\n return other;\n const Z1Z1 = mod(Z1 * Z1);\n const Z2Z2 = mod(Z2 * Z2);\n const U1 = mod(X1 * Z2Z2);\n const U2 = mod(X2 * Z1Z1);\n const S1 = mod(mod(Y1 * Z2) * Z2Z2);\n const S2 = mod(mod(Y2 * Z1) * Z1Z1);\n const H = mod(U2 - U1);\n const r = mod(S2 - S1);\n if (H === _0n) {\n if (r === _0n) {\n return this.double();\n }\n else {\n return JacobianPoint.ZERO;\n }\n }\n const HH = mod(H * H);\n const HHH = mod(H * HH);\n const V = mod(U1 * HH);\n const X3 = mod(r * r - HHH - _2n * V);\n const Y3 = mod(r * (V - X3) - S1 * HHH);\n const Z3 = mod(Z1 * Z2 * H);\n return new JacobianPoint(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiplyUnsafe(scalar) {\n const P0 = JacobianPoint.ZERO;\n if (typeof scalar === 'bigint' && scalar === _0n)\n return P0;\n let n = normalizeScalar(scalar);\n if (n === _1n)\n return this;\n if (!USE_ENDOMORPHISM) {\n let p = P0;\n let d = this;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = P0;\n let k2p = P0;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n return k1p.add(k2p);\n }\n precomputeWindow(W) {\n const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;\n const points = [];\n let p = this;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n for (let i = 1; i < 2 ** (W - 1); i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n wNAF(n, affinePoint) {\n if (!affinePoint && this.equals(JacobianPoint.BASE))\n affinePoint = Point.BASE;\n const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;\n if (256 % W) {\n throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');\n }\n let precomputes = affinePoint && pointPrecomputes.get(affinePoint);\n if (!precomputes) {\n precomputes = this.precomputeWindow(W);\n if (affinePoint && W !== 1) {\n precomputes = JacobianPoint.normalizeZ(precomputes);\n pointPrecomputes.set(affinePoint, precomputes);\n }\n }\n let p = JacobianPoint.ZERO;\n let f = JacobianPoint.BASE;\n const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);\n const windowSize = 2 ** (W - 1);\n const mask = BigInt(2 ** W - 1);\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n let wbits = Number(n & mask);\n n >>= shiftBy;\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1;\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n return { p, f };\n }\n multiply(scalar, affinePoint) {\n let n = normalizeScalar(scalar);\n let point;\n let fake;\n if (USE_ENDOMORPHISM) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);\n let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);\n k1p = constTimeNegate(k1neg, k1p);\n k2p = constTimeNegate(k2neg, k2p);\n k2p = new JacobianPoint(mod(k2p.x * endo.beta), k2p.y, k2p.z);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n, affinePoint);\n point = p;\n fake = f;\n }\n return JacobianPoint.normalizeZ([point, fake])[0];\n }\n toAffine(invZ) {\n const { x, y, z } = this;\n const is0 = this.equals(JacobianPoint.ZERO);\n if (invZ == null)\n invZ = is0 ? _8n : invert(z);\n const iz1 = invZ;\n const iz2 = mod(iz1 * iz1);\n const iz3 = mod(iz2 * iz1);\n const ax = mod(x * iz2);\n const ay = mod(y * iz3);\n const zz = mod(z * iz1);\n if (is0)\n return Point.ZERO;\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return new Point(ax, ay);\n }\n}\nJacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);\nJacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nconst pointPrecomputes = new WeakMap();\nexport class Point {\n constructor(x, y) {\n this.x = x;\n this.y = y;\n }\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n hasEvenY() {\n return this.y % _2n === _0n;\n }\n static fromCompressedHex(bytes) {\n const isShort = bytes.length === 32;\n const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrass(x);\n let y = sqrtMod(y2);\n const isYOdd = (y & _1n) === _1n;\n if (isShort) {\n if (isYOdd)\n y = mod(-y);\n }\n else {\n const isFirstByteOdd = (bytes[0] & 1) === 1;\n if (isFirstByteOdd !== isYOdd)\n y = mod(-y);\n }\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromUncompressedHex(bytes) {\n const x = bytesToNumber(bytes.subarray(1, fieldLen + 1));\n const y = bytesToNumber(bytes.subarray(fieldLen + 1, fieldLen * 2 + 1));\n const point = new Point(x, y);\n point.assertValidity();\n return point;\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n const len = bytes.length;\n const header = bytes[0];\n if (len === fieldLen)\n return this.fromCompressedHex(bytes);\n if (len === compressedLen && (header === 0x02 || header === 0x03)) {\n return this.fromCompressedHex(bytes);\n }\n if (len === uncompressedLen && header === 0x04)\n return this.fromUncompressedHex(bytes);\n throw new Error(`Point.fromHex: received invalid point. Expected 32-${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes, not ${len}`);\n }\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normalizePrivateKey(privateKey));\n }\n static fromSignature(msgHash, signature, recovery) {\n const { r, s } = normalizeSignature(signature);\n if (![0, 1, 2, 3].includes(recovery))\n throw new Error('Cannot recover: invalid recovery bit');\n const h = truncateHash(ensureBytes(msgHash));\n const { n } = CURVE;\n const radj = recovery === 2 || recovery === 3 ? r + n : r;\n const rinv = invert(radj, n);\n const u1 = mod(-h * rinv, n);\n const u2 = mod(s * rinv, n);\n const prefix = recovery & 1 ? '03' : '02';\n const R = Point.fromHex(prefix + numTo32bStr(radj));\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);\n if (!Q)\n throw new Error('Cannot recover signature: point at infinify');\n Q.assertValidity();\n return Q;\n }\n toRawBytes(isCompressed = false) {\n return hexToBytes(this.toHex(isCompressed));\n }\n toHex(isCompressed = false) {\n const x = numTo32bStr(this.x);\n if (isCompressed) {\n const prefix = this.hasEvenY() ? '02' : '03';\n return `${prefix}${x}`;\n }\n else {\n return `04${x}${numTo32bStr(this.y)}`;\n }\n }\n toHexX() {\n return this.toHex(true).slice(2);\n }\n toRawX() {\n return this.toRawBytes(true).slice(1);\n }\n assertValidity() {\n const msg = 'Point is not on elliptic curve';\n const { x, y } = this;\n if (!isValidFieldElement(x) || !isValidFieldElement(y))\n throw new Error(msg);\n const left = mod(y * y);\n const right = weierstrass(x);\n if (mod(left - right) !== _0n)\n throw new Error(msg);\n }\n equals(other) {\n return this.x === other.x && this.y === other.y;\n }\n negate() {\n return new Point(this.x, mod(-this.y));\n }\n double() {\n return JacobianPoint.fromAffine(this).double().toAffine();\n }\n add(other) {\n return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();\n }\n subtract(other) {\n return this.add(other.negate());\n }\n multiply(scalar) {\n return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();\n }\n multiplyAndAddUnsafe(Q, a, b) {\n const P = JacobianPoint.fromAffine(this);\n const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);\n const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);\n const sum = aP.add(bQ);\n return sum.equals(JacobianPoint.ZERO) ? undefined : sum.toAffine();\n }\n}\nPoint.BASE = new Point(CURVE.Gx, CURVE.Gy);\nPoint.ZERO = new Point(_0n, _0n);\nfunction sliceDER(s) {\n return Number.parseInt(s[0], 16) >= 8 ? '00' + s : s;\n}\nfunction parseDERInt(data) {\n if (data.length < 2 || data[0] !== 0x02) {\n throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);\n }\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) {\n throw new Error(`Invalid signature integer: wrong length`);\n }\n if (res[0] === 0x00 && res[1] <= 0x7f) {\n throw new Error('Invalid signature integer: trailing length');\n }\n return { data: bytesToNumber(res), left: data.subarray(len + 2) };\n}\nfunction parseDERSignature(data) {\n if (data.length < 2 || data[0] != 0x30) {\n throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);\n }\n if (data[1] !== data.length - 2) {\n throw new Error('Invalid signature: incorrect length');\n }\n const { data: r, left: sBytes } = parseDERInt(data.subarray(2));\n const { data: s, left: rBytesLeft } = parseDERInt(sBytes);\n if (rBytesLeft.length) {\n throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);\n }\n return { r, s };\n}\nexport class Signature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromCompact(hex) {\n const arr = hex instanceof Uint8Array;\n const name = 'Signature.fromCompact';\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`${name}: Expected string or Uint8Array`);\n const str = arr ? bytesToHex(hex) : hex;\n if (str.length !== 128)\n throw new Error(`${name}: Expected 64-byte hex`);\n return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));\n }\n static fromDER(hex) {\n const arr = hex instanceof Uint8Array;\n if (typeof hex !== 'string' && !arr)\n throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);\n const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));\n return new Signature(r, s);\n }\n static fromHex(hex) {\n return this.fromDER(hex);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isWithinCurveOrder(r))\n throw new Error('Invalid Signature: r must be 0 < r < n');\n if (!isWithinCurveOrder(s))\n throw new Error('Invalid Signature: s must be 0 < s < n');\n }\n hasHighS() {\n const HALF = CURVE.n >> _1n;\n return this.s > HALF;\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, mod(-this.s, CURVE.n)) : this;\n }\n toDERRawBytes() {\n return hexToBytes(this.toDERHex());\n }\n toDERHex() {\n const sHex = sliceDER(numberToHexUnpadded(this.s));\n const rHex = sliceDER(numberToHexUnpadded(this.r));\n const sHexL = sHex.length / 2;\n const rHexL = rHex.length / 2;\n const sLen = numberToHexUnpadded(sHexL);\n const rLen = numberToHexUnpadded(rHexL);\n const length = numberToHexUnpadded(rHexL + sHexL + 4);\n return `30${length}02${rLen}${rHex}02${sLen}${sHex}`;\n }\n toRawBytes() {\n return this.toDERRawBytes();\n }\n toHex() {\n return this.toDERHex();\n }\n toCompactRawBytes() {\n return hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n}\nfunction concatBytes(...arrays) {\n if (!arrays.every((b) => b instanceof Uint8Array))\n throw new Error('Uint8Array list expected');\n if (arrays.length === 1)\n return arrays[0];\n const length = arrays.reduce((a, arr) => a + arr.length, 0);\n const result = new Uint8Array(length);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n result.set(arr, pad);\n pad += arr.length;\n }\n return result;\n}\nconst hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\nfunction bytesToHex(uint8a) {\n if (!(uint8a instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n let hex = '';\n for (let i = 0; i < uint8a.length; i++) {\n hex += hexes[uint8a[i]];\n }\n return hex;\n}\nconst POW_2_256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');\nfunction numTo32bStr(num) {\n if (typeof num !== 'bigint')\n throw new Error('Expected bigint');\n if (!(_0n <= num && num < POW_2_256))\n throw new Error('Expected number 0 <= n < 2^256');\n return num.toString(16).padStart(64, '0');\n}\nfunction numTo32b(num) {\n const b = hexToBytes(numTo32bStr(num));\n if (b.length !== 32)\n throw new Error('Error: expected 32 bytes');\n return b;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToNumber: expected string, got ' + typeof hex);\n }\n return BigInt(`0x${hex}`);\n}\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string') {\n throw new TypeError('hexToBytes: expected string, got ' + typeof hex);\n }\n if (hex.length % 2)\n throw new Error('hexToBytes: received invalid unpadded hex' + hex.length);\n const array = new Uint8Array(hex.length / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\nfunction bytesToNumber(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction ensureBytes(hex) {\n return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);\n}\nfunction normalizeScalar(num) {\n if (typeof num === 'number' && Number.isSafeInteger(num) && num > 0)\n return BigInt(num);\n if (typeof num === 'bigint' && isWithinCurveOrder(num))\n return num;\n throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');\n}\nfunction mod(a, b = CURVE.P) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\nfunction pow2(x, power) {\n const { P } = CURVE;\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= P;\n }\n return res;\n}\nfunction sqrtMod(x) {\n const { P } = CURVE;\n const _6n = BigInt(6);\n const _11n = BigInt(11);\n const _22n = BigInt(22);\n const _23n = BigInt(23);\n const _44n = BigInt(44);\n const _88n = BigInt(88);\n const b2 = (x * x * x) % P;\n const b3 = (b2 * b2 * x) % P;\n const b6 = (pow2(b3, _3n) * b3) % P;\n const b9 = (pow2(b6, _3n) * b3) % P;\n const b11 = (pow2(b9, _2n) * b2) % P;\n const b22 = (pow2(b11, _11n) * b11) % P;\n const b44 = (pow2(b22, _22n) * b22) % P;\n const b88 = (pow2(b44, _44n) * b44) % P;\n const b176 = (pow2(b88, _88n) * b88) % P;\n const b220 = (pow2(b176, _44n) * b44) % P;\n const b223 = (pow2(b220, _3n) * b3) % P;\n const t1 = (pow2(b223, _23n) * b22) % P;\n const t2 = (pow2(t1, _6n) * b2) % P;\n const rt = pow2(t2, _2n);\n const xc = (rt * rt) % P;\n if (xc !== x)\n throw new Error('Cannot find square root');\n return rt;\n}\nfunction invert(number, modulo = CURVE.P) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n let a = mod(number, modulo);\n let b = modulo;\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\nfunction invertBatch(nums, p = CURVE.P) {\n const scratch = new Array(nums.length);\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = acc;\n return mod(acc * num, p);\n }, _1n);\n const inverted = invert(lastMultiplied, p);\n nums.reduceRight((acc, num, i) => {\n if (num === _0n)\n return acc;\n scratch[i] = mod(acc * scratch[i], p);\n return mod(acc * num, p);\n }, inverted);\n return scratch;\n}\nfunction bits2int_2(bytes) {\n const delta = bytes.length * 8 - groupLen * 8;\n const num = bytesToNumber(bytes);\n return delta > 0 ? num >> BigInt(delta) : num;\n}\nfunction truncateHash(hash, truncateOnly = false) {\n const h = bits2int_2(hash);\n if (truncateOnly)\n return h;\n const { n } = CURVE;\n return h >= n ? h - n : h;\n}\nlet _sha256Sync;\nlet _hmacSha256Sync;\nclass HmacDrbg {\n constructor(hashLen, qByteLen) {\n this.hashLen = hashLen;\n this.qByteLen = qByteLen;\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n this.v = new Uint8Array(hashLen).fill(1);\n this.k = new Uint8Array(hashLen).fill(0);\n this.counter = 0;\n }\n hmac(...values) {\n return utils.hmacSha256(this.k, ...values);\n }\n hmacSync(...values) {\n return _hmacSha256Sync(this.k, ...values);\n }\n checkSync() {\n if (typeof _hmacSha256Sync !== 'function')\n throw new ShaError('hmacSha256Sync needs to be set');\n }\n incr() {\n if (this.counter >= 1000)\n throw new Error('Tried 1,000 k values for sign(), all were invalid');\n this.counter += 1;\n }\n async reseed(seed = new Uint8Array()) {\n this.k = await this.hmac(this.v, Uint8Array.from([0x00]), seed);\n this.v = await this.hmac(this.v);\n if (seed.length === 0)\n return;\n this.k = await this.hmac(this.v, Uint8Array.from([0x01]), seed);\n this.v = await this.hmac(this.v);\n }\n reseedSync(seed = new Uint8Array()) {\n this.checkSync();\n this.k = this.hmacSync(this.v, Uint8Array.from([0x00]), seed);\n this.v = this.hmacSync(this.v);\n if (seed.length === 0)\n return;\n this.k = this.hmacSync(this.v, Uint8Array.from([0x01]), seed);\n this.v = this.hmacSync(this.v);\n }\n async generate() {\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = await this.hmac(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n generateSync() {\n this.checkSync();\n this.incr();\n let len = 0;\n const out = [];\n while (len < this.qByteLen) {\n this.v = this.hmacSync(this.v);\n const sl = this.v.slice();\n out.push(sl);\n len += this.v.length;\n }\n return concatBytes(...out);\n }\n}\nfunction isWithinCurveOrder(num) {\n return _0n < num && num < CURVE.n;\n}\nfunction isValidFieldElement(num) {\n return _0n < num && num < CURVE.P;\n}\nfunction kmdToSig(kBytes, m, d, lowS = true) {\n const { n } = CURVE;\n const k = truncateHash(kBytes, true);\n if (!isWithinCurveOrder(k))\n return;\n const kinv = invert(k, n);\n const q = Point.BASE.multiply(k);\n const r = mod(q.x, n);\n if (r === _0n)\n return;\n const s = mod(kinv * mod(m + d * r, n), n);\n if (s === _0n)\n return;\n let sig = new Signature(r, s);\n let recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);\n if (lowS && sig.hasHighS()) {\n sig = sig.normalizeS();\n recovery ^= 1;\n }\n return { sig, recovery };\n}\nfunction normalizePrivateKey(key) {\n let num;\n if (typeof key === 'bigint') {\n num = key;\n }\n else if (typeof key === 'number' && Number.isSafeInteger(key) && key > 0) {\n num = BigInt(key);\n }\n else if (typeof key === 'string') {\n if (key.length !== 2 * groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = hexToNumber(key);\n }\n else if (key instanceof Uint8Array) {\n if (key.length !== groupLen)\n throw new Error('Expected 32 bytes of private key');\n num = bytesToNumber(key);\n }\n else {\n throw new TypeError('Expected valid private key');\n }\n if (!isWithinCurveOrder(num))\n throw new Error('Expected private key: 0 < key < n');\n return num;\n}\nfunction normalizePublicKey(publicKey) {\n if (publicKey instanceof Point) {\n publicKey.assertValidity();\n return publicKey;\n }\n else {\n return Point.fromHex(publicKey);\n }\n}\nfunction normalizeSignature(signature) {\n if (signature instanceof Signature) {\n signature.assertValidity();\n return signature;\n }\n try {\n return Signature.fromDER(signature);\n }\n catch (error) {\n return Signature.fromCompact(signature);\n }\n}\nexport function getPublicKey(privateKey, isCompressed = false) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n}\nexport function recoverPublicKey(msgHash, signature, recovery, isCompressed = false) {\n return Point.fromSignature(msgHash, signature, recovery).toRawBytes(isCompressed);\n}\nfunction isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === compressedLen * 2 || len === uncompressedLen * 2;\n if (item instanceof Point)\n return true;\n return false;\n}\nexport function getSharedSecret(privateA, publicB, isCompressed = false) {\n if (isProbPub(privateA))\n throw new TypeError('getSharedSecret: first arg must be private key');\n if (!isProbPub(publicB))\n throw new TypeError('getSharedSecret: second arg must be public key');\n const b = normalizePublicKey(publicB);\n b.assertValidity();\n return b.multiply(normalizePrivateKey(privateA)).toRawBytes(isCompressed);\n}\nfunction bits2int(bytes) {\n const slice = bytes.length > fieldLen ? bytes.slice(0, fieldLen) : bytes;\n return bytesToNumber(slice);\n}\nfunction bits2octets(bytes) {\n const z1 = bits2int(bytes);\n const z2 = mod(z1, CURVE.n);\n return int2octets(z2 < _0n ? z1 : z2);\n}\nfunction int2octets(num) {\n return numTo32b(num);\n}\nfunction initSigArgs(msgHash, privateKey, extraEntropy) {\n if (msgHash == null)\n throw new Error(`sign: expected valid message hash, not \"${msgHash}\"`);\n const h1 = ensureBytes(msgHash);\n const d = normalizePrivateKey(privateKey);\n const seedArgs = [int2octets(d), bits2octets(h1)];\n if (extraEntropy != null) {\n if (extraEntropy === true)\n extraEntropy = utils.randomBytes(fieldLen);\n const e = ensureBytes(extraEntropy);\n if (e.length !== fieldLen)\n throw new Error(`sign: Expected ${fieldLen} bytes of extra data`);\n seedArgs.push(e);\n }\n const seed = concatBytes(...seedArgs);\n const m = bits2int(h1);\n return { seed, m, d };\n}\nfunction finalizeSig(recSig, opts) {\n const { sig, recovery } = recSig;\n const { der, recovered } = Object.assign({ canonical: true, der: true }, opts);\n const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();\n return recovered ? [hashed, recovery] : hashed;\n}\nasync function sign(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n await drbg.reseed(seed);\n let sig;\n while (!(sig = kmdToSig(await drbg.generate(), m, d, opts.canonical)))\n await drbg.reseed();\n return finalizeSig(sig, opts);\n}\nfunction signSync(msgHash, privKey, opts = {}) {\n const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);\n const drbg = new HmacDrbg(hashLen, groupLen);\n drbg.reseedSync(seed);\n let sig;\n while (!(sig = kmdToSig(drbg.generateSync(), m, d, opts.canonical)))\n drbg.reseedSync();\n return finalizeSig(sig, opts);\n}\nexport { sign, signSync };\nconst vopts = { strict: true };\nexport function verify(signature, msgHash, publicKey, opts = vopts) {\n let sig;\n try {\n sig = normalizeSignature(signature);\n msgHash = ensureBytes(msgHash);\n }\n catch (error) {\n return false;\n }\n const { r, s } = sig;\n if (opts.strict && sig.hasHighS())\n return false;\n const h = truncateHash(msgHash);\n let P;\n try {\n P = normalizePublicKey(publicKey);\n }\n catch (error) {\n return false;\n }\n const { n } = CURVE;\n const sinv = invert(s, n);\n const u1 = mod(h * sinv, n);\n const u2 = mod(r * sinv, n);\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2);\n if (!R)\n return false;\n const v = mod(R.x, n);\n return v === r;\n}\nfunction schnorrChallengeFinalize(ch) {\n return mod(bytesToNumber(ch), CURVE.n);\n}\nclass SchnorrSignature {\n constructor(r, s) {\n this.r = r;\n this.s = s;\n this.assertValidity();\n }\n static fromHex(hex) {\n const bytes = ensureBytes(hex);\n if (bytes.length !== 64)\n throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);\n const r = bytesToNumber(bytes.subarray(0, 32));\n const s = bytesToNumber(bytes.subarray(32, 64));\n return new SchnorrSignature(r, s);\n }\n assertValidity() {\n const { r, s } = this;\n if (!isValidFieldElement(r) || !isWithinCurveOrder(s))\n throw new Error('Invalid signature');\n }\n toHex() {\n return numTo32bStr(this.r) + numTo32bStr(this.s);\n }\n toRawBytes() {\n return hexToBytes(this.toHex());\n }\n}\nfunction schnorrGetPublicKey(privateKey) {\n return Point.fromPrivateKey(privateKey).toRawX();\n}\nclass InternalSchnorrSignature {\n constructor(message, privateKey, auxRand = utils.randomBytes()) {\n if (message == null)\n throw new TypeError(`sign: Expected valid message, not \"${message}\"`);\n this.m = ensureBytes(message);\n const { x, scalar } = this.getScalar(normalizePrivateKey(privateKey));\n this.px = x;\n this.d = scalar;\n this.rand = ensureBytes(auxRand);\n if (this.rand.length !== 32)\n throw new TypeError('sign: Expected 32 bytes of aux randomness');\n }\n getScalar(priv) {\n const point = Point.fromPrivateKey(priv);\n const scalar = point.hasEvenY() ? priv : CURVE.n - priv;\n return { point, scalar, x: point.toRawX() };\n }\n initNonce(d, t0h) {\n return numTo32b(d ^ bytesToNumber(t0h));\n }\n finalizeNonce(k0h) {\n const k0 = mod(bytesToNumber(k0h), CURVE.n);\n if (k0 === _0n)\n throw new Error('sign: Creation of signature failed. k is zero');\n const { point: R, x: rx, scalar: k } = this.getScalar(k0);\n return { R, rx, k };\n }\n finalizeSig(R, k, e, d) {\n return new SchnorrSignature(R.x, mod(k + e * d, CURVE.n)).toRawBytes();\n }\n error() {\n throw new Error('sign: Invalid signature produced');\n }\n async calc() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHash;\n const t = this.initNonce(d, await tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(await tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(await tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!(await schnorrVerify(sig, m, px)))\n this.error();\n return sig;\n }\n calcSync() {\n const { m, d, px, rand } = this;\n const tag = utils.taggedHashSync;\n const t = this.initNonce(d, tag(TAGS.aux, rand));\n const { R, rx, k } = this.finalizeNonce(tag(TAGS.nonce, t, px, m));\n const e = schnorrChallengeFinalize(tag(TAGS.challenge, rx, px, m));\n const sig = this.finalizeSig(R, k, e, d);\n if (!schnorrVerifySync(sig, m, px))\n this.error();\n return sig;\n }\n}\nasync function schnorrSign(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calc();\n}\nfunction schnorrSignSync(msg, privKey, auxRand) {\n return new InternalSchnorrSignature(msg, privKey, auxRand).calcSync();\n}\nfunction initSchnorrVerify(signature, message, publicKey) {\n const raw = signature instanceof SchnorrSignature;\n const sig = raw ? signature : SchnorrSignature.fromHex(signature);\n if (raw)\n sig.assertValidity();\n return {\n ...sig,\n m: ensureBytes(message),\n P: normalizePublicKey(publicKey),\n };\n}\nfunction finalizeSchnorrVerify(r, P, s, e) {\n const R = Point.BASE.multiplyAndAddUnsafe(P, normalizePrivateKey(s), mod(-e, CURVE.n));\n if (!R || !R.hasEvenY() || R.x !== r)\n return false;\n return true;\n}\nasync function schnorrVerify(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n return false;\n }\n}\nfunction schnorrVerifySync(signature, message, publicKey) {\n try {\n const { r, s, m, P } = initSchnorrVerify(signature, message, publicKey);\n const e = schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge, numTo32b(r), P.toRawX(), m));\n return finalizeSchnorrVerify(r, P, s, e);\n }\n catch (error) {\n if (error instanceof ShaError)\n throw error;\n return false;\n }\n}\nexport const schnorr = {\n Signature: SchnorrSignature,\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n signSync: schnorrSignSync,\n verifySync: schnorrVerifySync,\n};\nPoint.BASE._setWindowSize(8);\nconst crypto = {\n node: nodeCrypto,\n web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,\n};\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n aux: 'BIP0340/aux',\n nonce: 'BIP0340/nonce',\n};\nconst TAGGED_HASH_PREFIXES = {};\nexport const utils = {\n bytesToHex,\n hexToBytes,\n concatBytes,\n mod,\n invert,\n isValidPrivateKey(privateKey) {\n try {\n normalizePrivateKey(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n _bigintTo32Bytes: numTo32b,\n _normalizePrivateKey: normalizePrivateKey,\n hashToPrivateKey: (hash) => {\n hash = ensureBytes(hash);\n const minLen = groupLen + 8;\n if (hash.length < minLen || hash.length > 1024) {\n throw new Error(`Expected valid bytes of private key as per FIPS 186`);\n }\n const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;\n return numTo32b(num);\n },\n randomBytes: (bytesLength = 32) => {\n if (crypto.web) {\n return crypto.web.getRandomValues(new Uint8Array(bytesLength));\n }\n else if (crypto.node) {\n const { randomBytes } = crypto.node;\n return Uint8Array.from(randomBytes(bytesLength));\n }\n else {\n throw new Error(\"The environment doesn't have randomBytes function\");\n }\n },\n randomPrivateKey: () => utils.hashToPrivateKey(utils.randomBytes(groupLen + 8)),\n precompute(windowSize = 8, point = Point.BASE) {\n const cached = point === Point.BASE ? point : new Point(point.x, point.y);\n cached._setWindowSize(windowSize);\n cached.multiply(_3n);\n return cached;\n },\n sha256: async (...messages) => {\n if (crypto.web) {\n const buffer = await crypto.web.subtle.digest('SHA-256', concatBytes(...messages));\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHash } = crypto.node;\n const hash = createHash('sha256');\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have sha256 function\");\n }\n },\n hmacSha256: async (key, ...messages) => {\n if (crypto.web) {\n const ckey = await crypto.web.subtle.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n const message = concatBytes(...messages);\n const buffer = await crypto.web.subtle.sign('HMAC', ckey, message);\n return new Uint8Array(buffer);\n }\n else if (crypto.node) {\n const { createHmac } = crypto.node;\n const hash = createHmac('sha256', key);\n messages.forEach((m) => hash.update(m));\n return Uint8Array.from(hash.digest());\n }\n else {\n throw new Error(\"The environment doesn't have hmac-sha256 function\");\n }\n },\n sha256Sync: undefined,\n hmacSha256Sync: undefined,\n taggedHash: async (tag, ...messages) => {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return utils.sha256(tagP, ...messages);\n },\n taggedHashSync: (tag, ...messages) => {\n if (typeof _sha256Sync !== 'function')\n throw new ShaError('sha256Sync is undefined, you need to set it');\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return _sha256Sync(tagP, ...messages);\n },\n _JacobianPoint: JacobianPoint,\n};\nObject.defineProperties(utils, {\n sha256Sync: {\n configurable: false,\n get() {\n return _sha256Sync;\n },\n set(val) {\n if (!_sha256Sync)\n _sha256Sync = val;\n },\n },\n hmacSha256Sync: {\n configurable: false,\n get() {\n return _hmacSha256Sync;\n },\n set(val) {\n if (!_hmacSha256Sync)\n _hmacSha256Sync = val;\n },\n },\n});\n","import * as secp from \"@noble/secp256k1\";\nimport { concat } from \"@waku/utils/bytes\";\nimport sha3 from \"js-sha3\";\n/**\n * ECDSA Sign a message with the given private key.\n *\n * @param message The message to sign, usually a hash.\n * @param privateKey The ECDSA private key to use to sign the message.\n *\n * @returns The signature and the recovery id concatenated.\n */\nexport async function sign(message, privateKey) {\n const [signature, recoveryId] = await secp.sign(message, privateKey, {\n recovered: true,\n der: false\n });\n return concat([signature, new Uint8Array([recoveryId])], signature.length + 1);\n}\nexport function keccak256(input) {\n return new Uint8Array(sha3.keccak256.arrayBuffer(input));\n}\nexport function compressPublicKey(publicKey) {\n if (publicKey.length === 64) {\n publicKey = concat([new Uint8Array([4]), publicKey], 65);\n }\n const point = secp.Point.fromHex(publicKey);\n return point.toRawBytes(true);\n}\n/**\n * Verify an ECDSA signature.\n */\nexport function verifySignature(signature, message, publicKey) {\n try {\n const _signature = secp.Signature.fromCompact(signature.slice(0, 64));\n return secp.verify(_signature, message, publicKey);\n }\n catch {\n return false;\n }\n}\n//# sourceMappingURL=crypto.js.map","// Maximum encoded size of an ENR\nexport const MAX_RECORD_SIZE = 300;\nexport const ERR_INVALID_ID = \"Invalid record id\";\nexport const ERR_NO_SIGNATURE = \"No valid signature found\";\n// The maximum length of byte size of a multiaddr to encode in the `multiaddr` field\n// The size is a big endian 16-bit unsigned integer\nexport const MULTIADDR_LENGTH_SIZE = 2;\n//# sourceMappingURL=constants.js.map","import { multiaddrFromFields } from \"./multiaddr_from_fields.js\";\nexport function locationMultiaddrFromEnrFields(enr, protocol) {\n switch (protocol) {\n case \"udp\":\n return (locationMultiaddrFromEnrFields(enr, \"udp4\") ||\n locationMultiaddrFromEnrFields(enr, \"udp6\"));\n case \"tcp\":\n return (locationMultiaddrFromEnrFields(enr, \"tcp4\") ||\n locationMultiaddrFromEnrFields(enr, \"tcp6\"));\n }\n const isIpv6 = protocol.endsWith(\"6\");\n const ipVal = enr.get(isIpv6 ? \"ip6\" : \"ip\");\n if (!ipVal)\n return;\n const protoName = protocol.slice(0, 3);\n let protoVal;\n switch (protoName) {\n case \"udp\":\n protoVal = isIpv6 ? enr.get(\"udp6\") : enr.get(\"udp\");\n break;\n case \"tcp\":\n protoVal = isIpv6 ? enr.get(\"tcp6\") : enr.get(\"tcp\");\n break;\n default:\n return;\n }\n if (!protoVal)\n return;\n return multiaddrFromFields(isIpv6 ? \"ip6\" : \"ip4\", protoName, ipVal, protoVal);\n}\n//# sourceMappingURL=get_multiaddr.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { convertToString } from \"@multiformats/multiaddr/convert\";\nexport function multiaddrFromFields(ipFamily, protocol, ipBytes, protocolBytes) {\n let ma = multiaddr(\"/\" + ipFamily + \"/\" + convertToString(ipFamily, ipBytes));\n ma = ma.encapsulate(multiaddr(\"/\" + protocol + \"/\" + convertToString(protocol, protocolBytes)));\n return ma;\n}\n//# sourceMappingURL=multiaddr_from_fields.js.map","import { multiaddr } from \"@multiformats/multiaddr\";\nimport { MULTIADDR_LENGTH_SIZE } from \"./constants.js\";\nexport function decodeMultiaddrs(bytes) {\n const multiaddrs = [];\n let index = 0;\n while (index < bytes.length) {\n const sizeDataView = new DataView(bytes.buffer, index, MULTIADDR_LENGTH_SIZE);\n const size = sizeDataView.getUint16(0);\n index += MULTIADDR_LENGTH_SIZE;\n const multiaddrBytes = bytes.slice(index, index + size);\n index += size;\n multiaddrs.push(multiaddr(multiaddrBytes));\n }\n return multiaddrs;\n}\nexport function encodeMultiaddrs(multiaddrs) {\n const totalLength = multiaddrs.reduce((acc, ma) => acc + MULTIADDR_LENGTH_SIZE + ma.bytes.length, 0);\n const bytes = new Uint8Array(totalLength);\n const dataView = new DataView(bytes.buffer);\n let index = 0;\n multiaddrs.forEach((multiaddr) => {\n if (multiaddr.getPeerId())\n throw new Error(\"`multiaddr` field MUST not contain peer id\");\n // Prepend the size of the next entry\n dataView.setUint16(index, multiaddr.bytes.length);\n index += MULTIADDR_LENGTH_SIZE;\n bytes.set(multiaddr.bytes, index);\n index += multiaddr.bytes.length;\n });\n return bytes;\n}\n//# sourceMappingURL=multiaddrs_codec.js.map","export function encodeWaku2(protocols) {\n let byte = 0;\n if (protocols.lightPush)\n byte += 1;\n byte = byte << 1;\n if (protocols.filter)\n byte += 1;\n byte = byte << 1;\n if (protocols.store)\n byte += 1;\n byte = byte << 1;\n if (protocols.relay)\n byte += 1;\n return byte;\n}\nexport function decodeWaku2(byte) {\n const waku2 = {\n relay: false,\n store: false,\n filter: false,\n lightPush: false\n };\n if (byte % 2)\n waku2.relay = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.store = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.filter = true;\n byte = byte >> 1;\n if (byte % 2)\n waku2.lightPush = true;\n return waku2;\n}\n//# sourceMappingURL=waku2_codec.js.map","import { convertToBytes, convertToString } from \"@multiformats/multiaddr/convert\";\nimport { decodeRelayShard } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { decodeMultiaddrs, encodeMultiaddrs } from \"./multiaddrs_codec.js\";\nimport { decodeWaku2, encodeWaku2 } from \"./waku2_codec.js\";\nexport class RawEnr extends Map {\n seq;\n signature;\n constructor(kvs = {}, seq = BigInt(1), signature) {\n super(Object.entries(kvs));\n this.seq = seq;\n this.signature = signature;\n }\n set(k, v) {\n this.signature = undefined;\n this.seq++;\n return super.set(k, v);\n }\n get id() {\n const id = this.get(\"id\");\n if (!id)\n throw new Error(\"id not found.\");\n return bytesToUtf8(id);\n }\n get publicKey() {\n switch (this.id) {\n case \"v4\":\n return this.get(\"secp256k1\");\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n get rs() {\n const rs = this.get(\"rs\");\n if (!rs)\n return undefined;\n return decodeRelayShard(rs);\n }\n get rsv() {\n const rsv = this.get(\"rsv\");\n if (!rsv)\n return undefined;\n return decodeRelayShard(rsv);\n }\n get ip() {\n return getStringValue(this, \"ip\", \"ip4\");\n }\n set ip(ip) {\n setStringValue(this, \"ip\", \"ip4\", ip);\n }\n get tcp() {\n return getNumberAsStringValue(this, \"tcp\", \"tcp\");\n }\n set tcp(port) {\n setNumberAsStringValue(this, \"tcp\", \"tcp\", port);\n }\n get udp() {\n return getNumberAsStringValue(this, \"udp\", \"udp\");\n }\n set udp(port) {\n setNumberAsStringValue(this, \"udp\", \"udp\", port);\n }\n get ip6() {\n return getStringValue(this, \"ip6\", \"ip6\");\n }\n set ip6(ip) {\n setStringValue(this, \"ip6\", \"ip6\", ip);\n }\n get tcp6() {\n return getNumberAsStringValue(this, \"tcp6\", \"tcp\");\n }\n set tcp6(port) {\n setNumberAsStringValue(this, \"tcp6\", \"tcp\", port);\n }\n get udp6() {\n return getNumberAsStringValue(this, \"udp6\", \"udp\");\n }\n set udp6(port) {\n setNumberAsStringValue(this, \"udp6\", \"udp\", port);\n }\n /**\n * Get the `multiaddrs` field from ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.getLocationMultiaddr } should be preferred.\n *\n * The multiaddresses stored in this field are expected to be location multiaddresses, ie, peer id less.\n */\n get multiaddrs() {\n const raw = this.get(\"multiaddrs\");\n if (raw)\n return decodeMultiaddrs(raw);\n return;\n }\n /**\n * Set the `multiaddrs` field on the ENR.\n *\n * This field is used to store multiaddresses that cannot be stored with the current ENR pre-defined keys.\n * These can be a multiaddresses that include encapsulation (e.g. wss) or do not use `ip4` nor `ip6` for the host\n * address (e.g. `dns4`, `dnsaddr`, etc)..\n *\n * If the peer information only contains information that can be represented with the ENR pre-defined keys\n * (ip, tcp, etc) then the usage of { @link ENR.setLocationMultiaddr } should be preferred.\n * The multiaddresses stored in this field must be location multiaddresses,\n * ie, without a peer id.\n */\n set multiaddrs(multiaddrs) {\n deleteUndefined(this, \"multiaddrs\", multiaddrs, encodeMultiaddrs);\n }\n /**\n * Get the `waku2` field from ENR.\n */\n get waku2() {\n const raw = this.get(\"waku2\");\n if (raw)\n return decodeWaku2(raw[0]);\n return;\n }\n /**\n * Set the `waku2` field on the ENR.\n */\n set waku2(waku2) {\n deleteUndefined(this, \"waku2\", waku2, (w) => new Uint8Array([encodeWaku2(w)]));\n }\n}\nfunction getStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return convertToString(proto, raw);\n}\nfunction getNumberAsStringValue(map, key, proto) {\n const raw = map.get(key);\n if (!raw)\n return;\n return Number(convertToString(proto, raw));\n}\nfunction setStringValue(map, key, proto, value) {\n deleteUndefined(map, key, value, convertToBytes.bind({}, proto));\n}\nfunction setNumberAsStringValue(map, key, proto, value) {\n setStringValue(map, key, proto, value?.toString(10));\n}\nfunction deleteUndefined(map, key, value, transform) {\n if (value !== undefined) {\n map.set(key, transform(value));\n }\n else {\n map.delete(key);\n }\n}\n//# sourceMappingURL=raw_enr.js.map","import * as secp from \"@noble/secp256k1\";\nimport { bytesToHex } from \"@waku/utils/bytes\";\nimport { keccak256 } from \"./crypto.js\";\nexport async function sign(privKey, msg) {\n return secp.sign(keccak256(msg), privKey, {\n der: false\n });\n}\nexport function nodeId(pubKey) {\n const publicKey = secp.Point.fromHex(pubKey);\n const uncompressedPubkey = publicKey.toRawBytes(false);\n return bytesToHex(keccak256(uncompressedPubkey.slice(1)));\n}\n//# sourceMappingURL=v4.js.map","import { Logger } from \"@waku/utils\";\nimport { ERR_INVALID_ID } from \"./constants.js\";\nimport { keccak256, verifySignature } from \"./crypto.js\";\nimport { locationMultiaddrFromEnrFields } from \"./get_multiaddr.js\";\nimport { createPeerIdFromPublicKey } from \"./peer_id.js\";\nimport { RawEnr } from \"./raw_enr.js\";\nimport * as v4 from \"./v4.js\";\nconst log = new Logger(\"enr\");\nexport var TransportProtocol;\n(function (TransportProtocol) {\n TransportProtocol[\"TCP\"] = \"tcp\";\n TransportProtocol[\"UDP\"] = \"udp\";\n})(TransportProtocol || (TransportProtocol = {}));\nexport var TransportProtocolPerIpVersion;\n(function (TransportProtocolPerIpVersion) {\n TransportProtocolPerIpVersion[\"TCP4\"] = \"tcp4\";\n TransportProtocolPerIpVersion[\"UDP4\"] = \"udp4\";\n TransportProtocolPerIpVersion[\"TCP6\"] = \"tcp6\";\n TransportProtocolPerIpVersion[\"UDP6\"] = \"udp6\";\n})(TransportProtocolPerIpVersion || (TransportProtocolPerIpVersion = {}));\nexport class ENR extends RawEnr {\n static RECORD_PREFIX = \"enr:\";\n peerId;\n static create(kvs = {}, seq = BigInt(1), signature) {\n const enr = new ENR(kvs, seq, signature);\n try {\n const publicKey = enr.publicKey;\n if (publicKey) {\n enr.peerId = createPeerIdFromPublicKey(publicKey);\n }\n }\n catch (e) {\n log.error(\"Could not calculate peer id for ENR\", e);\n }\n return enr;\n }\n get nodeId() {\n switch (this.id) {\n case \"v4\":\n return this.publicKey ? v4.nodeId(this.publicKey) : undefined;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n }\n getLocationMultiaddr = locationMultiaddrFromEnrFields.bind({}, this);\n get shardInfo() {\n if (this.rs && this.rsv) {\n log.warn(\"ENR contains both `rs` and `rsv` fields.\");\n }\n return this.rs || this.rsv;\n }\n setLocationMultiaddr(multiaddr) {\n const protoNames = multiaddr.protoNames();\n if (protoNames.length !== 2 &&\n protoNames[1] !== \"udp\" &&\n protoNames[1] !== \"tcp\") {\n throw new Error(\"Invalid multiaddr\");\n }\n const tuples = multiaddr.tuples();\n if (!tuples[0][1] || !tuples[1][1]) {\n throw new Error(\"Invalid multiaddr\");\n }\n // IPv4\n if (tuples[0][0] === 4) {\n this.set(\"ip\", tuples[0][1]);\n this.set(protoNames[1], tuples[1][1]);\n }\n else {\n this.set(\"ip6\", tuples[0][1]);\n this.set(protoNames[1] + \"6\", tuples[1][1]);\n }\n }\n getAllLocationMultiaddrs() {\n const multiaddrs = [];\n for (const protocol of Object.values(TransportProtocolPerIpVersion)) {\n const ma = this.getLocationMultiaddr(protocol);\n if (ma)\n multiaddrs.push(ma);\n }\n const _multiaddrs = this.multiaddrs ?? [];\n return multiaddrs.concat(_multiaddrs).map((ma) => {\n if (this.peerId) {\n return ma.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n return ma;\n });\n }\n get peerInfo() {\n const id = this.peerId;\n if (!id)\n return;\n return {\n id,\n multiaddrs: this.getAllLocationMultiaddrs()\n };\n }\n /**\n * Returns the full multiaddr from the ENR fields matching the provided\n * `protocol` parameter.\n * To return full multiaddrs from the `multiaddrs` ENR field,\n * use { @link ENR.getFullMultiaddrs }.\n *\n * @param protocol\n */\n getFullMultiaddr(protocol) {\n if (this.peerId) {\n const locationMultiaddr = this.getLocationMultiaddr(protocol);\n if (locationMultiaddr) {\n return locationMultiaddr.encapsulate(`/p2p/${this.peerId.toString()}`);\n }\n }\n return;\n }\n /**\n * Returns the full multiaddrs from the `multiaddrs` ENR field.\n */\n getFullMultiaddrs() {\n if (this.peerId && this.multiaddrs) {\n const peerId = this.peerId;\n return this.multiaddrs.map((ma) => {\n return ma.encapsulate(`/p2p/${peerId.toString()}`);\n });\n }\n return [];\n }\n verify(data, signature) {\n if (!this.get(\"id\") || this.id !== \"v4\") {\n throw new Error(ERR_INVALID_ID);\n }\n if (!this.publicKey) {\n throw new Error(\"Failed to verify ENR: No public key\");\n }\n return verifySignature(signature, keccak256(data), this.publicKey);\n }\n async sign(data, privateKey) {\n switch (this.id) {\n case \"v4\":\n this.signature = await v4.sign(privateKey, data);\n break;\n default:\n throw new Error(ERR_INVALID_ID);\n }\n return this.signature;\n }\n}\n//# sourceMappingURL=enr.js.map","import { publicKeyFromRaw } from \"@libp2p/crypto/keys\";\nimport { peerIdFromPublicKey } from \"@libp2p/peer-id\";\nexport const ERR_TYPE_NOT_IMPLEMENTED = \"Keypair type not implemented\";\nexport function createPeerIdFromPublicKey(publicKey) {\n const pubKey = publicKeyFromRaw(publicKey);\n if (pubKey.type !== \"secp256k1\") {\n throw new Error(ERR_TYPE_NOT_IMPLEMENTED);\n }\n return peerIdFromPublicKey(pubKey);\n}\n//# sourceMappingURL=peer_id.js.map","\"use strict\";\nlet _permanentCensorErrors = false;\nlet _censorErrors = false;\nconst LogLevels = { debug: 1, \"default\": 2, info: 2, warning: 3, error: 4, off: 5 };\nlet _logLevel = LogLevels[\"default\"];\nimport { version } from \"./_version\";\nlet _globalLogger = null;\nfunction _checkNormalize() {\n try {\n const missing = [];\n // Make sure all forms of normalization are supported\n [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].forEach((form) => {\n try {\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad normalize\");\n }\n ;\n }\n catch (error) {\n missing.push(form);\n }\n });\n if (missing.length) {\n throw new Error(\"missing \" + missing.join(\", \"));\n }\n if (String.fromCharCode(0xe9).normalize(\"NFD\") !== String.fromCharCode(0x65, 0x0301)) {\n throw new Error(\"broken implementation\");\n }\n }\n catch (error) {\n return error.message;\n }\n return null;\n}\nconst _normalizeError = _checkNormalize();\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[\"DEBUG\"] = \"DEBUG\";\n LogLevel[\"INFO\"] = \"INFO\";\n LogLevel[\"WARNING\"] = \"WARNING\";\n LogLevel[\"ERROR\"] = \"ERROR\";\n LogLevel[\"OFF\"] = \"OFF\";\n})(LogLevel || (LogLevel = {}));\nexport var ErrorCode;\n(function (ErrorCode) {\n ///////////////////\n // Generic Errors\n // Unknown Error\n ErrorCode[\"UNKNOWN_ERROR\"] = \"UNKNOWN_ERROR\";\n // Not Implemented\n ErrorCode[\"NOT_IMPLEMENTED\"] = \"NOT_IMPLEMENTED\";\n // Unsupported Operation\n // - operation\n ErrorCode[\"UNSUPPORTED_OPERATION\"] = \"UNSUPPORTED_OPERATION\";\n // Network Error (i.e. Ethereum Network, such as an invalid chain ID)\n // - event (\"noNetwork\" is not re-thrown in provider.ready; otherwise thrown)\n ErrorCode[\"NETWORK_ERROR\"] = \"NETWORK_ERROR\";\n // Some sort of bad response from the server\n ErrorCode[\"SERVER_ERROR\"] = \"SERVER_ERROR\";\n // Timeout\n ErrorCode[\"TIMEOUT\"] = \"TIMEOUT\";\n ///////////////////\n // Operational Errors\n // Buffer Overrun\n ErrorCode[\"BUFFER_OVERRUN\"] = \"BUFFER_OVERRUN\";\n // Numeric Fault\n // - operation: the operation being executed\n // - fault: the reason this faulted\n ErrorCode[\"NUMERIC_FAULT\"] = \"NUMERIC_FAULT\";\n ///////////////////\n // Argument Errors\n // Missing new operator to an object\n // - name: The name of the class\n ErrorCode[\"MISSING_NEW\"] = \"MISSING_NEW\";\n // Invalid argument (e.g. value is incompatible with type) to a function:\n // - argument: The argument name that was invalid\n // - value: The value of the argument\n ErrorCode[\"INVALID_ARGUMENT\"] = \"INVALID_ARGUMENT\";\n // Missing argument to a function:\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"MISSING_ARGUMENT\"] = \"MISSING_ARGUMENT\";\n // Too many arguments\n // - count: The number of arguments received\n // - expectedCount: The number of arguments expected\n ErrorCode[\"UNEXPECTED_ARGUMENT\"] = \"UNEXPECTED_ARGUMENT\";\n ///////////////////\n // Blockchain Errors\n // Call exception\n // - transaction: the transaction\n // - address?: the contract address\n // - args?: The arguments passed into the function\n // - method?: The Solidity method signature\n // - errorSignature?: The EIP848 error signature\n // - errorArgs?: The EIP848 error parameters\n // - reason: The reason (only for EIP848 \"Error(string)\")\n ErrorCode[\"CALL_EXCEPTION\"] = \"CALL_EXCEPTION\";\n // Insufficient funds (< value + gasLimit * gasPrice)\n // - transaction: the transaction attempted\n ErrorCode[\"INSUFFICIENT_FUNDS\"] = \"INSUFFICIENT_FUNDS\";\n // Nonce has already been used\n // - transaction: the transaction attempted\n ErrorCode[\"NONCE_EXPIRED\"] = \"NONCE_EXPIRED\";\n // The replacement fee for the transaction is too low\n // - transaction: the transaction attempted\n ErrorCode[\"REPLACEMENT_UNDERPRICED\"] = \"REPLACEMENT_UNDERPRICED\";\n // The gas limit could not be estimated\n // - transaction: the transaction passed to estimateGas\n ErrorCode[\"UNPREDICTABLE_GAS_LIMIT\"] = \"UNPREDICTABLE_GAS_LIMIT\";\n // The transaction was replaced by one with a higher gas price\n // - reason: \"cancelled\", \"replaced\" or \"repriced\"\n // - cancelled: true if reason == \"cancelled\" or reason == \"replaced\")\n // - hash: original transaction hash\n // - replacement: the full TransactionsResponse for the replacement\n // - receipt: the receipt of the replacement\n ErrorCode[\"TRANSACTION_REPLACED\"] = \"TRANSACTION_REPLACED\";\n ///////////////////\n // Interaction Errors\n // The user rejected the action, such as signing a message or sending\n // a transaction\n ErrorCode[\"ACTION_REJECTED\"] = \"ACTION_REJECTED\";\n})(ErrorCode || (ErrorCode = {}));\n;\nconst HEX = \"0123456789abcdef\";\nexport class Logger {\n constructor(version) {\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n value: version,\n writable: false\n });\n }\n _log(logLevel, args) {\n const level = logLevel.toLowerCase();\n if (LogLevels[level] == null) {\n this.throwArgumentError(\"invalid log level name\", \"logLevel\", logLevel);\n }\n if (_logLevel > LogLevels[level]) {\n return;\n }\n console.log.apply(console, args);\n }\n debug(...args) {\n this._log(Logger.levels.DEBUG, args);\n }\n info(...args) {\n this._log(Logger.levels.INFO, args);\n }\n warn(...args) {\n this._log(Logger.levels.WARNING, args);\n }\n makeError(message, code, params) {\n // Errors are being censored\n if (_censorErrors) {\n return this.makeError(\"censored error\", code, {});\n }\n if (!code) {\n code = Logger.errors.UNKNOWN_ERROR;\n }\n if (!params) {\n params = {};\n }\n const messageDetails = [];\n Object.keys(params).forEach((key) => {\n const value = params[key];\n try {\n if (value instanceof Uint8Array) {\n let hex = \"\";\n for (let i = 0; i < value.length; i++) {\n hex += HEX[value[i] >> 4];\n hex += HEX[value[i] & 0x0f];\n }\n messageDetails.push(key + \"=Uint8Array(0x\" + hex + \")\");\n }\n else {\n messageDetails.push(key + \"=\" + JSON.stringify(value));\n }\n }\n catch (error) {\n messageDetails.push(key + \"=\" + JSON.stringify(params[key].toString()));\n }\n });\n messageDetails.push(`code=${code}`);\n messageDetails.push(`version=${this.version}`);\n const reason = message;\n let url = \"\";\n switch (code) {\n case ErrorCode.NUMERIC_FAULT: {\n url = \"NUMERIC_FAULT\";\n const fault = message;\n switch (fault) {\n case \"overflow\":\n case \"underflow\":\n case \"division-by-zero\":\n url += \"-\" + fault;\n break;\n case \"negative-power\":\n case \"negative-width\":\n url += \"-unsupported\";\n break;\n case \"unbound-bitwise-result\":\n url += \"-unbound-result\";\n break;\n }\n break;\n }\n case ErrorCode.CALL_EXCEPTION:\n case ErrorCode.INSUFFICIENT_FUNDS:\n case ErrorCode.MISSING_NEW:\n case ErrorCode.NONCE_EXPIRED:\n case ErrorCode.REPLACEMENT_UNDERPRICED:\n case ErrorCode.TRANSACTION_REPLACED:\n case ErrorCode.UNPREDICTABLE_GAS_LIMIT:\n url = code;\n break;\n }\n if (url) {\n message += \" [ See: https:/\\/links.ethers.org/v5-errors-\" + url + \" ]\";\n }\n if (messageDetails.length) {\n message += \" (\" + messageDetails.join(\", \") + \")\";\n }\n // @TODO: Any??\n const error = new Error(message);\n error.reason = reason;\n error.code = code;\n Object.keys(params).forEach(function (key) {\n error[key] = params[key];\n });\n return error;\n }\n throwError(message, code, params) {\n throw this.makeError(message, code, params);\n }\n throwArgumentError(message, name, value) {\n return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {\n argument: name,\n value: value\n });\n }\n assert(condition, message, code, params) {\n if (!!condition) {\n return;\n }\n this.throwError(message, code, params);\n }\n assertArgument(condition, message, name, value) {\n if (!!condition) {\n return;\n }\n this.throwArgumentError(message, name, value);\n }\n checkNormalize(message) {\n if (message == null) {\n message = \"platform missing String.prototype.normalize\";\n }\n if (_normalizeError) {\n this.throwError(\"platform missing String.prototype.normalize\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"String.prototype.normalize\", form: _normalizeError\n });\n }\n }\n checkSafeUint53(value, message) {\n if (typeof (value) !== \"number\") {\n return;\n }\n if (message == null) {\n message = \"value not safe\";\n }\n if (value < 0 || value >= 0x1fffffffffffff) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"out-of-safe-range\",\n value: value\n });\n }\n if (value % 1) {\n this.throwError(message, Logger.errors.NUMERIC_FAULT, {\n operation: \"checkSafeInteger\",\n fault: \"non-integer\",\n value: value\n });\n }\n }\n checkArgumentCount(count, expectedCount, message) {\n if (message) {\n message = \": \" + message;\n }\n else {\n message = \"\";\n }\n if (count < expectedCount) {\n this.throwError(\"missing argument\" + message, Logger.errors.MISSING_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n if (count > expectedCount) {\n this.throwError(\"too many arguments\" + message, Logger.errors.UNEXPECTED_ARGUMENT, {\n count: count,\n expectedCount: expectedCount\n });\n }\n }\n checkNew(target, kind) {\n if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n checkAbstract(target, kind) {\n if (target === kind) {\n this.throwError(\"cannot instantiate abstract class \" + JSON.stringify(kind.name) + \" directly; use a sub-class\", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: \"new\" });\n }\n else if (target === Object || target == null) {\n this.throwError(\"missing new\", Logger.errors.MISSING_NEW, { name: kind.name });\n }\n }\n static globalLogger() {\n if (!_globalLogger) {\n _globalLogger = new Logger(version);\n }\n return _globalLogger;\n }\n static setCensorship(censorship, permanent) {\n if (!censorship && permanent) {\n this.globalLogger().throwError(\"cannot permanently disable censorship\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n if (_permanentCensorErrors) {\n if (!censorship) {\n return;\n }\n this.globalLogger().throwError(\"error censorship permanent\", Logger.errors.UNSUPPORTED_OPERATION, {\n operation: \"setCensorship\"\n });\n }\n _censorErrors = !!censorship;\n _permanentCensorErrors = !!permanent;\n }\n static setLogLevel(logLevel) {\n const level = LogLevels[logLevel.toLowerCase()];\n if (level == null) {\n Logger.globalLogger().warn(\"invalid log level - \" + logLevel);\n return;\n }\n _logLevel = level;\n }\n static from(version) {\n return new Logger(version);\n }\n}\nLogger.errors = ErrorCode;\nLogger.levels = LogLevel;\n//# sourceMappingURL=index.js.map","export const version = \"logger/5.7.0\";\n//# sourceMappingURL=_version.js.map","export const version = \"bytes/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\n///////////////////////////////\nfunction isHexable(value) {\n return !!(value.toHexString);\n}\nfunction addSlice(array) {\n if (array.slice) {\n return array;\n }\n array.slice = function () {\n const args = Array.prototype.slice.call(arguments);\n return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args)));\n };\n return array;\n}\nexport function isBytesLike(value) {\n return ((isHexString(value) && !(value.length % 2)) || isBytes(value));\n}\nfunction isInteger(value) {\n return (typeof (value) === \"number\" && value == value && (value % 1) === 0);\n}\nexport function isBytes(value) {\n if (value == null) {\n return false;\n }\n if (value.constructor === Uint8Array) {\n return true;\n }\n if (typeof (value) === \"string\") {\n return false;\n }\n if (!isInteger(value.length) || value.length < 0) {\n return false;\n }\n for (let i = 0; i < value.length; i++) {\n const v = value[i];\n if (!isInteger(v) || v < 0 || v >= 256) {\n return false;\n }\n }\n return true;\n}\nexport function arrayify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid arrayify value\");\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value = parseInt(String(value / 256));\n }\n if (result.length === 0) {\n result.push(0);\n }\n return addSlice(new Uint8Array(result));\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n value = value.toHexString();\n }\n if (isHexString(value)) {\n let hex = value.substring(2);\n if (hex.length % 2) {\n if (options.hexPad === \"left\") {\n hex = \"0\" + hex;\n }\n else if (options.hexPad === \"right\") {\n hex += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n const result = [];\n for (let i = 0; i < hex.length; i += 2) {\n result.push(parseInt(hex.substring(i, i + 2), 16));\n }\n return addSlice(new Uint8Array(result));\n }\n if (isBytes(value)) {\n return addSlice(new Uint8Array(value));\n }\n return logger.throwArgumentError(\"invalid arrayify value\", \"value\", value);\n}\nexport function concat(items) {\n const objects = items.map(item => arrayify(item));\n const length = objects.reduce((accum, item) => (accum + item.length), 0);\n const result = new Uint8Array(length);\n objects.reduce((offset, object) => {\n result.set(object, offset);\n return offset + object.length;\n }, 0);\n return addSlice(result);\n}\nexport function stripZeros(value) {\n let result = arrayify(value);\n if (result.length === 0) {\n return result;\n }\n // Find the first non-zero entry\n let start = 0;\n while (start < result.length && result[start] === 0) {\n start++;\n }\n // If we started with zeros, strip them\n if (start) {\n result = result.slice(start);\n }\n return result;\n}\nexport function zeroPad(value, length) {\n value = arrayify(value);\n if (value.length > length) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[0]);\n }\n const result = new Uint8Array(length);\n result.set(value, length - value.length);\n return addSlice(result);\n}\nexport function isHexString(value, length) {\n if (typeof (value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false;\n }\n if (length && value.length !== 2 + 2 * length) {\n return false;\n }\n return true;\n}\nconst HexCharacters = \"0123456789abcdef\";\nexport function hexlify(value, options) {\n if (!options) {\n options = {};\n }\n if (typeof (value) === \"number\") {\n logger.checkSafeUint53(value, \"invalid hexlify value\");\n let hex = \"\";\n while (value) {\n hex = HexCharacters[value & 0xf] + hex;\n value = Math.floor(value / 16);\n }\n if (hex.length) {\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n return \"0x\" + hex;\n }\n return \"0x00\";\n }\n if (typeof (value) === \"bigint\") {\n value = value.toString(16);\n if (value.length % 2) {\n return (\"0x0\" + value);\n }\n return \"0x\" + value;\n }\n if (options.allowMissingPrefix && typeof (value) === \"string\" && value.substring(0, 2) !== \"0x\") {\n value = \"0x\" + value;\n }\n if (isHexable(value)) {\n return value.toHexString();\n }\n if (isHexString(value)) {\n if (value.length % 2) {\n if (options.hexPad === \"left\") {\n value = \"0x0\" + value.substring(2);\n }\n else if (options.hexPad === \"right\") {\n value += \"0\";\n }\n else {\n logger.throwArgumentError(\"hex data is odd-length\", \"value\", value);\n }\n }\n return value.toLowerCase();\n }\n if (isBytes(value)) {\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n let v = value[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n }\n return logger.throwArgumentError(\"invalid hexlify value\", \"value\", value);\n}\n/*\nfunction unoddify(value: BytesLike | Hexable | number): BytesLike | Hexable | number {\n if (typeof(value) === \"string\" && value.length % 2 && value.substring(0, 2) === \"0x\") {\n return \"0x0\" + value.substring(2);\n }\n return value;\n}\n*/\nexport function hexDataLength(data) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n return null;\n }\n return (data.length - 2) / 2;\n}\nexport function hexDataSlice(data, offset, endOffset) {\n if (typeof (data) !== \"string\") {\n data = hexlify(data);\n }\n else if (!isHexString(data) || (data.length % 2)) {\n logger.throwArgumentError(\"invalid hexData\", \"value\", data);\n }\n offset = 2 + 2 * offset;\n if (endOffset != null) {\n return \"0x\" + data.substring(offset, 2 + 2 * endOffset);\n }\n return \"0x\" + data.substring(offset);\n}\nexport function hexConcat(items) {\n let result = \"0x\";\n items.forEach((item) => {\n result += hexlify(item).substring(2);\n });\n return result;\n}\nexport function hexValue(value) {\n const trimmed = hexStripZeros(hexlify(value, { hexPad: \"left\" }));\n if (trimmed === \"0x\") {\n return \"0x0\";\n }\n return trimmed;\n}\nexport function hexStripZeros(value) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n value = value.substring(2);\n let offset = 0;\n while (offset < value.length && value[offset] === \"0\") {\n offset++;\n }\n return \"0x\" + value.substring(offset);\n}\nexport function hexZeroPad(value, length) {\n if (typeof (value) !== \"string\") {\n value = hexlify(value);\n }\n else if (!isHexString(value)) {\n logger.throwArgumentError(\"invalid hex string\", \"value\", value);\n }\n if (value.length > 2 * length + 2) {\n logger.throwArgumentError(\"value out of range\", \"value\", arguments[1]);\n }\n while (value.length < 2 * length + 2) {\n value = \"0x0\" + value.substring(2);\n }\n return value;\n}\nexport function splitSignature(signature) {\n const result = {\n r: \"0x\",\n s: \"0x\",\n _vs: \"0x\",\n recoveryParam: 0,\n v: 0,\n yParityAndS: \"0x\",\n compact: \"0x\"\n };\n if (isBytesLike(signature)) {\n let bytes = arrayify(signature);\n // Get the r, s and v\n if (bytes.length === 64) {\n // EIP-2098; pull the v from the top bit of s and clear it\n result.v = 27 + (bytes[32] >> 7);\n bytes[32] &= 0x7f;\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n }\n else if (bytes.length === 65) {\n result.r = hexlify(bytes.slice(0, 32));\n result.s = hexlify(bytes.slice(32, 64));\n result.v = bytes[64];\n }\n else {\n logger.throwArgumentError(\"invalid signature string\", \"signature\", signature);\n }\n // Allow a recid to be used as the v\n if (result.v < 27) {\n if (result.v === 0 || result.v === 1) {\n result.v += 27;\n }\n else {\n logger.throwArgumentError(\"signature invalid v byte\", \"signature\", signature);\n }\n }\n // Compute recoveryParam from v\n result.recoveryParam = 1 - (result.v % 2);\n // Compute _vs from recoveryParam and s\n if (result.recoveryParam) {\n bytes[32] |= 0x80;\n }\n result._vs = hexlify(bytes.slice(32, 64));\n }\n else {\n result.r = signature.r;\n result.s = signature.s;\n result.v = signature.v;\n result.recoveryParam = signature.recoveryParam;\n result._vs = signature._vs;\n // If the _vs is available, use it to populate missing s, v and recoveryParam\n // and verify non-missing s, v and recoveryParam\n if (result._vs != null) {\n const vs = zeroPad(arrayify(result._vs), 32);\n result._vs = hexlify(vs);\n // Set or check the recid\n const recoveryParam = ((vs[0] >= 128) ? 1 : 0);\n if (result.recoveryParam == null) {\n result.recoveryParam = recoveryParam;\n }\n else if (result.recoveryParam !== recoveryParam) {\n logger.throwArgumentError(\"signature recoveryParam mismatch _vs\", \"signature\", signature);\n }\n // Set or check the s\n vs[0] &= 0x7f;\n const s = hexlify(vs);\n if (result.s == null) {\n result.s = s;\n }\n else if (result.s !== s) {\n logger.throwArgumentError(\"signature v mismatch _vs\", \"signature\", signature);\n }\n }\n // Use recid and v to populate each other\n if (result.recoveryParam == null) {\n if (result.v == null) {\n logger.throwArgumentError(\"signature missing v and recoveryParam\", \"signature\", signature);\n }\n else if (result.v === 0 || result.v === 1) {\n result.recoveryParam = result.v;\n }\n else {\n result.recoveryParam = 1 - (result.v % 2);\n }\n }\n else {\n if (result.v == null) {\n result.v = 27 + result.recoveryParam;\n }\n else {\n const recId = (result.v === 0 || result.v === 1) ? result.v : (1 - (result.v % 2));\n if (result.recoveryParam !== recId) {\n logger.throwArgumentError(\"signature recoveryParam mismatch v\", \"signature\", signature);\n }\n }\n }\n if (result.r == null || !isHexString(result.r)) {\n logger.throwArgumentError(\"signature missing or invalid r\", \"signature\", signature);\n }\n else {\n result.r = hexZeroPad(result.r, 32);\n }\n if (result.s == null || !isHexString(result.s)) {\n logger.throwArgumentError(\"signature missing or invalid s\", \"signature\", signature);\n }\n else {\n result.s = hexZeroPad(result.s, 32);\n }\n const vs = arrayify(result.s);\n if (vs[0] >= 128) {\n logger.throwArgumentError(\"signature s out of range\", \"signature\", signature);\n }\n if (result.recoveryParam) {\n vs[0] |= 0x80;\n }\n const _vs = hexlify(vs);\n if (result._vs) {\n if (!isHexString(result._vs)) {\n logger.throwArgumentError(\"signature invalid _vs\", \"signature\", signature);\n }\n result._vs = hexZeroPad(result._vs, 32);\n }\n // Set or check the _vs\n if (result._vs == null) {\n result._vs = _vs;\n }\n else if (result._vs !== _vs) {\n logger.throwArgumentError(\"signature _vs mismatch v and s\", \"signature\", signature);\n }\n }\n result.yParityAndS = result._vs;\n result.compact = result.r + result.yParityAndS.substring(2);\n return result;\n}\nexport function joinSignature(signature) {\n signature = splitSignature(signature);\n return hexlify(concat([\n signature.r,\n signature.s,\n (signature.recoveryParam ? \"0x1c\" : \"0x1b\")\n ]));\n}\n//# sourceMappingURL=index.js.map","export const version = \"rlp/5.7.0\";\n//# sourceMappingURL=_version.js.map","\"use strict\";\n//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { arrayify, hexlify, isBytesLike } from \"@ethersproject/bytes\";\nimport { Logger } from \"@ethersproject/logger\";\nimport { version } from \"./_version\";\nconst logger = new Logger(version);\nfunction arrayifyInteger(value) {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\nfunction unarrayifyInteger(data, offset, length) {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\nfunction _encode(object) {\n if (Array.isArray(object)) {\n let payload = [];\n object.forEach(function (child) {\n payload = payload.concat(_encode(child));\n });\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length);\n return payload;\n }\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n return length.concat(payload);\n }\n if (!isBytesLike(object)) {\n logger.throwArgumentError(\"RLP object must be BytesLike\", \"object\", object);\n }\n const data = Array.prototype.slice.call(arrayify(object));\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n }\n else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n return length.concat(data);\n}\nexport function encode(object) {\n return hexlify(_encode(object));\n}\nfunction _decodeChildren(data, offset, childOffset, length) {\n const result = [];\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n result.push(decoded.result);\n childOffset += decoded.consumed;\n if (childOffset > offset + 1 + length) {\n logger.throwError(\"child data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n }\n return { consumed: (1 + length), result: result };\n}\n// returns { consumed: number, result: Object }\nfunction _decode(data, offset) {\n if (data.length === 0) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data short segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data long segment too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n }\n else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n return _decodeChildren(data, offset, offset + 1, length);\n }\n else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n if (offset + 1 + lengthLength > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n if (offset + 1 + lengthLength + length > data.length) {\n logger.throwError(\"data array too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result };\n }\n else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n if (offset + 1 + length > data.length) {\n logger.throwError(\"data too short\", Logger.errors.BUFFER_OVERRUN, {});\n }\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result };\n }\n return { consumed: 1, result: hexlify(data[offset]) };\n}\nexport function decode(data) {\n const bytes = arrayify(data);\n const decoded = _decode(bytes, 0);\n if (decoded.consumed !== bytes.length) {\n logger.throwArgumentError(\"invalid rlp data\", \"data\", data);\n }\n return decoded.result;\n}\n//# sourceMappingURL=index.js.map","import * as RLP from \"@ethersproject/rlp\";\nimport { Logger } from \"@waku/utils\";\nimport { bytesToHex, bytesToUtf8, hexToBytes } from \"@waku/utils/bytes\";\nimport { fromString } from \"uint8arrays/from-string\";\nimport { ENR } from \"./enr.js\";\nconst log = new Logger(\"enr:decoder\");\nexport class EnrDecoder {\n static fromString(encoded) {\n if (!encoded.startsWith(ENR.RECORD_PREFIX)) {\n throw new Error(`\"string encoded ENR must start with '${ENR.RECORD_PREFIX}'`);\n }\n return EnrDecoder.fromRLP(fromString(encoded.slice(4), \"base64url\"));\n }\n static fromRLP(encoded) {\n const decoded = RLP.decode(encoded).map(hexToBytes);\n return fromValues(decoded);\n }\n}\nasync function fromValues(values) {\n const { signature, seq, kvs } = checkValues(values);\n const obj = {};\n for (let i = 0; i < kvs.length; i += 2) {\n try {\n obj[bytesToUtf8(kvs[i])] = kvs[i + 1];\n }\n catch (e) {\n log.error(\"Failed to decode ENR key to UTF-8, skipping it\", kvs[i], e);\n }\n }\n const _seq = decodeSeq(seq);\n const enr = ENR.create(obj, _seq, signature);\n checkSignature(seq, kvs, enr, signature);\n return enr;\n}\nfunction decodeSeq(seq) {\n // If seq is an empty array, translate as value 0\n if (!seq.length)\n return BigInt(0);\n return BigInt(\"0x\" + bytesToHex(seq));\n}\nfunction checkValues(values) {\n if (!Array.isArray(values)) {\n throw new Error(\"Decoded ENR must be an array\");\n }\n if (values.length % 2 !== 0) {\n throw new Error(\"Decoded ENR must have an even number of elements\");\n }\n const [signature, seq, ...kvs] = values;\n if (!signature || Array.isArray(signature)) {\n throw new Error(\"Decoded ENR invalid signature: must be a byte array\");\n }\n if (!seq || Array.isArray(seq)) {\n throw new Error(\"Decoded ENR invalid sequence number: must be a byte array\");\n }\n return { signature, seq, kvs };\n}\nfunction checkSignature(seq, kvs, enr, signature) {\n const rlpEncodedBytes = hexToBytes(RLP.encode([seq, ...kvs]));\n if (!enr.verify(rlpEncodedBytes, signature)) {\n throw new Error(\"Unable to verify ENR signature\");\n }\n}\n//# sourceMappingURL=decoder.js.map","const v4Regex = /^(\\d{1,3}\\.){3,3}\\d{1,3}$/\nconst v4Size = 4\nconst v6Regex = /^(::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i\nconst v6Size = 16\n\nexport const v4 = {\n name: 'v4',\n size: v4Size,\n isFormat: ip => v4Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n buff = buff || new Uint8Array(offset + v4Size)\n const max = ip.length\n let n = 0\n for (let i = 0; i < max;) {\n const c = ip.charCodeAt(i++)\n if (c === 46) { // \".\"\n buff[offset++] = n\n n = 0\n } else {\n n = n * 10 + (c - 48)\n }\n }\n buff[offset] = n\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`\n }\n}\n\nexport const v6 = {\n name: 'v6',\n size: v6Size,\n isFormat: ip => ip.length > 0 && v6Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n let end = offset + v6Size\n let fill = -1\n let hexN = 0\n let decN = 0\n let prevColon = true\n let useDec = false\n buff = buff || new Uint8Array(offset + v6Size)\n // Note: This algorithm needs to check if the offset\n // could exceed the buffer boundaries as it supports\n // non-standard compliant encodings that may go beyond\n // the boundary limits. if (offset < end) checks should\n // not be necessary...\n for (let i = 0; i < ip.length; i++) {\n let c = ip.charCodeAt(i)\n if (c === 58) { // :\n if (prevColon) {\n if (fill !== -1) {\n // Not Standard! (standard doesn't allow multiple ::)\n // We need to treat\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (offset < end) {\n // :: in the middle\n fill = offset\n }\n } else {\n // : ends the previous number\n if (useDec === true) {\n // Non-standard! (ipv4 should be at end only)\n // A ipv4 address should not be found anywhere else but at\n // the end. This codec also support putting characters\n // after the ipv4 address..\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n hexN = 0\n decN = 0\n }\n prevColon = true\n useDec = false\n } else if (c === 46) { // . indicates IPV4 notation\n if (offset < end) buff[offset] = decN\n offset++\n decN = 0\n hexN = 0\n prevColon = false\n useDec = true\n } else {\n prevColon = false\n if (c >= 97) {\n c -= 87 // a-f ... 97~102 -87 => 10~15\n } else if (c >= 65) {\n c -= 55 // A-F ... 65~70 -55 => 10~15\n } else {\n c -= 48 // 0-9 ... starting from charCode 48\n decN = decN * 10 + c\n }\n // We don't know yet if its a dec or hex number\n hexN = (hexN << 4) + c\n }\n }\n if (prevColon === false) {\n // Commiting last number\n if (useDec === true) {\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n } else if (fill === 0) {\n // Not Standard! (standard doesn't allow multiple ::)\n // This means that a : was found at the start AND end which means the\n // end needs to be treated as 0 entry...\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (fill !== -1) {\n // Non-standard! (standard doens't allow multiple ::)\n // Here we find that there has been a :: somewhere in the middle\n // and the end. To treat the end with priority we need to move all\n // written data two bytes to the right.\n offset += 2\n for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) {\n buff[i] = buff[i - 2]\n }\n buff[fill] = 0\n buff[fill + 1] = 0\n fill = offset\n }\n if (fill !== offset && fill !== -1) {\n // Move the written numbers to the end while filling the everything\n // \"fill\" to the bytes with zeros.\n if (offset > end - 2) {\n // Non Standard support, when the cursor exceeds bounds.\n offset = end - 2\n }\n while (end > fill) {\n buff[--end] = offset < end && offset > fill ? buff[--offset] : 0\n }\n } else {\n // Fill the rest with zeros\n while (offset < end) {\n buff[offset++] = 0\n }\n }\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n let result = ''\n for (let i = 0; i < v6Size; i += 2) {\n if (i !== 0) {\n result += ':'\n }\n result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16)\n }\n return result\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n}\n\nexport const name = 'ip'\nexport function sizeOf (ip) {\n if (v4.isFormat(ip)) return v4.size\n if (v6.isFormat(ip)) return v6.size\n throw Error(`Invalid ip address: ${ip}`)\n}\n\nexport function familyOf (string) {\n return sizeOf(string) === v4.size ? 1 : 2\n}\n\nexport function encode (ip, buff, offset) {\n offset = ~~offset\n const size = sizeOf(ip)\n if (typeof buff === 'function') {\n buff = buff(offset + size)\n }\n if (size === v4.size) {\n return v4.encode(ip, buff, offset)\n }\n return v6.encode(ip, buff, offset)\n}\n\nexport function decode (buff, offset, length) {\n offset = ~~offset\n length = length || (buff.length - offset)\n if (length === v4.size) {\n return v4.decode(buff, offset, length)\n }\n if (length === v6.size) {\n return v6.decode(buff, offset, length)\n }\n throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`)\n}\n","export function toString (type) {\n switch (type) {\n case 1: return 'A'\n case 10: return 'NULL'\n case 28: return 'AAAA'\n case 18: return 'AFSDB'\n case 42: return 'APL'\n case 257: return 'CAA'\n case 60: return 'CDNSKEY'\n case 59: return 'CDS'\n case 37: return 'CERT'\n case 5: return 'CNAME'\n case 49: return 'DHCID'\n case 32769: return 'DLV'\n case 39: return 'DNAME'\n case 48: return 'DNSKEY'\n case 43: return 'DS'\n case 55: return 'HIP'\n case 13: return 'HINFO'\n case 45: return 'IPSECKEY'\n case 25: return 'KEY'\n case 36: return 'KX'\n case 29: return 'LOC'\n case 15: return 'MX'\n case 35: return 'NAPTR'\n case 2: return 'NS'\n case 47: return 'NSEC'\n case 50: return 'NSEC3'\n case 51: return 'NSEC3PARAM'\n case 12: return 'PTR'\n case 46: return 'RRSIG'\n case 17: return 'RP'\n case 24: return 'SIG'\n case 6: return 'SOA'\n case 99: return 'SPF'\n case 33: return 'SRV'\n case 44: return 'SSHFP'\n case 32768: return 'TA'\n case 249: return 'TKEY'\n case 52: return 'TLSA'\n case 250: return 'TSIG'\n case 16: return 'TXT'\n case 252: return 'AXFR'\n case 251: return 'IXFR'\n case 41: return 'OPT'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + type\n}\n\nexport function toType (name) {\n switch (name.toUpperCase()) {\n case 'A': return 1\n case 'NULL': return 10\n case 'AAAA': return 28\n case 'AFSDB': return 18\n case 'APL': return 42\n case 'CAA': return 257\n case 'CDNSKEY': return 60\n case 'CDS': return 59\n case 'CERT': return 37\n case 'CNAME': return 5\n case 'DHCID': return 49\n case 'DLV': return 32769\n case 'DNAME': return 39\n case 'DNSKEY': return 48\n case 'DS': return 43\n case 'HIP': return 55\n case 'HINFO': return 13\n case 'IPSECKEY': return 45\n case 'KEY': return 25\n case 'KX': return 36\n case 'LOC': return 29\n case 'MX': return 15\n case 'NAPTR': return 35\n case 'NS': return 2\n case 'NSEC': return 47\n case 'NSEC3': return 50\n case 'NSEC3PARAM': return 51\n case 'PTR': return 12\n case 'RRSIG': return 46\n case 'RP': return 17\n case 'SIG': return 24\n case 'SOA': return 6\n case 'SPF': return 99\n case 'SRV': return 33\n case 'SSHFP': return 44\n case 'TA': return 32768\n case 'TKEY': return 249\n case 'TLSA': return 52\n case 'TSIG': return 250\n case 'TXT': return 16\n case 'AXFR': return 252\n case 'IXFR': return 251\n case 'OPT': return 41\n case 'ANY': return 255\n case '*': return 255\n }\n if (name.toUpperCase().startsWith('UNKNOWN_')) return parseInt(name.slice(8))\n return 0\n}\n","/*\n * Traditional DNS header RCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml\n */\n\nexport function toString (rcode) {\n switch (rcode) {\n case 0: return 'NOERROR'\n case 1: return 'FORMERR'\n case 2: return 'SERVFAIL'\n case 3: return 'NXDOMAIN'\n case 4: return 'NOTIMP'\n case 5: return 'REFUSED'\n case 6: return 'YXDOMAIN'\n case 7: return 'YXRRSET'\n case 8: return 'NXRRSET'\n case 9: return 'NOTAUTH'\n case 10: return 'NOTZONE'\n case 11: return 'RCODE_11'\n case 12: return 'RCODE_12'\n case 13: return 'RCODE_13'\n case 14: return 'RCODE_14'\n case 15: return 'RCODE_15'\n }\n return 'RCODE_' + rcode\n}\n\nexport function toRcode (code) {\n switch (code.toUpperCase()) {\n case 'NOERROR': return 0\n case 'FORMERR': return 1\n case 'SERVFAIL': return 2\n case 'NXDOMAIN': return 3\n case 'NOTIMP': return 4\n case 'REFUSED': return 5\n case 'YXDOMAIN': return 6\n case 'YXRRSET': return 7\n case 'NXRRSET': return 8\n case 'NOTAUTH': return 9\n case 'NOTZONE': return 10\n case 'RCODE_11': return 11\n case 'RCODE_12': return 12\n case 'RCODE_13': return 13\n case 'RCODE_14': return 14\n case 'RCODE_15': return 15\n }\n return 0\n}\n","/*\n * Traditional DNS header OPCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5\n */\n\nexport function toString (opcode) {\n switch (opcode) {\n case 0: return 'QUERY'\n case 1: return 'IQUERY'\n case 2: return 'STATUS'\n case 3: return 'OPCODE_3'\n case 4: return 'NOTIFY'\n case 5: return 'UPDATE'\n case 6: return 'OPCODE_6'\n case 7: return 'OPCODE_7'\n case 8: return 'OPCODE_8'\n case 9: return 'OPCODE_9'\n case 10: return 'OPCODE_10'\n case 11: return 'OPCODE_11'\n case 12: return 'OPCODE_12'\n case 13: return 'OPCODE_13'\n case 14: return 'OPCODE_14'\n case 15: return 'OPCODE_15'\n }\n return 'OPCODE_' + opcode\n}\n\nexport function toOpcode (code) {\n switch (code.toUpperCase()) {\n case 'QUERY': return 0\n case 'IQUERY': return 1\n case 'STATUS': return 2\n case 'OPCODE_3': return 3\n case 'NOTIFY': return 4\n case 'UPDATE': return 5\n case 'OPCODE_6': return 6\n case 'OPCODE_7': return 7\n case 'OPCODE_8': return 8\n case 'OPCODE_9': return 9\n case 'OPCODE_10': return 10\n case 'OPCODE_11': return 11\n case 'OPCODE_12': return 12\n case 'OPCODE_13': return 13\n case 'OPCODE_14': return 14\n case 'OPCODE_15': return 15\n }\n return 0\n}\n","export function toString (klass) {\n switch (klass) {\n case 1: return 'IN'\n case 2: return 'CS'\n case 3: return 'CH'\n case 4: return 'HS'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + klass\n}\n\nexport function toClass (name) {\n switch (name.toUpperCase()) {\n case 'IN': return 1\n case 'CS': return 2\n case 'CH': return 3\n case 'HS': return 4\n case 'ANY': return 255\n }\n return 0\n}\n","export function toString (type) {\n switch (type) {\n // list at\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11\n case 1: return 'LLQ'\n case 2: return 'UL'\n case 3: return 'NSID'\n case 5: return 'DAU'\n case 6: return 'DHU'\n case 7: return 'N3U'\n case 8: return 'CLIENT_SUBNET'\n case 9: return 'EXPIRE'\n case 10: return 'COOKIE'\n case 11: return 'TCP_KEEPALIVE'\n case 12: return 'PADDING'\n case 13: return 'CHAIN'\n case 14: return 'KEY_TAG'\n case 26946: return 'DEVICEID'\n }\n if (type < 0) {\n return null\n }\n return `OPTION_${type}`\n}\n\nexport function toCode (name) {\n if (typeof name === 'number') {\n return name\n }\n if (!name) {\n return -1\n }\n switch (name.toUpperCase()) {\n case 'OPTION_0': return 0\n case 'LLQ': return 1\n case 'UL': return 2\n case 'NSID': return 3\n case 'OPTION_4': return 4\n case 'DAU': return 5\n case 'DHU': return 6\n case 'N3U': return 7\n case 'CLIENT_SUBNET': return 8\n case 'EXPIRE': return 9\n case 'COOKIE': return 10\n case 'TCP_KEEPALIVE': return 11\n case 'PADDING': return 12\n case 'CHAIN': return 13\n case 'KEY_TAG': return 14\n case 'DEVICEID': return 26946\n case 'OPTION_65535': return 65535\n }\n const m = name.match(/_(\\d+)$/)\n if (m) {\n return parseInt(m[1], 10)\n }\n return -1\n}\n","const SURROGATE_A = 0b1101100000000000\nconst SURROGATE_B = 0b1101110000000000\n\nexport const name = 'utf8'\n\nexport function encodingLength (str) {\n let len = 0\n const strLen = str.length\n for (let i = 0; i < strLen; i += 1) {\n const code = str.charCodeAt(i)\n if (code <= 0x7F) {\n len += 1\n } else if (code <= 0x07FF) {\n len += 2\n } else if ((code & 0xF800) !== SURROGATE_A) {\n len += 3\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n len += 3\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n len += 3\n } else {\n i = next\n len += 4\n }\n }\n }\n }\n return len\n}\n\nexport function encode (str, buf, offset) {\n const strLen = str.length\n if (offset === undefined || offset === null) {\n offset = 0\n }\n if (buf === undefined) {\n buf = new Uint8Array(encodingLength(str) + offset)\n }\n let off = offset\n for (let i = 0; i < strLen; i += 1) {\n let code = str.charCodeAt(i)\n if (code <= 0x7F) {\n buf[off++] = code\n } else if (code <= 0x07FF) {\n buf[off++] = 0b11000000 | ((code & 0b11111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b00000111111)\n } else if ((code & 0xF800) !== SURROGATE_A) {\n buf[off++] = 0b11100000 | ((code & 0b1111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b0000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b0000000000111111)\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n // Incorrectly started surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n // Incorrect surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n i = next\n code = 0b000010000000000000000 |\n ((code & 0b1111111111) << 10) |\n (nextCode & 0b1111111111)\n buf[off++] = 0b11110000 | ((code & 0b111000000000000000000) >> 18)\n buf[off++] = 0b10000000 | ((code & 0b000111111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b000000000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b000000000000000111111)\n }\n }\n }\n }\n encode.bytes = off - offset\n return buf\n}\nencode.bytes = 0\n\nexport function decode (buf, start, end) {\n let result = ''\n if (start === undefined || start === null) {\n start = 0\n }\n if (end === undefined || end === null) {\n end = buf.length\n }\n for (let offset = start; offset < end;) {\n const code = buf[offset++]\n let num\n if (code <= 128) {\n num = code\n } else if (code > 191 && code < 224) {\n num = ((code & 0b11111) << 6) | (buf[offset++] & 0b111111)\n } else if (code > 239 && code < 365) {\n num = (\n ((code & 0b111) << 18) |\n ((buf[offset++] & 0b111111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n ) - 0x10000\n const numA = SURROGATE_A | ((num >> 10) & 0b1111111111)\n result += String.fromCharCode(numA)\n num = SURROGATE_B | (num & 0b1111111111)\n } else {\n num = ((code & 0b1111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n }\n result += String.fromCharCode(num)\n }\n decode.bytes = end - start\n return result\n}\ndecode.bytes = 0\n","import * as utf8 from 'utf8-codec'\n\nexport const isU8Arr = input => input instanceof Uint8Array\n\nexport function bytelength (input) {\n return typeof input === 'string' ? utf8.encodingLength(input) : input.byteLength\n}\n\nexport function from (input) {\n if (input instanceof Uint8Array) {\n return input\n }\n if (Array.isArray(input)) {\n return new Uint8Array(input)\n }\n return utf8.encode(input)\n}\n\nexport function write (arr, str, start) {\n if (typeof str !== 'string') {\n throw new Error('unknown input type')\n }\n utf8.encode(str, arr, start)\n return utf8.encode.bytes\n}\n\nexport function toHex (buf, start, end) {\n let result = ''\n for (let offset = start; offset < end;) {\n const num = buf[offset++]\n const str = num.toString(16)\n result += (str.length === 1) ? '0' + str : str\n }\n return result\n}\n\nconst P_24 = Math.pow(2, 24)\nconst P_16 = Math.pow(2, 16)\nconst P_8 = Math.pow(2, 8)\nexport const readUInt32BE = (buf, offset) => buf[offset] * P_24 +\n buf[offset + 1] * P_16 +\n buf[offset + 2] * P_8 +\n buf[offset + 3]\n\nexport const readUInt16BE = (buf, offset) => (buf[offset] << 8) | buf[offset + 1]\nexport const writeUInt32BE = (buf, value, offset) => {\n value = +value\n buf[offset + 3] = value\n value = value >>> 8\n buf[offset + 2] = value\n value = value >>> 8\n buf[offset + 1] = value\n value = value >>> 8\n buf[offset] = value\n return offset + 4\n}\nexport const writeUInt16BE = (buf, value, offset) => {\n buf[offset] = value >> 8\n buf[offset + 1] = value & 0xFF\n return offset + 2\n}\n\nexport function copy (source, target, targetStart, sourceStart, sourceEnd) {\n if (targetStart < 0) {\n sourceStart -= targetStart\n targetStart = 0\n }\n\n if (sourceStart < 0) {\n sourceStart = 0\n }\n\n if (sourceEnd < 0) {\n return new Uint8Array(0)\n }\n\n if (targetStart >= target.length || sourceStart >= sourceEnd) {\n return 0\n }\n\n return _copyActual(source, target, targetStart, sourceStart, sourceEnd)\n}\n\nfunction _copyActual (source, target, targetStart, sourceStart, sourceEnd) {\n if (sourceEnd - sourceStart > target.length - targetStart) {\n sourceEnd = sourceStart + target.length - targetStart\n }\n\n let nb = sourceEnd - sourceStart\n const sourceLen = source.length - sourceStart\n if (nb > sourceLen) {\n nb = sourceLen\n }\n\n if (sourceStart !== 0 || sourceEnd < source.length) {\n source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb)\n }\n\n target.set(source, targetStart)\n\n return nb\n}\n","import * as ip from '@leichtgewicht/ip-codec'\nimport * as types from './types.mjs'\nimport * as rcodes from './rcodes.mjs'\nimport * as opcodes from './opcodes.mjs'\nimport * as classes from './classes.mjs'\nimport * as optioncodes from './optioncodes.mjs'\nimport * as b from './buffer_utils.mjs'\nimport { decode as toUtf8 } from 'utf8-codec'\n\nconst QUERY_FLAG = 0\nconst RESPONSE_FLAG = 1 << 15\nconst FLUSH_MASK = 1 << 15\nconst NOT_FLUSH_MASK = ~FLUSH_MASK\nconst QU_MASK = 1 << 15\nconst NOT_QU_MASK = ~QU_MASK\n\nfunction codec ({ bytes = 0, encode, decode, encodingLength }) {\n encode.bytes = bytes\n decode.bytes = bytes\n return {\n encode,\n decode,\n encodingLength: encodingLength || (() => bytes)\n }\n}\n\nexport const name = codec({\n encode (str, buf, offset) {\n if (!buf) buf = new Uint8Array(name.encodingLength(str))\n if (!offset) offset = 0\n const oldOffset = offset\n\n // strip leading and trailing .\n const n = str.replace(/^\\.|\\.$/gm, '')\n if (n.length) {\n const list = n.split('.')\n\n for (let i = 0; i < list.length; i++) {\n const len = b.write(buf, list[i], offset + 1)\n buf[offset] = len\n offset += len + 1\n }\n }\n\n buf[offset++] = 0\n\n name.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const list = []\n let oldOffset = offset\n let totalLength = 0\n let consumedBytes = 0\n let jumped = false\n\n while (true) {\n if (offset >= buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const len = buf[offset++]\n consumedBytes += jumped ? 0 : 1\n\n if (len === 0) {\n break\n } else if ((len & 0xc0) === 0) {\n if (offset + len > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n totalLength += len + 1\n if (totalLength > 254) {\n throw new Error('Cannot decode name (name too long)')\n }\n list.push(toUtf8(buf, offset, offset + len))\n offset += len\n consumedBytes += jumped ? 0 : len\n } else if ((len & 0xc0) === 0xc0) {\n if (offset + 1 > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const jumpOffset = b.readUInt16BE(buf, offset - 1) - 0xc000\n if (jumpOffset >= oldOffset) {\n // Allow only pointers to prior data. RFC 1035, section 4.1.4 states:\n // \"[...] an entire domain name or a list of labels at the end of a domain name\n // is replaced with a pointer to a prior occurance (sic) of the same name.\"\n throw new Error('Cannot decode name (bad pointer)')\n }\n offset = jumpOffset\n oldOffset = jumpOffset\n consumedBytes += jumped ? 0 : 1\n jumped = true\n } else {\n throw new Error('Cannot decode name (bad label)')\n }\n }\n\n name.decode.bytes = consumedBytes\n return list.length === 0 ? '.' : list.join('.')\n },\n encodingLength (n) {\n if (n === '.' || n === '..') return 1\n return b.bytelength(n.replace(/^\\.|\\.$/gm, '')) + 2\n }\n})\n\nconst string = codec({\n encode (s, buf, offset) {\n if (!buf) buf = new Uint8Array(string.encodingLength(s))\n if (!offset) offset = 0\n\n const len = b.write(buf, s, offset + 1)\n buf[offset] = len\n string.encode.bytes = len + 1\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = buf[offset]\n const s = toUtf8(buf, offset + 1, offset + 1 + len)\n string.decode.bytes = len + 1\n return s\n },\n encodingLength (s) {\n return b.bytelength(s) + 1\n }\n})\n\nconst header = codec({\n bytes: 12,\n encode (h, buf, offset) {\n if (!buf) buf = new Uint8Array(header.encodingLength(h))\n if (!offset) offset = 0\n\n const flags = (h.flags || 0) & 32767\n const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG\n\n b.writeUInt16BE(buf, h.id || 0, offset)\n b.writeUInt16BE(buf, flags | type, offset + 2)\n b.writeUInt16BE(buf, h.questions.length, offset + 4)\n b.writeUInt16BE(buf, h.answers.length, offset + 6)\n b.writeUInt16BE(buf, h.authorities.length, offset + 8)\n b.writeUInt16BE(buf, h.additionals.length, offset + 10)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n if (buf.length < 12) throw new Error('Header must be 12 bytes')\n const flags = b.readUInt16BE(buf, offset + 2)\n\n return {\n id: b.readUInt16BE(buf, offset),\n type: flags & RESPONSE_FLAG ? 'response' : 'query',\n flags: flags & 32767,\n flag_qr: ((flags >> 15) & 0x1) === 1,\n opcode: opcodes.toString((flags >> 11) & 0xf),\n flag_aa: ((flags >> 10) & 0x1) === 1,\n flag_tc: ((flags >> 9) & 0x1) === 1,\n flag_rd: ((flags >> 8) & 0x1) === 1,\n flag_ra: ((flags >> 7) & 0x1) === 1,\n flag_z: ((flags >> 6) & 0x1) === 1,\n flag_ad: ((flags >> 5) & 0x1) === 1,\n flag_cd: ((flags >> 4) & 0x1) === 1,\n rcode: rcodes.toString(flags & 0xf),\n questions: new Array(b.readUInt16BE(buf, offset + 4)),\n answers: new Array(b.readUInt16BE(buf, offset + 6)),\n authorities: new Array(b.readUInt16BE(buf, offset + 8)),\n additionals: new Array(b.readUInt16BE(buf, offset + 10))\n }\n },\n encodingLength () {\n return 12\n }\n})\n\nconst runknown = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(runknown.encodingLength(data))\n if (!offset) offset = 0\n\n const dLen = data.length\n b.writeUInt16BE(buf, dLen, offset)\n b.copy(data, buf, offset + 2, 0, dLen)\n\n runknown.encode.bytes = dLen + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const data = buf.slice(offset + 2, offset + 2 + len)\n runknown.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return data.length + 2\n }\n})\n\nconst rns = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rns.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rns.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const dd = name.decode(buf, offset + 2)\n\n rns.decode.bytes = len + 2\n return dd\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsoa = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsoa.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n name.encode(data.mname, buf, offset)\n offset += name.encode.bytes\n name.encode(data.rname, buf, offset)\n offset += name.encode.bytes\n b.writeUInt32BE(buf, data.serial || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.refresh || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.retry || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.expire || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.minimum || 0, offset)\n offset += 4\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rsoa.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.rname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.serial = b.readUInt32BE(buf, offset)\n offset += 4\n data.refresh = b.readUInt32BE(buf, offset)\n offset += 4\n data.retry = b.readUInt32BE(buf, offset)\n offset += 4\n data.expire = b.readUInt32BE(buf, offset)\n offset += 4\n data.minimum = b.readUInt32BE(buf, offset)\n offset += 4\n\n rsoa.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)\n }\n})\n\nconst rtxt = codec({\n encode (data, buf, offset) {\n if (!Array.isArray(data)) data = [data]\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] === 'string') {\n data[i] = b.from(data[i])\n }\n if (!b.isU8Arr(data[i])) {\n throw new Error('Must be a Buffer')\n }\n }\n\n if (!buf) buf = new Uint8Array(rtxt.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n\n data.forEach(function (d) {\n buf[offset++] = d.length\n b.copy(d, buf, offset, 0, d.length)\n offset += d.length\n })\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rtxt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n let remaining = b.readUInt16BE(buf, offset)\n offset += 2\n\n const data = []\n while (remaining > 0) {\n const len = buf[offset++]\n --remaining\n if (remaining < len) {\n throw new Error('Buffer overflow')\n }\n data.push(buf.slice(offset, offset + len))\n offset += len\n remaining -= len\n }\n\n rtxt.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!Array.isArray(data)) data = [data]\n let length = 2\n data.forEach(function (buf) {\n if (typeof buf === 'string') {\n length += b.bytelength(buf) + 1\n } else {\n length += buf.length + 1\n }\n })\n return length\n }\n})\n\nconst rnull = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rnull.encodingLength(data))\n if (!offset) offset = 0\n\n if (typeof data === 'string') data = b.from(data)\n if (!data) data = new Uint8Array(0)\n\n const oldOffset = offset\n offset += 2\n\n const len = data.length\n b.copy(data, buf, offset, 0, len)\n offset += len\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rnull.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n const len = b.readUInt16BE(buf, offset)\n\n offset += 2\n\n const data = buf.slice(offset, offset + len)\n offset += len\n\n rnull.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!data) return 2\n return (b.isU8Arr(data) ? data.length : b.bytelength(data)) + 2\n }\n})\n\nconst rhinfo = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rhinfo.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n string.encode(data.cpu, buf, offset)\n offset += string.encode.bytes\n string.encode(data.os, buf, offset)\n offset += string.encode.bytes\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rhinfo.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.cpu = string.decode(buf, offset)\n offset += string.decode.bytes\n data.os = string.decode(buf, offset)\n offset += string.decode.bytes\n rhinfo.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2\n }\n})\n\nconst rptr = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rptr.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rptr.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const data = name.decode(buf, offset + 2)\n rptr.decode.bytes = name.decode.bytes + 2\n return data\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsrv = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsrv.encodingLength(data))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, data.priority || 0, offset + 2)\n b.writeUInt16BE(buf, data.weight || 0, offset + 4)\n b.writeUInt16BE(buf, data.port || 0, offset + 6)\n name.encode(data.target, buf, offset + 8)\n\n const len = name.encode.bytes + 6\n b.writeUInt16BE(buf, len, offset)\n\n rsrv.encode.bytes = len + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n\n const data = {}\n data.priority = b.readUInt16BE(buf, offset + 2)\n data.weight = b.readUInt16BE(buf, offset + 4)\n data.port = b.readUInt16BE(buf, offset + 6)\n data.target = name.decode(buf, offset + 8)\n\n rsrv.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return 8 + name.encodingLength(data.target)\n }\n})\n\nconst rcaa = codec({\n encode (data, buf, offset) {\n const len = rcaa.encodingLength(data)\n\n if (!buf) buf = new Uint8Array(rcaa.encodingLength(data))\n if (!offset) offset = 0\n\n if (data.issuerCritical) {\n data.flags = rcaa.ISSUER_CRITICAL\n }\n\n b.writeUInt16BE(buf, len - 2, offset)\n offset += 2\n buf[offset] = data.flags || 0\n offset += 1\n string.encode(data.tag, buf, offset)\n offset += string.encode.bytes\n b.write(buf, data.value, offset)\n offset += b.bytelength(data.value)\n\n rcaa.encode.bytes = len\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n\n const oldOffset = offset\n const data = {}\n data.flags = buf[offset]\n offset += 1\n data.tag = string.decode(buf, offset)\n offset += string.decode.bytes\n data.value = toUtf8(buf, offset, oldOffset + len)\n\n data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)\n\n rcaa.decode.bytes = len + 2\n\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2\n }\n})\n\nrcaa.ISSUER_CRITICAL = 1 << 7\n\nconst rmx = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rmx.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n b.writeUInt16BE(buf, data.preference || 0, offset)\n offset += 2\n name.encode(data.exchange, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rmx.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.preference = b.readUInt16BE(buf, offset)\n offset += 2\n data.exchange = name.decode(buf, offset)\n offset += name.decode.bytes\n\n rmx.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 4 + name.encodingLength(data.exchange)\n }\n})\n\nconst ra = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(ra.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 4, offset)\n offset += 2\n ip.v4.encode(host, buf, offset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v4.decode(buf, offset)\n return host\n },\n bytes: 6\n})\n\nconst raaaa = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(raaaa.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 16, offset)\n offset += 2\n ip.v6.encode(host, buf, offset)\n raaaa.encode.bytes = 18\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v6.decode(buf, offset)\n raaaa.decode.bytes = 18\n return host\n },\n bytes: 18\n})\n\nconst alloc = size => new Uint8Array(size)\n\nconst roption = codec({\n encode (option, buf, offset) {\n if (!buf) buf = new Uint8Array(roption.encodingLength(option))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const code = optioncodes.toCode(option.code)\n b.writeUInt16BE(buf, code, offset)\n offset += 2\n if (option.data) {\n b.writeUInt16BE(buf, option.data.length, offset)\n offset += 2\n b.copy(option.data, buf, offset)\n offset += option.data.length\n } else {\n switch (code) {\n // case 3: NSID. No encode makes sense.\n // case 5,6,7: Not implementable\n case 8: // ECS\n {\n // note: do IP math before calling\n const spl = option.sourcePrefixLength || 0\n const fam = option.family || ip.familyOf(option.ip, alloc)\n const ipBuf = ip.encode(option.ip, alloc)\n const ipLen = Math.ceil(spl / 8)\n b.writeUInt16BE(buf, ipLen + 4, offset)\n offset += 2\n b.writeUInt16BE(buf, fam, offset)\n offset += 2\n buf[offset++] = spl\n buf[offset++] = option.scopePrefixLength || 0\n\n b.copy(ipBuf, buf, offset, 0, ipLen)\n offset += ipLen\n }\n break\n // case 9: EXPIRE (experimental)\n // case 10: COOKIE. No encode makes sense.\n case 11: // KEEP-ALIVE\n if (option.timeout) {\n b.writeUInt16BE(buf, 2, offset)\n offset += 2\n b.writeUInt16BE(buf, option.timeout, offset)\n offset += 2\n } else {\n b.writeUInt16BE(buf, 0, offset)\n offset += 2\n }\n break\n case 12: // PADDING\n {\n const len = option.length || 0\n b.writeUInt16BE(buf, len, offset)\n offset += 2\n buf.fill(0, offset, offset + len)\n offset += len\n }\n break\n // case 13: CHAIN. Experimental.\n case 14: // KEY-TAG\n {\n const tagsLen = option.tags.length * 2\n b.writeUInt16BE(buf, tagsLen, offset)\n offset += 2\n for (const tag of option.tags) {\n b.writeUInt16BE(buf, tag, offset)\n offset += 2\n }\n }\n break\n default:\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n }\n\n roption.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const option = {}\n option.code = b.readUInt16BE(buf, offset)\n option.type = optioncodes.toString(option.code)\n offset += 2\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n option.data = buf.slice(offset, offset + len)\n switch (option.code) {\n // case 3: NSID. No decode makes sense.\n case 8: // ECS\n option.family = b.readUInt16BE(buf, offset)\n offset += 2\n option.sourcePrefixLength = buf[offset++]\n option.scopePrefixLength = buf[offset++]\n {\n const padded = new Uint8Array((option.family === 1) ? 4 : 16)\n b.copy(buf, padded, 0, offset, offset + len - 4)\n option.ip = ip.decode(padded)\n }\n break\n // case 12: Padding. No decode makes sense.\n case 11: // KEEP-ALIVE\n if (len > 0) {\n option.timeout = b.readUInt16BE(buf, offset)\n offset += 2\n }\n break\n case 14:\n option.tags = []\n for (let i = 0; i < len; i += 2) {\n option.tags.push(b.readUInt16BE(buf, offset))\n offset += 2\n }\n // don't worry about default. caller will use data if desired\n }\n\n roption.decode.bytes = len + 4\n return option\n },\n encodingLength (option) {\n if (option.data) {\n return option.data.length + 4\n }\n const code = optioncodes.toCode(option.code)\n switch (code) {\n case 8: // ECS\n {\n const spl = option.sourcePrefixLength || 0\n return Math.ceil(spl / 8) + 8\n }\n case 11: // KEEP-ALIVE\n return (typeof option.timeout === 'number') ? 6 : 4\n case 12: // PADDING\n return option.length + 4\n case 14: // KEY-TAG\n return 4 + (option.tags.length * 2)\n }\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n})\n\nconst ropt = codec({\n encode (options, buf, offset) {\n if (!buf) buf = new Uint8Array(ropt.encodingLength(options))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const rdlen = encodingLengthList(options, roption)\n b.writeUInt16BE(buf, rdlen, offset)\n offset = encodeList(options, roption, buf, offset + 2)\n\n ropt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const options = []\n let rdlen = b.readUInt16BE(buf, offset)\n offset += 2\n let o = 0\n while (rdlen > 0) {\n options[o++] = roption.decode(buf, offset)\n offset += roption.decode.bytes\n rdlen -= roption.decode.bytes\n }\n ropt.decode.bytes = offset - oldOffset\n return options\n },\n encodingLength (options) {\n return 2 + encodingLengthList(options || [], roption)\n }\n})\n\nconst rdnskey = codec({\n encode (key, buf, offset) {\n if (!buf) buf = new Uint8Array(rdnskey.encodingLength(key))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const keydata = key.key\n if (!b.isU8Arr(keydata)) {\n throw new Error('Key must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, key.flags, offset)\n offset += 2\n buf[offset] = rdnskey.PROTOCOL_DNSSEC\n offset += 1\n buf[offset] = key.algorithm\n offset += 1\n b.copy(keydata, buf, offset, 0, keydata.length)\n offset += keydata.length\n\n rdnskey.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rdnskey.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const key = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n key.flags = b.readUInt16BE(buf, offset)\n offset += 2\n if (buf[offset] !== rdnskey.PROTOCOL_DNSSEC) {\n throw new Error('Protocol must be 3')\n }\n offset += 1\n key.algorithm = buf[offset]\n offset += 1\n key.key = buf.slice(offset, oldOffset + length + 2)\n offset += key.key.length\n rdnskey.decode.bytes = offset - oldOffset\n return key\n },\n encodingLength (key) {\n return 6 + b.bytelength(key.key)\n }\n})\n\nrdnskey.PROTOCOL_DNSSEC = 3\nrdnskey.ZONE_KEY = 0x80\nrdnskey.SECURE_ENTRYPOINT = 0x8000\n\nconst rrrsig = codec({\n encode (sig, buf, offset) {\n if (!buf) buf = new Uint8Array(rrrsig.encodingLength(sig))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const signature = sig.signature\n if (!b.isU8Arr(signature)) {\n throw new Error('Signature must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, types.toType(sig.typeCovered), offset)\n offset += 2\n buf[offset] = sig.algorithm\n offset += 1\n buf[offset] = sig.labels\n offset += 1\n b.writeUInt32BE(buf, sig.originalTTL, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.expiration, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.inception, offset)\n offset += 4\n b.writeUInt16BE(buf, sig.keyTag, offset)\n offset += 2\n name.encode(sig.signersName, buf, offset)\n offset += name.encode.bytes\n b.copy(signature, buf, offset, 0, signature.length)\n offset += signature.length\n\n rrrsig.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrrsig.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const sig = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n sig.typeCovered = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n sig.algorithm = buf[offset]\n offset += 1\n sig.labels = buf[offset]\n offset += 1\n sig.originalTTL = b.readUInt32BE(buf, offset)\n offset += 4\n sig.expiration = b.readUInt32BE(buf, offset)\n offset += 4\n sig.inception = b.readUInt32BE(buf, offset)\n offset += 4\n sig.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n sig.signersName = name.decode(buf, offset)\n offset += name.decode.bytes\n sig.signature = buf.slice(offset, oldOffset + length + 2)\n offset += sig.signature.length\n rrrsig.decode.bytes = offset - oldOffset\n return sig\n },\n encodingLength (sig) {\n return 20 +\n name.encodingLength(sig.signersName) +\n b.bytelength(sig.signature)\n }\n})\nconst rrp = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rrp.encodingLength(data))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(data.mbox || '.', buf, offset)\n offset += name.encode.bytes\n name.encode(data.txt || '.', buf, offset)\n offset += name.encode.bytes\n rrp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrp.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mbox = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n data.txt = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n rrp.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 2 + name.encodingLength(data.mbox || '.') + name.encodingLength(data.txt || '.')\n }\n})\n\nconst typebitmap = codec({\n encode (typelist, buf, offset) {\n if (!buf) buf = new Uint8Array(typebitmap.encodingLength(typelist))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typesByWindow = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n if (typesByWindow[typeid >> 8] === undefined) {\n typesByWindow[typeid >> 8] = []\n }\n typesByWindow[typeid >> 8][(typeid >> 3) & 0x1F] |= 1 << (7 - (typeid & 0x7))\n }\n\n for (let i = 0; i < typesByWindow.length; i++) {\n if (typesByWindow[i] !== undefined) {\n const windowBuf = b.from(typesByWindow[i])\n buf[offset] = i\n offset += 1\n buf[offset] = windowBuf.length\n offset += 1\n b.copy(windowBuf, buf, offset, 0, windowBuf.length)\n offset += windowBuf.length\n }\n }\n\n typebitmap.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset, length) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typelist = []\n while (offset - oldOffset < length) {\n const window = buf[offset]\n offset += 1\n const windowLength = buf[offset]\n offset += 1\n for (let i = 0; i < windowLength; i++) {\n const b = buf[offset + i]\n for (let j = 0; j < 8; j++) {\n if (b & (1 << (7 - j))) {\n const typeid = types.toString((window << 8) | (i << 3) | j)\n typelist.push(typeid)\n }\n }\n }\n offset += windowLength\n }\n\n typebitmap.decode.bytes = offset - oldOffset\n return typelist\n },\n encodingLength (typelist) {\n const extents = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 0xFF)\n }\n\n let len = 0\n for (let i = 0; i < extents.length; i++) {\n if (extents[i] !== undefined) {\n len += 2 + Math.ceil((extents[i] + 1) / 8)\n }\n }\n\n return len\n }\n})\n\nconst rnsec = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(record.nextDomain, buf, offset)\n offset += name.encode.bytes\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.nextDomain = name.decode(buf, offset)\n offset += name.decode.bytes\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 2 +\n name.encodingLength(record.nextDomain) +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rnsec3 = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec3.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const salt = record.salt\n if (!b.isU8Arr(salt)) {\n throw new Error('salt must be a Buffer')\n }\n\n const nextDomain = record.nextDomain\n if (!b.isU8Arr(nextDomain)) {\n throw new Error('nextDomain must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.flags\n offset += 1\n b.writeUInt16BE(buf, record.iterations, offset)\n offset += 2\n buf[offset] = salt.length\n offset += 1\n b.copy(salt, buf, offset, 0, salt.length)\n offset += salt.length\n buf[offset] = nextDomain.length\n offset += 1\n b.copy(nextDomain, buf, offset, 0, nextDomain.length)\n offset += nextDomain.length\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec3.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec3.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.algorithm = buf[offset]\n offset += 1\n record.flags = buf[offset]\n offset += 1\n record.iterations = b.readUInt16BE(buf, offset)\n offset += 2\n const saltLength = buf[offset]\n offset += 1\n record.salt = buf.slice(offset, offset + saltLength)\n offset += saltLength\n const hashLength = buf[offset]\n offset += 1\n record.nextDomain = buf.slice(offset, offset + hashLength)\n offset += hashLength\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec3.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 8 +\n record.salt.length +\n record.nextDomain.length +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rds = codec({\n encode (digest, buf, offset) {\n if (!buf) buf = new Uint8Array(rds.encodingLength(digest))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digestdata = digest.digest\n if (!b.isU8Arr(digestdata)) {\n throw new Error('Digest must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, digest.keyTag, offset)\n offset += 2\n buf[offset] = digest.algorithm\n offset += 1\n buf[offset] = digest.digestType\n offset += 1\n b.copy(digestdata, buf, offset, 0, digestdata.length)\n offset += digestdata.length\n\n rds.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rds.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digest = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n digest.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n digest.algorithm = buf[offset]\n offset += 1\n digest.digestType = buf[offset]\n offset += 1\n digest.digest = buf.slice(offset, oldOffset + length + 2)\n offset += digest.digest.length\n rds.decode.bytes = offset - oldOffset\n return digest\n },\n encodingLength (digest) {\n return 6 + b.bytelength(digest.digest)\n }\n})\n\nfunction renc (type) {\n switch (type.toUpperCase()) {\n case 'A': return ra\n case 'PTR': return rptr\n case 'CNAME': return rptr\n case 'DNAME': return rptr\n case 'TXT': return rtxt\n case 'NULL': return rnull\n case 'AAAA': return raaaa\n case 'SRV': return rsrv\n case 'HINFO': return rhinfo\n case 'CAA': return rcaa\n case 'NS': return rns\n case 'SOA': return rsoa\n case 'MX': return rmx\n case 'OPT': return ropt\n case 'DNSKEY': return rdnskey\n case 'RRSIG': return rrrsig\n case 'RP': return rrp\n case 'NSEC': return rnsec\n case 'NSEC3': return rnsec3\n case 'DS': return rds\n }\n return runknown\n}\n\nexport const answer = codec({\n encode (a, buf, offset) {\n if (!buf) buf = new Uint8Array(answer.encodingLength(a))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(a.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(a.type), offset)\n\n if (a.type.toUpperCase() === 'OPT') {\n if (a.name !== '.') {\n throw new Error('OPT name must be root.')\n }\n b.writeUInt16BE(buf, a.udpPayloadSize || 4096, offset + 2)\n buf[offset + 4] = a.extendedRcode || 0\n buf[offset + 5] = a.ednsVersion || 0\n b.writeUInt16BE(buf, a.flags || 0, offset + 6)\n\n offset += 8\n ropt.encode(a.options || [], buf, offset)\n offset += ropt.encode.bytes\n } else {\n let klass = classes.toClass(a.class === undefined ? 'IN' : a.class)\n if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit\n b.writeUInt16BE(buf, klass, offset + 2)\n b.writeUInt32BE(buf, a.ttl || 0, offset + 4)\n\n offset += 8\n const enc = renc(a.type)\n enc.encode(a.data, buf, offset)\n offset += enc.encode.bytes\n }\n\n answer.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const a = {}\n const oldOffset = offset\n\n a.name = name.decode(buf, offset)\n offset += name.decode.bytes\n a.type = types.toString(b.readUInt16BE(buf, offset))\n if (a.type === 'OPT') {\n a.udpPayloadSize = b.readUInt16BE(buf, offset + 2)\n a.extendedRcode = buf[offset + 4]\n a.ednsVersion = buf[offset + 5]\n a.flags = b.readUInt16BE(buf, offset + 6)\n a.flag_do = ((a.flags >> 15) & 0x1) === 1\n a.options = ropt.decode(buf, offset + 8)\n offset += 8 + ropt.decode.bytes\n } else {\n const klass = b.readUInt16BE(buf, offset + 2)\n a.ttl = b.readUInt32BE(buf, offset + 4)\n\n a.class = classes.toString(klass & NOT_FLUSH_MASK)\n a.flush = !!(klass & FLUSH_MASK)\n\n const enc = renc(a.type)\n a.data = enc.decode(buf, offset + 8)\n offset += 8 + enc.decode.bytes\n }\n\n answer.decode.bytes = offset - oldOffset\n return a\n },\n encodingLength (a) {\n const data = (a.data !== null && a.data !== undefined) ? a.data : a.options\n return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data)\n }\n})\n\nexport const question = codec({\n encode (q, buf, offset) {\n if (!buf) buf = new Uint8Array(question.encodingLength(q))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(q.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(q.type), offset)\n offset += 2\n\n b.writeUInt16BE(buf, classes.toClass(q.class === undefined ? 'IN' : q.class), offset)\n offset += 2\n\n question.encode.bytes = offset - oldOffset\n return q\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const q = {}\n\n q.name = name.decode(buf, offset)\n offset += name.decode.bytes\n\n q.type = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n q.class = classes.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n const qu = !!(q.class & QU_MASK)\n if (qu) q.class &= NOT_QU_MASK\n\n question.decode.bytes = offset - oldOffset\n return q\n },\n encodingLength (q) {\n return name.encodingLength(q.name) + 4\n }\n})\n\nexport {\n rsoa as soa,\n rtxt as txt,\n rnull as null,\n runknown as unknown,\n rns as ns,\n rhinfo as hinfo,\n rptr as ptr,\n rptr as cname,\n rptr as dname,\n rsrv as srv,\n rcaa as caa,\n rmx as mx,\n ra as a,\n raaaa as aaaa,\n roption as option,\n ropt as opt,\n rdnskey as dnskey,\n rrrsig as rrsig,\n rrp as rp,\n rnsec as nsec,\n rnsec3 as nsec3,\n rds as ds,\n renc as enc\n}\n\nexport const AUTHORITATIVE_ANSWER = 1 << 10\nexport const TRUNCATED_RESPONSE = 1 << 9\nexport const RECURSION_DESIRED = 1 << 8\nexport const RECURSION_AVAILABLE = 1 << 7\nexport const AUTHENTIC_DATA = 1 << 5\nexport const CHECKING_DISABLED = 1 << 4\nexport const DNSSEC_OK = 1 << 15\n\nexport const packet = {\n encode: function (result, buf, offset) {\n const allocing = !buf\n\n if (allocing) buf = new Uint8Array(encodingLength(result))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n if (!result.questions) result.questions = []\n if (!result.answers) result.answers = []\n if (!result.authorities) result.authorities = []\n if (!result.additionals) result.additionals = []\n\n header.encode(result, buf, offset)\n offset += header.encode.bytes\n\n offset = encodeList(result.questions, question, buf, offset)\n offset = encodeList(result.answers, answer, buf, offset)\n offset = encodeList(result.authorities, answer, buf, offset)\n offset = encodeList(result.additionals, answer, buf, offset)\n\n packet.encode.bytes = offset - oldOffset\n\n // just a quick sanity check\n if (allocing && encode.bytes !== buf.length) {\n return buf.slice(0, encode.bytes)\n }\n\n return buf\n },\n decode: function (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const result = header.decode(buf, offset)\n offset += header.decode.bytes\n\n offset = decodeList(result.questions, question, buf, offset)\n offset = decodeList(result.answers, answer, buf, offset)\n offset = decodeList(result.authorities, answer, buf, offset)\n offset = decodeList(result.additionals, answer, buf, offset)\n\n packet.decode.bytes = offset - oldOffset\n\n return result\n },\n encodingLength: function (result) {\n return header.encodingLength(result) +\n encodingLengthList(result.questions || [], question) +\n encodingLengthList(result.answers || [], answer) +\n encodingLengthList(result.authorities || [], answer) +\n encodingLengthList(result.additionals || [], answer)\n }\n}\npacket.encode.bytes = 0\npacket.decode.bytes = 0\n\nfunction sanitizeSingle (input, type) {\n if (input.questions) {\n throw new Error('Only one .question object expected instead of a .questions array!')\n }\n const sanitized = Object.assign({\n type\n }, input)\n if (sanitized.question) {\n sanitized.questions = [sanitized.question]\n delete sanitized.question\n }\n return sanitized\n}\n\nexport const query = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'query'), buf, offset)\n query.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n query.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'query'))\n }\n}\nquery.encode.bytes = 0\nquery.decode.bytes = 0\n\nexport const response = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'response'), buf, offset)\n response.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n response.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'response'))\n }\n}\nresponse.encode.bytes = 0\nresponse.decode.bytes = 0\n\nexport const encode = packet.encode\nexport const decode = packet.decode\nexport const encodingLength = packet.encodingLength\n\nexport function streamEncode (result) {\n const buf = encode(result)\n const combine = new Uint8Array(2 + buf.byteLength)\n b.writeUInt16BE(combine, buf.byteLength)\n b.copy(buf, combine, 2, 0, buf.length)\n streamEncode.bytes = combine.byteLength\n return combine\n}\nstreamEncode.bytes = 0\n\nexport function streamDecode (sbuf) {\n const len = b.readUInt16BE(sbuf, 0)\n if (sbuf.byteLength < len + 2) {\n // not enough data\n return null\n }\n const result = decode(sbuf.slice(2))\n streamDecode.bytes = decode.bytes\n return result\n}\nstreamDecode.bytes = 0\n\nexport function encodingLengthList (list, enc) {\n let len = 0\n for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i])\n return len\n}\n\nexport function encodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n enc.encode(list[i], buf, offset)\n offset += enc.encode.bytes\n }\n return offset\n}\n\nexport function decodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n list[i] = enc.decode(buf, offset)\n offset += enc.decode.bytes\n }\n return offset\n}\n","export const PREFERS_PADDING = 1\nexport const PREFERS_NO_PADDING = 2\n\nexport function make (name, charset, padding, paddingMode) {\n if (charset.length !== 64) {\n throw new Error(`Charset needs to be 64 characters long! (${charset.length})`)\n }\n const byCharCode = new Uint8Array(256)\n const byNum = new Uint8Array(64)\n for (let i = 0; i < 64; i += 1) {\n const code = charset.charCodeAt(i)\n if (code > 255) {\n throw new Error(`Character #${i} in charset [code=${code}, char=${charset.charAt(i)}] is too high! (max=255)`)\n }\n if (byCharCode[code] !== 0) {\n throw new Error(`Character [code=${code}, char=${charset.charAt(i)}] is more than once in the charset!`)\n }\n byCharCode[code] = i\n byNum[i] = code\n }\n const padCode = padding.charCodeAt(0)\n const codec = {\n name,\n encodingLength (str) {\n const strLen = str.length\n const len = strLen * 0.75 | 0\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n return len - 2\n }\n return len - 1\n }\n return len\n },\n encode (str, buffer, offset) {\n if (buffer === null || buffer === undefined) {\n buffer = new Uint8Array(codec.encodingLength(str))\n }\n if (offset === null || offset === undefined) {\n offset = 0\n }\n\n let strLen = str.length\n if (str.charCodeAt(strLen - 1) === padCode) {\n if (str.charCodeAt(strLen - 2) === padCode) {\n strLen -= 2\n } else {\n strLen -= 1\n }\n }\n\n const padding = strLen % 4\n const safeLen = strLen - padding\n\n let off = offset\n let i = 0\n while (i < safeLen) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 18) |\n (byCharCode[str.charCodeAt(i + 1)] << 12) |\n (byCharCode[str.charCodeAt(i + 2)] << 6) |\n byCharCode[str.charCodeAt(i + 3)]\n buffer[off++] = code >> 16\n buffer[off++] = code >> 8\n buffer[off++] = code\n i += 4\n }\n\n if (padding === 3) {\n const code =\n (byCharCode[str.charCodeAt(i)] << 10) |\n (byCharCode[str.charCodeAt(i + 1)] << 4) |\n (byCharCode[str.charCodeAt(i + 2)] >> 2)\n buffer[off++] = code >> 8\n buffer[off++] = code\n } else if (padding === 2) {\n buffer[off++] = (byCharCode[str.charCodeAt(i)] << 2) |\n (byCharCode[str.charCodeAt(i + 1)] >> 4)\n }\n\n codec.encode.bytes = off - offset\n return buffer\n },\n decode (buffer, start, end) {\n if (start === null || start === undefined) {\n start = 0\n }\n if (end === null || end === undefined) {\n end = buffer.length\n }\n\n const length = end - start\n const pad = length % 3\n const safeEnd = start + length - pad\n const codes = []\n for (let off = start; off < safeEnd; off += 3) {\n const num = (buffer[off] << 16) | ((buffer[off + 1] << 8)) | buffer[off + 2]\n codes.push(\n byNum[num >> 18 & 0x3F],\n byNum[num >> 12 & 0x3F],\n byNum[num >> 6 & 0x3F],\n byNum[num & 0x3F]\n )\n }\n\n if (pad === 2) {\n const num = (buffer[end - 2] << 8) + buffer[end - 1]\n codes.push(\n byNum[num >> 10],\n byNum[(num >> 4) & 0x3F],\n byNum[(num << 2) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode)\n }\n } else if (pad === 1) {\n const num = buffer[end - 1]\n codes.push(\n byNum[num >> 2],\n byNum[(num << 4) & 0x3F]\n )\n if (paddingMode === PREFERS_PADDING) {\n codes.push(padCode, padCode)\n }\n }\n\n codec.decode.bytes = length\n return String.fromCharCode.apply(String, codes)\n }\n }\n return codec\n}\n\nexport const base64 = make('base64', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', '=', PREFERS_PADDING)\n// https://datatracker.ietf.org/doc/html/rfc4648#section-5\nexport const base64URL = make('base64-url', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', '=', PREFERS_NO_PADDING)\n","let AbortError = typeof global !== 'undefined' ? global.AbortError : typeof window !== 'undefined' ? window.AbortError : null\nif (!AbortError) {\n AbortError = class AbortError extends Error {\n constructor (message = 'Request aborted.') {\n super(message)\n }\n }\n}\nAbortError.prototype.name = 'AbortError'\nAbortError.prototype.code = 'ABORT_ERR'\n\nconst URL = (typeof globalThis !== 'undefined' && globalThis.URL) || require('url').URL\n\nexport { AbortError, URL }\n\nexport class HTTPStatusError extends Error {\n constructor (uri, code, method) {\n super('status=' + code + ' while requesting ' + uri + ' [' + method + ']')\n this.uri = uri\n this.status = code\n this.method = method\n }\n\n toJSON () {\n return {\n code: this.code,\n uri: this.uri,\n status: this.status,\n method: this.method,\n endpoint: this.endpoint\n }\n }\n}\nHTTPStatusError.prototype.name = 'HTTPStatusError'\nHTTPStatusError.prototype.code = 'HTTP_STATUS'\n\nexport class ResponseError extends Error {\n constructor (message, cause) {\n super(message)\n this.cause = cause\n }\n\n toJSON () {\n return {\n message: this.message,\n endpoint: this.endpoint,\n code: this.code,\n cause: reduceError(this.cause)\n }\n }\n}\nResponseError.prototype.name = 'ResponseError'\nResponseError.prototype.code = 'RESPONSE_ERR'\n\nexport class TimeoutError extends Error {\n constructor (timeout) {\n super('Timeout (t=' + timeout + ').')\n this.timeout = timeout\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nTimeoutError.prototype.name = 'TimeoutError'\nTimeoutError.prototype.code = 'ETIMEOUT'\n\nconst v4Regex = /^((\\d{1,3}\\.){3,3}\\d{1,3})(:(\\d{2,5}))?$/\nconst v6Regex = /^((::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?)(:(\\d{2,5}))?$/i\n\nexport function reduceError (err) {\n if (typeof err === 'string') {\n return {\n message: err\n }\n }\n try {\n const json = JSON.stringify(err)\n if (json !== '{}') {\n return JSON.parse(json)\n }\n } catch (e) {}\n const error = {\n message: String(err.message || err)\n }\n if (err.code !== undefined) {\n error.code = String(err.code)\n }\n return error\n}\n\nconst baseParts = /^(([a-z0-9]+:)\\/\\/)?([^/[\\s:]+|\\[[^\\]]+\\])?(:([^/\\s]+))?(\\/[^\\s]*)?(.*)$/\nconst httpFlags = /\\[(post|get|((ipv4|ipv6|name)=([^\\]]+)))\\]/ig\nconst updFlags = /\\[(((pk|name)=([^\\]]+)))\\]/ig\n\nexport function parseEndpoint (endpoint) {\n const parts = baseParts.exec(endpoint)\n const protocol = parts[2] || 'https:'\n const host = parts[3]\n const port = parts[5]\n const path = parts[6]\n const rest = parts[7]\n if (protocol === 'https:' || protocol === 'http:') {\n const flags = parseFlags(rest, httpFlags)\n return {\n name: flags.name,\n protocol,\n ipv4: flags.ipv4,\n ipv6: flags.ipv6,\n host,\n port,\n path,\n method: flags.post ? 'POST' : 'GET'\n }\n }\n if (protocol === 'udp:' || protocol === 'udp4:' || protocol === 'udp6:') {\n const flags = parseFlags(rest, updFlags)\n const v6Parts = /^\\[(.*)\\]$/.exec(host)\n if (v6Parts && protocol === 'udp4:') {\n throw new Error(`Endpoint parsing error: Cannot use ipv6 host with udp4: (endpoint=${endpoint})`)\n }\n if (!v6Parts && protocol === 'udp6:') {\n throw new Error(`Endpoint parsing error: Incorrectly formatted host for udp6: (endpoint=${endpoint})`)\n }\n if (v6Parts) {\n return new UDP6Endpoint({ protocol: 'udp6:', ipv6: v6Parts[1], port, pk: flags.pk, name: flags.name })\n }\n return new UDP4Endpoint({ protocol: 'udp4:', ipv4: host, port, pk: flags.pk, name: flags.name })\n }\n throw new InvalidProtocolError(protocol, endpoint)\n}\n\nfunction parseFlags (rest, regex) {\n regex.lastIndex = 0\n const result = {}\n while (true) {\n const match = regex.exec(rest)\n if (!match) break\n if (match[2]) {\n result[match[3].toLowerCase()] = match[4]\n } else {\n result[match[1].toLowerCase()] = true\n }\n }\n return result\n}\n\nexport class InvalidProtocolError extends Error {\n constructor (protocol, endpoint) {\n super(`Invalid Endpoint: unsupported protocol \"${protocol}\" for endpoint: ${endpoint}, supported protocols: ${supportedProtocols.join(', ')}`)\n this.protocol = protocol\n this.endpoint = endpoint\n }\n\n toJSON () {\n return {\n code: this.code,\n endpoint: this.endpoint,\n timeout: this.timeout\n }\n }\n}\nInvalidProtocolError.prototype.name = 'InvalidProtocolError'\nInvalidProtocolError.prototype.code = 'EPROTOCOL'\n\nexport const supportedProtocols = ['http:', 'https:', 'udp4:', 'udp6:']\n\nexport class BaseEndpoint {\n constructor (opts, isHTTP) {\n this.name = opts.name || null\n this.protocol = opts.protocol\n const port = typeof opts.port === 'string' ? opts.port = parseInt(opts.port, 10) : opts.port\n if (port === undefined || port === null) {\n this.port = isHTTP\n ? (this.protocol === 'https:' ? 443 : 80)\n : (opts.pk ? 443 : 53)\n } else if (typeof port !== 'number' && !isNaN(port)) {\n throw new Error(`Invalid Endpoint: port \"${opts.port}\" needs to be a number: ${JSON.stringify(opts)}`)\n } else {\n this.port = port\n }\n }\n\n toJSON () {\n return this.toString()\n }\n}\n\nexport class UDPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(opts, false)\n this.pk = opts.pk || null\n }\n\n toString () {\n const port = this.port !== (this.pk ? 443 : 53) ? `:${this.port}` : ''\n const pk = this.pk ? ` [pk=${this.pk}]` : ''\n const name = this.name ? ` [name=${this.name}]` : ''\n return `udp://${this.ipv4 || `[${this.ipv6}]`}${port}${pk}${name}`\n }\n}\n\nexport class UDP4Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp4:' }, opts))\n if (!opts.ipv4 || typeof opts.ipv4 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv4 \"${opts.ipv4}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv4 = opts.ipv4\n }\n}\n\nexport class UDP6Endpoint extends UDPEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'udp6:' }, opts))\n if (!opts.ipv6 || typeof opts.ipv6 !== 'string') {\n throw new Error(`Invalid Endpoint: .ipv6 \"${opts.ipv6}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.ipv6 = opts.ipv6\n }\n}\n\nfunction safeHost (host) {\n return v6Regex.test(host) && !v4Regex.test(host) ? `[${host}]` : host\n}\n\nexport class HTTPEndpoint extends BaseEndpoint {\n constructor (opts) {\n super(Object.assign({ protocol: 'https:' }, opts), true)\n if (!opts.host) {\n if (opts.ipv4) {\n opts.host = opts.ipv4\n }\n if (opts.ipv6) {\n opts.host = `[${opts.ipv6}]`\n }\n }\n if (!opts.host || typeof opts.host !== 'string') {\n throw new Error(`Invalid Endpoint: host \"${opts.path}\" needs to be set: ${JSON.stringify(opts)}`)\n }\n this.host = opts.host\n this.path = opts.path || '/dns-query'\n this.method = /^post$/i.test(opts.method) ? 'POST' : 'GET'\n this.ipv4 = opts.ipv4\n this.ipv6 = opts.ipv6\n if (!this.ipv6) {\n const v6Parts = v6Regex.exec(this.host)\n if (v6Parts) {\n this.ipv6 = v6Parts[1]\n }\n }\n if (!this.ipv4) {\n if (v4Regex.test(this.host)) {\n this.ipv4 = this.host\n }\n }\n const url = `${this.protocol}//${safeHost(this.host)}:${this.port}${this.path}`\n try {\n this.url = new URL(url)\n } catch (err) {\n throw new Error(err.message + ` [${url}]`)\n }\n }\n\n toString () {\n const protocol = this.protocol === 'https:' ? '' : 'http://'\n const port = this.port !== (this.protocol === 'https:' ? 443 : 80) ? `:${this.port}` : ''\n const method = this.method !== 'GET' ? ' [post]' : ''\n const path = this.path === '/dns-query' ? '' : this.path\n const name = this.name ? ` [name=${this.name}]` : ''\n const ipv4 = this.ipv4 && this.ipv4 !== this.host ? ` [ipv4=${this.ipv4}]` : ''\n const ipv6 = this.ipv6 && this.ipv6 !== this.host ? ` [ipv6=${this.ipv6}]` : ''\n return `${protocol}${safeHost(this.host)}${port}${path}${method}${ipv4}${ipv6}${name}`\n }\n}\n\nexport function toEndpoint (input) {\n let opts\n if (typeof input === 'string') {\n opts = parseEndpoint(input)\n } else {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error(`Can not convert ${input} to an endpoint`)\n } else if (input instanceof BaseEndpoint) {\n return input\n }\n opts = input\n }\n if (opts.protocol === null || opts.protocol === undefined) {\n opts.protocol = 'https:'\n }\n const protocol = opts.protocol\n if (protocol === 'udp4:') {\n return new UDP4Endpoint(opts)\n }\n if (protocol === 'udp6:') {\n return new UDP6Endpoint(opts)\n }\n if (protocol === 'https:' || protocol === 'http:') {\n return new HTTPEndpoint(opts)\n }\n throw new InvalidProtocolError(protocol, JSON.stringify(opts))\n}\n","/* global XMLHttpRequest, localStorage */\nimport * as utf8Codec from 'utf8-codec'\nimport { base64URL } from '@leichtgewicht/base64-codec'\nimport {\n AbortError,\n HTTPStatusError,\n TimeoutError,\n URL\n} from './common.mjs'\nconst contentType = 'application/dns-message'\n\nfunction noop () { }\n\nexport function queryDns () {\n throw new Error('Only \"doh\" endpoints are supported in the browser')\n}\n\nexport async function loadJSON (url, cache, timeout, abortSignal) {\n const cacheKey = cache ? cache.localStoragePrefix + cache.name : null\n if (cacheKey) {\n try {\n const cached = JSON.parse(localStorage.getItem(cacheKey))\n if (cached && cached.time > cache.maxTime) {\n return cached\n }\n } catch (err) {}\n }\n const { data } = await requestRaw(url, 'GET', null, timeout, abortSignal)\n const result = {\n time: Date.now(),\n data: JSON.parse(utf8Codec.decode(data))\n }\n if (cacheKey) {\n try {\n localStorage.setItem(cacheKey, JSON.stringify(result))\n } catch (err) {\n result.time = null\n }\n }\n return result\n}\n\nfunction requestRaw (url, method, data, timeout, abortSignal) {\n return new Promise((resolve, reject) => {\n const target = new URL(url)\n if (method === 'GET' && data) {\n target.search = '?dns=' + base64URL.decode(data)\n }\n const uri = target.toString()\n const xhr = new XMLHttpRequest()\n xhr.open(method, uri, true)\n xhr.setRequestHeader('Accept', contentType)\n if (method === 'POST') {\n xhr.setRequestHeader('Content-Type', contentType)\n }\n xhr.responseType = 'arraybuffer'\n xhr.timeout = timeout\n xhr.ontimeout = ontimeout\n xhr.onreadystatechange = onreadystatechange\n xhr.onerror = onerror\n xhr.onload = onload\n if (method === 'POST') {\n xhr.send(data)\n } else {\n xhr.send()\n }\n\n if (abortSignal) {\n abortSignal.addEventListener('abort', onabort)\n }\n\n function ontimeout () {\n finish(new TimeoutError(timeout))\n try {\n xhr.abort()\n } catch (e) { }\n }\n\n function onload () {\n if (xhr.status !== 200) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n } else {\n let buf\n if (typeof xhr.response === 'string') {\n buf = utf8Codec.encode(xhr.response)\n } else if (xhr.response instanceof Uint8Array) {\n buf = xhr.response\n } else if (Array.isArray(xhr.response) || xhr.response instanceof ArrayBuffer) {\n buf = new Uint8Array(xhr.response)\n } else {\n throw new Error('Unprocessable response ' + xhr.response)\n }\n finish(null, buf)\n }\n }\n\n function onreadystatechange () {\n if (xhr.readyState > 1 && xhr.status !== 200 && xhr.status !== 0) {\n finish(new HTTPStatusError(uri, xhr.status, method))\n try {\n xhr.abort()\n } catch (e) { }\n }\n }\n\n let finish = function (error, data) {\n finish = noop\n if (abortSignal) {\n abortSignal.removeEventListener('abort', onabort)\n }\n if (error) {\n resolve({\n error,\n response: xhr\n })\n } else {\n resolve({\n data,\n response: xhr\n })\n }\n }\n\n function onerror () {\n finish(xhr.status === 200 ? new Error('Inexplicable XHR Error') : new HTTPStatusError(uri, xhr.status, method))\n }\n\n function onabort () {\n finish(new AbortError())\n try {\n xhr.abort()\n } catch (e) { }\n }\n })\n}\n\nexport function request (url, method, packet, timeout, abortSignal) {\n return requestRaw(url, method, packet, timeout, abortSignal)\n}\n\nexport function processResolvers (resolvers) {\n return resolvers.filter(resolver => resolver.cors || resolver.endpoint.cors)\n}\n","import * as packet from '@leichtgewicht/dns-packet'\nimport { toRcode } from '@leichtgewicht/dns-packet/rcodes.js'\nimport { decode } from 'utf8-codec'\nimport * as lib from './lib.mjs'\nimport { resolvers as backupResolvers } from './resolvers.mjs'\nimport {\n AbortError,\n ResponseError,\n URL,\n toEndpoint\n} from './common.mjs'\n\nexport {\n TimeoutError,\n HTTPStatusError,\n AbortError,\n ResponseError,\n BaseEndpoint,\n HTTPEndpoint,\n UDP4Endpoint,\n UDP6Endpoint,\n parseEndpoint,\n toEndpoint\n} from './common.mjs'\n\nexport const DNS_RCODE_ERROR = {\n 1: 'FormErr',\n 2: 'ServFail',\n 3: 'NXDomain',\n 4: 'NotImp',\n 5: 'Refused',\n 6: 'YXDomain',\n 7: 'YXRRSet',\n 8: 'NXRRSet',\n 9: 'NotAuth',\n 10: 'NotZone',\n 11: 'DSOTYPENI'\n}\n\nexport const DNS_RCODE_MESSAGE = {\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6\n 1: 'The name server was unable to interpret the query.',\n 2: 'The name server was unable to process this query due to a problem with the name server.',\n 3: 'Non-Existent Domain.',\n 4: 'The name server does not support the requested kind of query.',\n 5: 'The name server refuses to perform the specified operation for policy reasons.',\n 6: 'Name Exists when it should not.',\n 7: 'RR Set Exists when it should not.',\n 8: 'RR Set that should exist does not.',\n 9: 'Server Not Authoritative for zone / Not Authorized.',\n 10: 'Name not contained in zone.',\n 11: 'DSO-TYPE Not Implemented.'\n}\n\nexport class DNSRcodeError extends Error {\n constructor (rcode, question) {\n super(`${(DNS_RCODE_MESSAGE[rcode] || 'Undefined error.')} (rcode=${rcode}${DNS_RCODE_ERROR[rcode] ? `, error=${DNS_RCODE_ERROR[rcode]}` : ''}, question=${JSON.stringify(question)})`)\n this.rcode = rcode\n this.code = `DNS_RCODE_${rcode}`\n this.error = DNS_RCODE_ERROR[rcode]\n this.question = question\n }\n\n toJSON () {\n return {\n code: this.code,\n error: this.error,\n question: this.question,\n endpoint: this.endpoint\n }\n }\n}\n\nexport function validateResponse (data, question) {\n const rcode = toRcode(data.rcode)\n if (rcode !== 0) {\n const err = new DNSRcodeError(rcode, question)\n err.endpoint = data.endpoint\n throw err\n }\n return data\n}\n\nfunction processResolvers (res) {\n const time = (res.time === null || res.time === undefined) ? Date.now() : res.time\n const resolvers = lib.processResolvers(res.data.map(resolver => {\n resolver.endpoint = toEndpoint(Object.assign({ name: resolver.name }, resolver.endpoint))\n return resolver\n }))\n const endpoints = resolvers.map(resolver => resolver.endpoint)\n return {\n data: {\n resolvers,\n resolverByName: resolvers.reduce((byName, resolver) => {\n byName[resolver.name] = resolver\n return byName\n }, {}),\n endpoints,\n endpointByName: endpoints.reduce((byName, endpoint) => {\n byName[endpoint.name] = endpoint\n return byName\n }, {})\n },\n time\n }\n}\n\nexport const backup = processResolvers(backupResolvers)\n\nfunction toMultiQuery (singleQuery) {\n const query = Object.assign({\n type: 'query'\n }, singleQuery)\n delete query.question\n query.questions = []\n if (singleQuery.question) {\n query.questions.push(singleQuery.question)\n }\n return query\n}\n\nfunction queryOne (endpoint, query, timeout, abortSignal) {\n if (abortSignal && abortSignal.aborted) {\n return Promise.reject(new AbortError())\n }\n if (endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:') {\n return lib.queryDns(endpoint, query, timeout, abortSignal)\n }\n return queryDoh(endpoint, query, timeout, abortSignal)\n}\n\nfunction queryDoh (endpoint, query, timeout, abortSignal) {\n return lib.request(\n endpoint.url,\n endpoint.method,\n packet.encode(Object.assign({\n flags: packet.RECURSION_DESIRED\n }, query)),\n timeout,\n abortSignal\n ).then(\n function (res) {\n const data = res.data\n const response = res.response\n let error = res.error\n if (error === undefined) {\n if (data.length === 0) {\n error = new ResponseError('Empty.')\n } else {\n try {\n const decoded = packet.decode(data)\n decoded.response = response\n return decoded\n } catch (err) {\n error = new ResponseError('Invalid packet (cause=' + err.message + ')', err)\n }\n }\n }\n throw Object.assign(error, { response })\n }\n )\n}\n\nconst UPDATE_URL = new URL('https://martinheidegger.github.io/dns-query/resolvers.json')\n\nfunction concatUint8 (arrs) {\n const res = new Uint8Array(\n arrs.reduce((len, arr) => len + arr.length, 0)\n )\n let pos = 0\n for (const arr of arrs) {\n res.set(arr, pos)\n pos += arr.length\n }\n return res\n}\n\nexport function combineTXT (inputs) {\n return decode(concatUint8(inputs))\n}\n\nfunction isNameString (entry) {\n return /^@/.test(entry)\n}\n\nexport class Wellknown {\n constructor (opts) {\n this.opts = Object.assign({\n timeout: 5000,\n update: true,\n updateURL: UPDATE_URL,\n persist: false,\n localStoragePrefix: 'dnsquery_',\n maxAge: 300000 // 5 minutes\n }, opts)\n this._dataP = null\n }\n\n _data (force, outdated) {\n if (!force && this._dataP !== null) {\n return this._dataP.then(res => {\n if (res.time < Date.now() - this.opts.maxAge) {\n return this._data(true, res)\n }\n return res\n })\n }\n this._dataP = (!this.opts.update\n ? Promise.resolve(backup)\n : lib.loadJSON(\n this.opts.updateURL,\n this.opts.persist\n ? {\n name: 'resolvers.json',\n localStoragePrefix: this.opts.localStoragePrefix,\n maxTime: Date.now() - this.opts.maxAge\n }\n : null,\n this.opts.timeout\n )\n .then(res => processResolvers({\n data: res.data.resolvers,\n time: res.time\n }))\n .catch(() => outdated || backup)\n )\n return this._dataP\n }\n\n data () {\n return this._data(false).then(data => data.data)\n }\n\n endpoints (input) {\n if (input === null || input === undefined) {\n return this.data().then(data => data.endpoints)\n }\n if (input === 'doh') {\n input = filterDoh\n }\n if (input === 'dns') {\n input = filterDns\n }\n if (typeof input === 'function') {\n return this.data().then(data => data.endpoints.filter(input))\n }\n if (typeof input === 'string' || typeof input[Symbol.iterator] !== 'function') {\n return Promise.reject(new Error(`Endpoints (${input}) needs to be iterable (array).`))\n }\n input = Array.from(input).filter(Boolean)\n if (input.findIndex(isNameString) === -1) {\n try {\n return Promise.resolve(input.map(toEndpoint))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n return this.data().then(data =>\n input.map(entry => {\n if (isNameString(entry)) {\n const found = data.endpointByName[entry.substring(1)]\n if (!found) {\n throw new Error(`Endpoint ${entry} is not known.`)\n }\n return found\n }\n return toEndpoint(entry)\n })\n )\n }\n}\n\nexport const wellknown = new Wellknown()\n\nfunction isPromise (input) {\n if (input === null) {\n return false\n }\n if (typeof input !== 'object') {\n return false\n }\n return typeof input.then === 'function'\n}\n\nfunction toPromise (input) {\n return isPromise(input) ? input : Promise.resolve(input)\n}\n\nexport function query (q, opts) {\n opts = Object.assign({\n retries: 5,\n timeout: 30000 // 30 seconds\n }, opts)\n if (!q.question) return Promise.reject(new Error('To request data you need to specify a .question!'))\n return toPromise(opts.endpoints)\n .then(endpoints => {\n if (!Array.isArray(endpoints) || endpoints.length === 0) {\n throw new Error('No endpoints defined to lookup dns records.')\n }\n return queryN(endpoints.map(toEndpoint), toMultiQuery(q), opts)\n })\n .then(data => {\n data.question = data.questions[0]\n delete data.questions\n return data\n })\n}\n\nexport function lookupTxt (domain, opts) {\n const q = Object.assign({\n question: {\n type: 'TXT',\n name: domain\n }\n }, opts.query)\n return query(q, opts)\n .then(data => {\n validateResponse(data, q)\n return {\n entries: (data.answers || [])\n .filter(answer => answer.type === 'TXT' && answer.data)\n .map(answer => {\n return ({\n data: combineTXT(answer.data),\n ttl: answer.ttl\n })\n })\n .sort((a, b) => {\n if (a.data > b.data) return 1\n if (a.data < b.data) return -1\n return 0\n }),\n endpoint: data.endpoint\n }\n })\n}\n\nfunction queryN (endpoints, q, opts) {\n const endpoint = endpoints.length === 1\n ? endpoints[0]\n : endpoints[Math.floor(Math.random() * endpoints.length) % endpoints.length]\n return queryOne(endpoint, q, opts.timeout, opts.signal)\n .then(\n data => {\n // Add the endpoint to give a chance to identify which endpoint returned the result\n data.endpoint = endpoint.toString()\n return data\n },\n err => {\n if (err.name === 'AbortError' || opts.retries === 0) {\n err.endpoint = endpoint.toString()\n throw err\n }\n if (opts.retries > 0) {\n opts.retries -= 1\n }\n return queryN(endpoints, q, opts)\n }\n )\n}\n\nfunction filterDoh (endpoint) {\n return endpoint.protocol === 'https:' || endpoint.protocol === 'http:'\n}\n\nfunction filterDns (endpoint) {\n return endpoint.protocol === 'udp4:' || endpoint.protocol === 'udp6:'\n}\n","export const resolvers = {\n data: [\n {\n name: 'adfree.usableprivacy.net',\n endpoint: {\n protocol: 'https:',\n host: 'adfree.usableprivacy.net'\n },\n description: 'Public updns DoH service with advertising, tracker and malware filters.\\nHosted in Europe by @usableprivacy, details see: https://docs.usableprivacy.com',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true\n },\n {\n name: 'adguard-dns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.adguard.com',\n ipv4: '94.140.15.15'\n },\n description: 'Remove ads and protect your computer from malware (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-family-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-family.adguard.com',\n ipv4: '94.140.15.16'\n },\n description: 'Adguard DNS with safesearch and adult content blocking (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n },\n filter: true\n },\n {\n name: 'adguard-dns-unfiltered-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-unfiltered.adguard.com',\n ipv4: '94.140.14.140'\n },\n description: 'AdGuard public DNS servers without filters (over DoH)',\n country: 'France',\n location: {\n lat: 48.8582,\n long: 2.3387\n }\n },\n {\n name: 'ahadns-doh-chi',\n endpoint: {\n protocol: 'https:',\n host: 'doh.chi.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 41.8483,\n long: -87.6517\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-in',\n endpoint: {\n protocol: 'https:',\n host: 'doh.in.ahadns.net',\n cors: true\n },\n 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',\n country: 'India',\n location: {\n lat: 19.0748,\n long: 72.8856\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-la',\n endpoint: {\n protocol: 'https:',\n host: 'doh.la.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 34.0549,\n long: -118.2578\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.nl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-ny',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ny.ahadns.net',\n cors: true\n },\n 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',\n country: 'United States',\n location: {\n lat: 40.7308,\n long: -73.9975\n },\n filter: true,\n cors: true\n },\n {\n name: 'ahadns-doh-pl',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pl.ahadns.net',\n cors: true\n },\n 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',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'alidns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.alidns.com',\n ipv4: '223.5.5.5',\n cors: true\n },\n 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/',\n country: 'China',\n location: {\n lat: 34.7725,\n long: 113.7266\n },\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'ams-ads-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl-noads.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging. Blocks ads, malware and trackers. DNSSEC enabled.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n },\n filter: true\n },\n {\n name: 'ams-doh-nl',\n endpoint: {\n protocol: 'https:',\n host: 'dnsnl.alekberg.net'\n },\n description: 'Resolver in Amsterdam. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Romania',\n location: {\n lat: 45.9968,\n long: 24.997\n }\n },\n {\n name: 'att',\n endpoint: {\n protocol: 'https:',\n host: 'dohtrial.att.net'\n },\n description: 'AT&T test DoH server.',\n log: true\n },\n {\n name: 'bcn-ads-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses-noads.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n },\n filter: true\n },\n {\n name: 'bcn-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dnses.alekberg.net'\n },\n description: 'Resolver in Spain. DoH protocol. Non-logging, non-filtering, DNSSEC.',\n country: 'Spain',\n location: {\n lat: 41.3891,\n long: 2.1611\n }\n },\n {\n name: 'brahma-world',\n endpoint: {\n protocol: 'https:',\n host: 'dns.brahma.world'\n },\n 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)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'cisco-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.opendns.com',\n ipv4: '146.112.41.2'\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true,\n log: true\n },\n {\n name: 'cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'dns.cloudflare.com',\n ipv4: '1.0.0.1',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) - aka 1.1.1.1 / 1.0.0.1',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n cors: true\n },\n {\n name: 'cloudflare-family',\n endpoint: {\n protocol: 'https:',\n host: 'family.cloudflare-dns.com',\n ipv4: '1.0.0.3',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware protection and parental control - aka 1.1.1.3 / 1.0.0.3',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'cloudflare-ipv6',\n endpoint: {\n protocol: 'https:',\n host: '1dot1dot1dot1.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare DNS over IPv6 (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'cloudflare-security',\n endpoint: {\n protocol: 'https:',\n host: 'security.cloudflare-dns.com',\n ipv4: '1.0.0.2',\n cors: true\n },\n description: 'Cloudflare DNS (anycast) with malware blocking - aka 1.1.1.2 / 1.0.0.2',\n country: 'Australia',\n location: {\n lat: -33.494,\n long: 143.2104\n },\n filter: true,\n cors: true\n },\n {\n name: 'controld-block-malware',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p1'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p2'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-block-malware-ad-social',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p3'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-family-friendly',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/family'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n },\n filter: true\n },\n {\n name: 'controld-uncensored',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/uncensored'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'controld-unfiltered',\n endpoint: {\n protocol: 'https:',\n host: 'freedns.controld.com',\n path: '/p0'\n },\n 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.',\n country: 'Canada',\n location: {\n lat: 43.6319,\n long: -79.3716\n }\n },\n {\n name: 'dns.digitale-gesellschaft.ch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.digitale-gesellschaft.ch'\n },\n description: 'Public DoH resolver operated by the Digital Society (https://www.digitale-gesellschaft.ch).\\nHosted in Zurich, Switzerland.\\nNon-logging, non-filtering, supports DNSSEC.',\n country: 'Switzerland',\n location: {\n lat: 47.1449,\n long: 8.1551\n }\n },\n {\n name: 'dns.ryan-palmer',\n endpoint: {\n protocol: 'https:',\n host: 'dns1.ryan-palmer.com'\n },\n description: 'Non-logging, non-filtering, DNSSEC DoH Server. Hosted in the UK.',\n country: 'United Kingdom',\n location: {\n lat: 51.5164,\n long: -0.093\n }\n },\n {\n name: 'dns.sb',\n endpoint: {\n protocol: 'https:',\n host: 'doh.sb',\n ipv4: '185.222.222.222',\n cors: true\n },\n description: 'DNSSEC-enabled DoH server by https://xtom.com/\\nhttps://dns.sb/doh/',\n country: 'Unknown',\n location: {\n lat: 47,\n long: 8\n },\n cors: true\n },\n {\n name: 'dns.therifleman.name',\n endpoint: {\n protocol: 'https:',\n host: 'dns.therifleman.name'\n },\n 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',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforfamily-doh-no-safe-search',\n endpoint: {\n protocol: 'https:',\n host: 'dns-doh-no-safe-search.dnsforfamily.com'\n },\n 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',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true\n },\n {\n name: 'dnsforge.de',\n endpoint: {\n protocol: 'https:',\n host: 'dnsforge.de',\n cors: true\n },\n description: 'Public DoH resolver running with Pihole for Adblocking (https://dnsforge.de).\\nNon-logging, AD-filtering, supports DNSSEC. Hosted in Germany.',\n country: 'Germany',\n location: {\n lat: 52.2998,\n long: 9.447\n },\n filter: true,\n cors: true\n },\n {\n name: 'dnshome-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.dnshome.de'\n },\n description: 'https://www.dnshome.de/ public resolver in Germany'\n },\n {\n name: 'dnspod-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.pub',\n cors: true\n },\n description: 'A public DNS resolver in mainland China provided by DNSPod (Tencent Cloud).\\nhttps://www.dnspod.cn/Products/Public.DNS?lang=en',\n filter: true,\n log: true,\n cors: true\n },\n {\n name: 'dnswarden-asia-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adblock'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-adultfilter-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/adultfilter'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'dnswarden-asia-uncensor-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.asia.dnswarden.com',\n path: '/uncensored'\n },\n description: 'Hosted in Singapore. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n }\n },\n {\n name: 'dnswarden-eu-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.eu.dnswarden.com'\n },\n description: 'Hosted in Germany. For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'Germany',\n location: {\n lat: 50.1103,\n long: 8.7147\n },\n filter: true\n },\n {\n name: 'dnswarden-us-adblock-dohv4',\n endpoint: {\n protocol: 'https:',\n host: 'doh.us.dnswarden.com'\n },\n description: 'Hosted in USA (Dallas) . For more information look [here](https://github.com/bhanupratapys/dnswarden) or [here](https://dnswarden.com).',\n country: 'United States',\n location: {\n lat: 32.7889,\n long: -96.8021\n },\n filter: true\n },\n {\n name: 'doh-ch-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ch.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Switzerland. By https://blahdns.com/',\n country: 'Netherlands',\n location: {\n lat: 52.3824,\n long: 4.8995\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-adult',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/adult-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-family',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/family-filter/',\n cors: true\n },\n 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/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-cleanbrowsing-security',\n endpoint: {\n protocol: 'https:',\n host: 'doh.cleanbrowsing.org',\n path: '/doh/security-filter/',\n cors: true\n },\n description: 'Block access to phishing, malware and malicious domains. It does not block adult content.\\nBy https://cleanbrowsing.org/',\n filter: true,\n cors: true\n },\n {\n name: 'doh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'doh.crypto.sx',\n cors: true\n },\n description: 'DNS-over-HTTPS server. Anycast, no logs, no censorship, DNSSEC.\\nBackend hosted by Scaleway, globally cached via Cloudflare.\\nMaintained by Frank Denis.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-crypto-sx-ipv6',\n endpoint: {\n protocol: 'https:',\n host: 'doh-ipv6.crypto.sx',\n cors: true\n },\n 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.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'doh-de-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-de.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Germany. By https://blahdns.com/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-fi-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-fi.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Finland. By https://blahdns.com/',\n country: 'Finland',\n location: {\n lat: 60.1758,\n long: 24.9349\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh-ibksturm',\n endpoint: {\n protocol: 'https:',\n host: 'ibksturm.synology.me'\n },\n description: 'DoH & DoT Server, No Logging, No Filters, DNSSEC\\nRunning privately by ibksturm in Thurgau, Switzerland'\n },\n {\n name: 'doh-jp-blahdns',\n endpoint: {\n protocol: 'https:',\n host: 'doh-jp.blahdns.com',\n cors: true\n },\n description: 'Blocks ad and Tracking, no Logging, DNSSEC, Hosted in Japan. By https://blahdns.com/',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n },\n filter: true,\n cors: true\n },\n {\n name: 'doh.ffmuc.net',\n endpoint: {\n protocol: 'https:',\n host: 'doh.ffmuc.net'\n },\n description: 'An open (non-logging, non-filtering, non-censoring) DoH resolver operated by Freifunk Munich with nodes in DE.\\nhttps://ffmuc.net/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'doh.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org'\n },\n description: 'Non-Logging DNS-over-HTTPS server, cached via Cloudflare.\\nFilters out ads, trackers and malware, NO ECS, supports DNSSEC.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'google',\n endpoint: {\n protocol: 'https:',\n host: 'dns.google',\n ipv4: '8.8.8.8',\n cors: true\n },\n description: 'Google DNS (anycast)',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true,\n cors: true\n },\n {\n name: 'hdns',\n endpoint: {\n protocol: 'https:',\n host: 'query.hdns.io',\n cors: true\n },\n description: 'HDNS is a public DNS resolver that supports Handshake domains.\\nhttps://www.hdns.io',\n country: 'United States',\n location: {\n lat: 37.7771,\n long: -122.406\n },\n cors: true\n },\n {\n name: 'he',\n endpoint: {\n protocol: 'https:',\n host: 'ordns.he.net'\n },\n description: 'Hurricane Electric DoH server (anycast)\\nUnknown logging policy.',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n log: true\n },\n {\n name: 'id-gmail-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app'\n },\n description: 'Non-Logging DNS-over-HTTPS server located in Singapore.\\nFilters out ads, trackers and malware, supports DNSSEC, provided by id-gmail.',\n country: 'Singapore',\n location: {\n lat: 1.2929,\n long: 103.8547\n },\n filter: true\n },\n {\n name: 'iij',\n endpoint: {\n protocol: 'https:',\n host: 'public.dns.iij.jp'\n },\n description: 'DoH server operated by Internet Initiative Japan in Tokyo.\\nhttps://www.iij.ad.jp/',\n country: 'Japan',\n location: {\n lat: 35.69,\n long: 139.69\n },\n log: true\n },\n {\n name: 'iqdns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'a.passcloud.xyz'\n },\n 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',\n filter: true\n },\n {\n name: 'jp.tiar.app-doh',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app'\n },\n description: 'Non-Logging, Non-Filtering DNS-over-HTTPS server in Japan.\\nNo ECS, Support DNSSEC',\n country: 'Japan',\n location: {\n lat: 35.6882,\n long: 139.7532\n }\n },\n {\n name: 'jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org'\n },\n description: 'DNS-over-HTTPS Server. Non-Logging, Non-Filtering, No ECS, Support DNSSEC.\\nCached via Cloudflare.'\n },\n {\n name: 'libredns',\n endpoint: {\n protocol: 'https:',\n host: 'doh.libredns.gr'\n },\n description: 'DoH server in Germany. No logging, but no DNS padding and no DNSSEC support.\\nhttps://libredns.gr/',\n country: 'Germany',\n location: {\n lat: 51.2993,\n long: 9.491\n }\n },\n {\n name: 'nextdns',\n endpoint: {\n protocol: 'https:',\n host: 'anycsast.dns.nextdns.io'\n },\n 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/',\n country: 'Netherlands',\n location: {\n lat: 52.3891,\n long: 4.6563\n }\n },\n {\n name: 'nextdns-ultralow',\n endpoint: {\n protocol: 'https:',\n host: 'dns.nextdns.io',\n path: '/dnscrypt-proxy'\n },\n 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.'\n },\n {\n name: 'njalla-doh',\n endpoint: {\n protocol: 'https:',\n host: 'dns.njal.la',\n cors: true\n },\n description: 'Non-logging DoH server in Sweden operated by Njalla.\\nhttps://dns.njal.la/',\n country: 'Sweden',\n location: {\n lat: 59.3247,\n long: 18.056\n },\n cors: true\n },\n {\n name: 'odoh-cloudflare',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.cloudflare-dns.com',\n cors: true\n },\n description: 'Cloudflare ODoH server.\\nhttps://cloudflare.com',\n cors: true\n },\n {\n name: 'odoh-crypto-sx',\n endpoint: {\n protocol: 'https:',\n host: 'odoh.crypto.sx',\n cors: true\n },\n description: 'ODoH target server. Anycast, no logs.\\nBackend hosted by Scaleway. Maintained by Frank Denis.',\n cors: true\n },\n {\n name: 'odoh-id-gmail',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. Based in Singapore, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'odoh-jp.tiar.app',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiar.app',\n path: '/odoh'\n },\n description: 'ODoH target server. no logs.'\n },\n {\n name: 'odoh-jp.tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'jp.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.'\n },\n {\n name: 'odoh-resolver4.dns.openinternet.io',\n endpoint: {\n protocol: 'https:',\n host: 'resolver4.dns.openinternet.io'\n },\n 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\"\n },\n {\n name: 'odoh-tiarap.org',\n endpoint: {\n protocol: 'https:',\n host: 'doh.tiarap.org',\n path: '/odoh'\n },\n description: 'ODoH target server via Cloudflare, no logs.\\nFilter ads, trackers and malware.',\n filter: true\n },\n {\n name: 'publicarray-au2-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh-2.seby.io',\n cors: true\n },\n description: 'DNSSEC • OpenNIC • Non-logging • Uncensored - hosted on ovh.com.au\\nMaintained by publicarray - https://dns.seby.io',\n country: 'Australia',\n location: {\n lat: -33.8591,\n long: 151.2002\n },\n cors: true\n },\n {\n name: 'puredns-doh',\n endpoint: {\n protocol: 'https:',\n host: 'puredns.org',\n ipv4: '146.190.6.13',\n cors: true\n },\n description: 'Public uncensored DNS resolver in Singapore - https://puredns.org\\n** Only available in Indonesia and Singapore **',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n cors: true\n },\n {\n name: 'quad101',\n endpoint: {\n protocol: 'https:',\n host: 'dns.twnic.tw',\n cors: true\n },\n description: 'DNSSEC-aware public resolver by the Taiwan Network Information Center (TWNIC)\\nhttps://101.101.101.101/index_en.html',\n cors: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns11.quad9.net',\n ipv4: '149.112.112.11'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter/ecs 9.9.9.11 - 149.112.112.11',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns.quad9.net',\n ipv4: '149.112.112.112'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 9.9.9.9 - 149.112.112.9 - 149.112.112.112',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-ecs-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns12.quad9.net',\n ipv4: '9.9.9.12'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter/ecs 9.9.9.12 - 149.112.112.12',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip4-port443-nofilter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns10.quad9.net',\n ipv4: '149.112.112.10'\n },\n description: 'Quad9 (anycast) no-dnssec/no-log/no-filter 9.9.9.10 - 149.112.112.10',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n }\n },\n {\n name: 'quad9-doh-ip6-port5053-filter-pri',\n endpoint: {\n protocol: 'https:',\n host: 'dns9.quad9.net'\n },\n description: 'Quad9 (anycast) dnssec/no-log/filter 2620:fe::fe - 2620:fe::9 - 2620:fe::fe:9',\n country: 'United States',\n location: {\n lat: 37.751,\n long: -97.822\n },\n filter: true\n },\n {\n name: 'safesurfer-doh',\n endpoint: {\n protocol: 'https:',\n host: 'doh.safesurfer.io'\n },\n 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',\n filter: true,\n log: true\n },\n {\n name: 'sth-ads-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse-noads.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, remove ads and malware, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n },\n filter: true\n },\n {\n name: 'sth-doh-se',\n endpoint: {\n protocol: 'https:',\n host: 'dnsse.alekberg.net'\n },\n description: 'Resolver in Stockholm, Sweden. DoH server. Non-logging, non-filtering, DNSSEC.',\n country: 'Bulgaria',\n location: {\n lat: 42.696,\n long: 23.332\n }\n },\n {\n name: 'switch',\n endpoint: {\n protocol: 'https:',\n host: 'dns.switch.ch'\n },\n description: 'Public DoH service provided by SWITCH in Switzerland\\nhttps://www.switch.ch\\nProvides protection against malware, but does not block ads.',\n filter: true\n },\n {\n name: 'uncensoreddns-dk-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'unicast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, unicast hosted in Denmark - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'uncensoreddns-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'anycast.uncensoreddns.org'\n },\n description: 'Also known as censurfridns.\\nDoH, no logs, no filter, DNSSEC, anycast - https://blog.uncensoreddns.org',\n country: 'Denmark',\n location: {\n lat: 55.7123,\n long: 12.0564\n }\n },\n {\n name: 'v.dnscrypt.uk-doh-ipv4',\n endpoint: {\n protocol: 'https:',\n host: 'v.dnscrypt.uk'\n },\n description: 'DoH, no logs, uncensored, DNSSEC. Hosted in London UK on Digital Ocean\\nhttps://www.dnscrypt.uk',\n country: 'United Kingdom',\n location: {\n lat: 51.4964,\n long: -0.1224\n }\n }\n ],\n time: 1654187067783\n}\n","import { Logger } from \"@waku/utils\";\nimport { bytesToUtf8 } from \"@waku/utils/bytes\";\nimport { query, wellknown } from \"dns-query\";\nconst log = new Logger(\"dns-over-https\");\nexport class DnsOverHttps {\n endpoints;\n retries;\n /**\n * Create new Dns-Over-Http DNS client.\n *\n * @param endpoints The endpoints for Dns-Over-Https queries;\n * Defaults to using dns-query's API..\n * @param retries Retries if a given endpoint fails.\n *\n * @throws {code: string} If DNS query fails.\n */\n static async create(endpoints, retries) {\n const _endpoints = endpoints ?? (await wellknown.endpoints(\"doh\"));\n return new DnsOverHttps(_endpoints, retries);\n }\n constructor(endpoints, retries = 3) {\n this.endpoints = endpoints;\n this.retries = retries;\n }\n /**\n * Resolves a TXT record\n *\n * @param domain The domain name\n *\n * @throws if the query fails\n */\n async resolveTXT(domain) {\n let answers;\n try {\n const res = await query({\n question: { type: \"TXT\", name: domain }\n }, {\n endpoints: this.endpoints,\n retries: this.retries\n });\n answers = res.answers;\n }\n catch (error) {\n log.error(\"query failed: \", error);\n throw new Error(\"DNS query failed\");\n }\n if (!answers)\n throw new Error(`Could not resolve ${domain}`);\n const data = answers.map((a) => a.data);\n const result = [];\n data.forEach((d) => {\n if (typeof d === \"string\") {\n result.push(d);\n }\n else if (Array.isArray(d)) {\n d.forEach((sd) => {\n if (typeof sd === \"string\") {\n result.push(sd);\n }\n else {\n result.push(bytesToUtf8(sd));\n }\n });\n }\n else {\n result.push(bytesToUtf8(d));\n }\n });\n return result;\n }\n}\n//# sourceMappingURL=dns_over_https.js.map","import { ENR } from \"@waku/enr\";\nimport { keccak256, verifySignature } from \"@waku/enr\";\nimport { utf8ToBytes } from \"@waku/utils/bytes\";\nimport base32 from \"hi-base32\";\nimport { fromString } from \"uint8arrays/from-string\";\nexport class ENRTree {\n static RECORD_PREFIX = ENR.RECORD_PREFIX;\n static TREE_PREFIX = \"enrtree:\";\n static BRANCH_PREFIX = \"enrtree-branch:\";\n static ROOT_PREFIX = \"enrtree-root:\";\n /**\n * Extracts the branch subdomain referenced by a DNS tree root string after verifying\n * the root record signature with its base32 compressed public key.\n */\n static parseAndVerifyRoot(root, publicKey) {\n if (!root.startsWith(this.ROOT_PREFIX))\n throw new Error(`ENRTree root entry must start with '${this.ROOT_PREFIX}'`);\n const rootValues = ENRTree.parseRootValues(root);\n const decodedPublicKey = base32.decode.asBytes(publicKey);\n // The signature is a 65-byte secp256k1 over the keccak256 hash\n // of the record content, excluding the `sig=` part, encoded as URL-safe base64 string\n // (Trailing recovery bit must be trimmed to pass `ecdsaVerify` method)\n const signedComponent = root.split(\" sig\")[0];\n const signedComponentBuffer = utf8ToBytes(signedComponent);\n const signatureBuffer = fromString(rootValues.signature, \"base64url\").slice(0, 64);\n const isVerified = verifySignature(signatureBuffer, keccak256(signedComponentBuffer), new Uint8Array(decodedPublicKey));\n if (!isVerified)\n throw new Error(\"Unable to verify ENRTree root signature\");\n return rootValues.eRoot;\n }\n static parseRootValues(txt) {\n const matches = txt.match(/^enrtree-root:v1 e=([^ ]+) l=([^ ]+) seq=(\\d+) sig=([^ ]+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree root entry\");\n matches.shift(); // The first entry is the full match\n const [eRoot, lRoot, seq, signature] = matches;\n if (!eRoot)\n throw new Error(\"Could not parse 'e' value from ENRTree root entry\");\n if (!lRoot)\n throw new Error(\"Could not parse 'l' value from ENRTree root entry\");\n if (!seq)\n throw new Error(\"Could not parse 'seq' value from ENRTree root entry\");\n if (!signature)\n throw new Error(\"Could not parse 'sig' value from ENRTree root entry\");\n return { eRoot, lRoot, seq: Number(seq), signature };\n }\n /**\n * Returns the public key and top level domain of an ENR tree entry.\n * The domain is the starting point for traversing a set of linked DNS TXT records\n * and the public key is used to verify the root entry record\n */\n static parseTree(tree) {\n if (!tree.startsWith(this.TREE_PREFIX))\n throw new Error(`ENRTree tree entry must start with '${this.TREE_PREFIX}'`);\n const matches = tree.match(/^enrtree:\\/\\/([^@]+)@(.+)$/);\n if (!Array.isArray(matches))\n throw new Error(\"Could not parse ENRTree tree entry\");\n matches.shift(); // The first entry is the full match\n const [publicKey, domain] = matches;\n if (!publicKey)\n throw new Error(\"Could not parse public key from ENRTree tree entry\");\n if (!domain)\n throw new Error(\"Could not parse domain from ENRTree tree entry\");\n return { publicKey, domain };\n }\n /**\n * Returns subdomains listed in an ENR branch entry. These in turn lead to\n * either further branch entries or ENR records.\n */\n static parseBranch(branch) {\n if (!branch.startsWith(this.BRANCH_PREFIX))\n throw new Error(`ENRTree branch entry must start with '${this.BRANCH_PREFIX}'`);\n return branch.split(this.BRANCH_PREFIX)[1].split(\",\");\n }\n}\n//# sourceMappingURL=enrtree.js.map","import { Logger } from \"@waku/utils\";\nconst log = new Logger(\"discovery:fetch_nodes\");\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peers = [];\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && isNewPeer(peer, peers)) {\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n peers.push(peer);\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n return peers;\n}\n/**\n * Fetch nodes using passed [[getNode]] until all wanted capabilities are\n * fulfilled or the number of [[getNode]] call exceeds the sum of\n * [[wantedNodeCapabilityCount]] plus [[errorTolerance]].\n */\nexport async function* yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, errorTolerance, getNode) {\n const wanted = {\n relay: wantedNodeCapabilityCount.relay ?? 0,\n store: wantedNodeCapabilityCount.store ?? 0,\n filter: wantedNodeCapabilityCount.filter ?? 0,\n lightPush: wantedNodeCapabilityCount.lightPush ?? 0\n };\n const maxSearches = wanted.relay + wanted.store + wanted.filter + wanted.lightPush;\n const actual = {\n relay: 0,\n store: 0,\n filter: 0,\n lightPush: 0\n };\n let totalSearches = 0;\n const peerNodeIds = new Set();\n while (!isSatisfied(wanted, actual) &&\n totalSearches < maxSearches + errorTolerance) {\n const peer = await getNode();\n if (peer && peer.nodeId && !peerNodeIds.has(peer.nodeId)) {\n peerNodeIds.add(peer.nodeId);\n // ENRs without a waku2 key are ignored.\n if (peer.waku2) {\n if (helpsSatisfyCapabilities(peer.waku2, wanted, actual)) {\n addCapabilities(peer.waku2, actual);\n yield peer;\n }\n }\n log.info(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);\n }\n totalSearches++;\n }\n}\nfunction isSatisfied(wanted, actual) {\n return (actual.relay >= wanted.relay &&\n actual.store >= wanted.store &&\n actual.filter >= wanted.filter &&\n actual.lightPush >= wanted.lightPush);\n}\nfunction isNewPeer(peer, peers) {\n if (!peer.nodeId)\n return false;\n for (const existingPeer of peers) {\n if (peer.nodeId === existingPeer.nodeId) {\n return false;\n }\n }\n return true;\n}\nfunction addCapabilities(node, total) {\n if (node.relay)\n total.relay += 1;\n if (node.store)\n total.store += 1;\n if (node.filter)\n total.filter += 1;\n if (node.lightPush)\n total.lightPush += 1;\n}\n/**\n * Checks if the proposed ENR [[node]] helps satisfy the [[wanted]] capabilities,\n * considering the [[actual]] capabilities of nodes retrieved so far..\n *\n * @throws If the function is called when the wanted capabilities are already fulfilled.\n */\nfunction helpsSatisfyCapabilities(node, wanted, actual) {\n if (isSatisfied(wanted, actual)) {\n throw \"Internal Error: Waku2 wanted capabilities are already fulfilled\";\n }\n const missing = missingCapabilities(wanted, actual);\n return ((missing.relay && node.relay) ||\n (missing.store && node.store) ||\n (missing.filter && node.filter) ||\n (missing.lightPush && node.lightPush));\n}\n/**\n * Return a [[Waku2]] Object for which capabilities are set to true if they are\n * [[wanted]] yet missing from [[actual]].\n */\nfunction missingCapabilities(wanted, actual) {\n return {\n relay: actual.relay < wanted.relay,\n store: actual.store < wanted.store,\n filter: actual.filter < wanted.filter,\n lightPush: actual.lightPush < wanted.lightPush\n };\n}\n//# sourceMappingURL=fetch_nodes.js.map","import { EnrDecoder } from \"@waku/enr\";\nimport { Logger } from \"@waku/utils\";\nimport { DnsOverHttps } from \"./dns_over_https.js\";\nimport { ENRTree } from \"./enrtree.js\";\nimport { fetchNodesUntilCapabilitiesFulfilled, yieldNodesUntilCapabilitiesFulfilled } from \"./fetch_nodes.js\";\nconst log = new Logger(\"discovery:dns\");\nexport class DnsNodeDiscovery {\n dns;\n _DNSTreeCache;\n _errorTolerance = 10;\n static async dnsOverHttp(dnsClient) {\n if (!dnsClient) {\n dnsClient = await DnsOverHttps.create();\n }\n return new DnsNodeDiscovery(dnsClient);\n }\n /**\n * Returns a list of verified peers listed in an EIP-1459 DNS tree. Method may\n * return fewer peers than requested if @link wantedNodeCapabilityCount requires\n * larger quantity of peers than available or the number of errors/duplicate\n * peers encountered by randomized search exceeds the sum of the fields of\n * @link wantedNodeCapabilityCount plus the @link _errorTolerance factor.\n */\n async getPeers(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n const peers = await fetchNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context));\n log.info(\"retrieved peers: \", peers.map((peer) => {\n return {\n id: peer.peerId?.toString(),\n multiaddrs: peer.multiaddrs?.map((ma) => ma.toString())\n };\n }));\n return peers;\n }\n constructor(dns) {\n this._DNSTreeCache = {};\n this.dns = dns;\n }\n /**\n * {@inheritDoc getPeers}\n */\n async *getNextPeer(enrTreeUrls, wantedNodeCapabilityCount) {\n const networkIndex = Math.floor(Math.random() * enrTreeUrls.length);\n const { publicKey, domain } = ENRTree.parseTree(enrTreeUrls[networkIndex]);\n const context = {\n domain,\n publicKey,\n visits: {}\n };\n for await (const peer of yieldNodesUntilCapabilitiesFulfilled(wantedNodeCapabilityCount, this._errorTolerance, () => this._search(domain, context))) {\n yield peer;\n }\n }\n /**\n * Runs a recursive, randomized descent of the DNS tree to retrieve a single\n * ENR record as an ENR. Returns null if parsing or DNS resolution fails.\n */\n async _search(subdomain, context) {\n try {\n const entry = await this._getTXTRecord(subdomain, context);\n context.visits[subdomain] = true;\n let next;\n let branches;\n const entryType = getEntryType(entry);\n try {\n switch (entryType) {\n case ENRTree.ROOT_PREFIX:\n next = ENRTree.parseAndVerifyRoot(entry, context.publicKey);\n return await this._search(next, context);\n case ENRTree.BRANCH_PREFIX:\n branches = ENRTree.parseBranch(entry);\n next = selectRandomPath(branches, context);\n return await this._search(next, context);\n case ENRTree.RECORD_PREFIX:\n return EnrDecoder.fromString(entry);\n default:\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to search DNS tree ${entryType} at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n catch (error) {\n log.error(`Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`);\n return null;\n }\n }\n /**\n * Retrieves the TXT record stored at a location from either\n * this DNS tree cache or via DNS query.\n *\n * @throws if the TXT Record contains non-UTF-8 values.\n */\n async _getTXTRecord(subdomain, context) {\n if (this._DNSTreeCache[subdomain]) {\n return this._DNSTreeCache[subdomain];\n }\n // Location is either the top level tree entry host or a subdomain of it.\n const location = subdomain !== context.domain\n ? `${subdomain}.${context.domain}`\n : context.domain;\n const response = await this.dns.resolveTXT(location);\n if (!response.length)\n throw new Error(\"Received empty result array while fetching TXT record\");\n if (!response[0].length)\n throw new Error(\"Received empty TXT record\");\n // Branch entries can be an array of strings of comma delimited subdomains, with\n // some subdomain strings split across the array elements\n const result = response.join(\"\");\n this._DNSTreeCache[subdomain] = result;\n return result;\n }\n}\nfunction getEntryType(entry) {\n if (entry.startsWith(ENRTree.ROOT_PREFIX))\n return ENRTree.ROOT_PREFIX;\n if (entry.startsWith(ENRTree.BRANCH_PREFIX))\n return ENRTree.BRANCH_PREFIX;\n if (entry.startsWith(ENRTree.RECORD_PREFIX))\n return ENRTree.RECORD_PREFIX;\n return \"\";\n}\n/**\n * Returns a randomly selected subdomain string from the list provided by a branch\n * entry record.\n *\n * The client must track subdomains which are already resolved to avoid\n * going into an infinite loop b/c branch entries can contain\n * circular references. It’s in the client’s best interest to traverse the\n * tree in random order.\n */\nfunction selectRandomPath(branches, context) {\n // Identify domains already visited in this traversal of the DNS tree.\n // Then filter against them to prevent cycles.\n const circularRefs = {};\n for (const [idx, subdomain] of branches.entries()) {\n if (context.visits[subdomain]) {\n circularRefs[idx] = true;\n }\n }\n // If all possible paths are circular...\n if (Object.keys(circularRefs).length === branches.length) {\n throw new Error(\"Unresolvable circular path detected\");\n }\n // Randomly select a viable path\n let index;\n do {\n index = Math.floor(Math.random() * branches.length);\n } while (circularRefs[index]);\n return branches[index];\n}\n//# sourceMappingURL=dns.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { DNS_DISCOVERY_TAG } from \"@waku/interfaces\";\nimport { encodeRelayShard, Logger } from \"@waku/utils\";\nimport { DEFAULT_BOOTSTRAP_TAG_NAME, DEFAULT_BOOTSTRAP_TAG_TTL, DEFAULT_BOOTSTRAP_TAG_VALUE, DEFAULT_NODE_REQUIREMENTS } from \"./constants.js\";\nimport { DnsNodeDiscovery } from \"./dns.js\";\nconst log = new Logger(\"peer-discovery-dns\");\n/**\n * Parse options and expose function to return bootstrap peer addresses.\n */\nexport class PeerDiscoveryDns extends TypedEventEmitter {\n nextPeer;\n _started;\n _components;\n _options;\n constructor(components, options) {\n super();\n this._started = false;\n this._components = components;\n this._options = options;\n const { enrUrls } = options;\n log.info(\"Use following EIP-1459 ENR Tree URLs: \", enrUrls);\n }\n /**\n * Start discovery process\n */\n async start() {\n log.info(\"Starting peer discovery via dns\");\n this._started = true;\n await this.findPeers();\n }\n async findPeers() {\n if (!this.nextPeer) {\n let { enrUrls } = this._options;\n if (!Array.isArray(enrUrls))\n enrUrls = [enrUrls];\n const { wantedNodeCapabilityCount } = this._options;\n const dns = await DnsNodeDiscovery.dnsOverHttp();\n this.nextPeer = dns.getNextPeer.bind(dns, enrUrls, wantedNodeCapabilityCount);\n }\n for await (const peerEnr of this.nextPeer()) {\n if (!this._started) {\n return;\n }\n const { peerInfo, shardInfo } = peerEnr;\n if (!peerInfo) {\n continue;\n }\n const tagsToUpdate = {\n [DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._options.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._options.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n };\n let isPeerChanged = false;\n const isPeerExists = await this._components.peerStore.has(peerInfo.id);\n if (isPeerExists) {\n const peer = await this._components.peerStore.get(peerInfo.id);\n const hasBootstrapTag = peer.tags.has(DEFAULT_BOOTSTRAP_TAG_NAME);\n if (!hasBootstrapTag) {\n isPeerChanged = true;\n await this._components.peerStore.merge(peerInfo.id, {\n tags: tagsToUpdate\n });\n }\n }\n else {\n isPeerChanged = true;\n await this._components.peerStore.save(peerInfo.id, {\n tags: tagsToUpdate,\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n })\n });\n }\n if (isPeerChanged) {\n this.dispatchEvent(new CustomEvent(\"peer\", { detail: peerInfo }));\n }\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n this._started = false;\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return DNS_DISCOVERY_TAG;\n }\n}\nexport function wakuDnsDiscovery(enrUrls, wantedNodeCapabilityCount = DEFAULT_NODE_REQUIREMENTS) {\n return (components) => new PeerDiscoveryDns(components, { enrUrls, wantedNodeCapabilityCount });\n}\n//# sourceMappingURL=dns_discovery.js.map","export function selectOpenConnection(connections) {\n return connections\n .filter((c) => c.status === \"open\")\n .sort((left, right) => right.timeline.open - left.timeline.open)\n .at(0);\n}\n//# sourceMappingURL=utils.js.map","import { Logger } from \"@waku/utils\";\nimport { selectOpenConnection } from \"./utils.js\";\nconst STREAM_LOCK_KEY = \"consumed\";\nexport class StreamManager {\n multicodec;\n getConnections;\n addEventListener;\n log;\n ongoingCreation = new Set();\n streamPool = new Map();\n constructor(multicodec, getConnections, addEventListener) {\n this.multicodec = multicodec;\n this.getConnections = getConnections;\n this.addEventListener = addEventListener;\n this.log = new Logger(`stream-manager:${multicodec}`);\n this.addEventListener(\"peer:update\", this.handlePeerUpdateStreamPool);\n }\n async getStream(peer) {\n const peerId = peer.id.toString();\n const scheduledStream = this.streamPool.get(peerId);\n if (scheduledStream) {\n this.streamPool.delete(peerId);\n await scheduledStream;\n }\n let stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n stream = await this.createStream(peer);\n this.lockStream(peer.id.toString(), stream);\n return stream;\n }\n async createStream(peer, retries = 0) {\n const connections = this.getConnections(peer.id);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n }\n let lastError;\n let stream;\n for (let i = 0; i < retries + 1; i++) {\n try {\n this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n stream = await connection.newStream(this.multicodec);\n this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n break;\n }\n catch (error) {\n lastError = error;\n }\n }\n if (!stream) {\n throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +\n lastError);\n }\n return stream;\n }\n async createStreamWithLock(peer) {\n const peerId = peer.id.toString();\n if (this.ongoingCreation.has(peerId)) {\n this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);\n return;\n }\n try {\n this.ongoingCreation.add(peerId);\n await this.createStream(peer);\n }\n catch (error) {\n this.log.error(`Failed to createStreamWithLock:`, error);\n }\n finally {\n this.ongoingCreation.delete(peerId);\n }\n return;\n }\n handlePeerUpdateStreamPool = (evt) => {\n const { peer } = evt.detail;\n if (!peer.protocols.includes(this.multicodec)) {\n return;\n }\n const stream = this.getOpenStreamForCodec(peer.id);\n if (stream) {\n return;\n }\n this.scheduleNewStream(peer);\n };\n scheduleNewStream(peer) {\n this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);\n // abandon previous attempt\n if (this.streamPool.has(peer.id.toString())) {\n this.streamPool.delete(peer.id.toString());\n }\n this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));\n }\n getOpenStreamForCodec(peerId) {\n const connections = this.getConnections(peerId);\n const connection = selectOpenConnection(connections);\n if (!connection) {\n return;\n }\n const stream = connection.streams.find((s) => s.protocol === this.multicodec);\n if (!stream) {\n return;\n }\n const isStreamUnusable = [\"done\", \"closed\", \"closing\"].includes(stream.writeStatus || \"\");\n if (isStreamUnusable || this.isStreamLocked(stream)) {\n return;\n }\n return stream;\n }\n lockStream(peerId, stream) {\n this.log.info(`Locking stream for peerId:${peerId}\\tstreamId:${stream.id}`);\n stream.metadata[STREAM_LOCK_KEY] = true;\n }\n isStreamLocked(stream) {\n return !!stream.metadata[STREAM_LOCK_KEY];\n }\n}\n//# sourceMappingURL=stream_manager.js.map","import { StreamManager } from \"./stream_manager/index.js\";\n/**\n * A class with predefined helpers, to be used as a base to implement Waku\n * Protocols.\n */\nexport class BaseProtocol {\n multicodec;\n components;\n pubsubTopics;\n addLibp2pEventListener;\n removeLibp2pEventListener;\n streamManager;\n constructor(multicodec, components, pubsubTopics) {\n this.multicodec = multicodec;\n this.components = components;\n this.pubsubTopics = pubsubTopics;\n this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);\n this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);\n this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);\n }\n async getStream(peer) {\n return this.streamManager.getStream(peer);\n }\n}\n//# sourceMappingURL=base_protocol.js.map","import { proto_peer_exchange as proto } from \"@waku/proto\";\n/**\n * PeerExchangeRPC represents a message conforming to the Waku Peer Exchange protocol\n */\nexport class PeerExchangeRPC {\n proto;\n constructor(proto) {\n this.proto = proto;\n }\n static createRequest(params) {\n const { numPeers } = params;\n return new PeerExchangeRPC({\n query: {\n numPeers: numPeers\n },\n response: undefined\n });\n }\n /**\n * Encode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n encode() {\n return proto.PeerExchangeRPC.encode(this.proto);\n }\n /**\n * Decode the current PeerExchangeRPC request to bytes\n * @returns Uint8Array\n */\n static decode(bytes) {\n const res = proto.PeerExchangeRPC.decode(bytes);\n return new PeerExchangeRPC(res);\n }\n get query() {\n return this.proto.query;\n }\n get response() {\n return this.proto.response;\n }\n}\n//# sourceMappingURL=rpc.js.map","import { BaseProtocol } from \"@waku/core/lib/base_protocol\";\nimport { EnrDecoder } from \"@waku/enr\";\nimport { ProtocolError } from \"@waku/interfaces\";\nimport { isDefined } from \"@waku/utils\";\nimport { Logger } from \"@waku/utils\";\nimport all from \"it-all\";\nimport * as lp from \"it-length-prefixed\";\nimport { pipe } from \"it-pipe\";\nimport { Uint8ArrayList } from \"uint8arraylist\";\nimport { PeerExchangeRPC } from \"./rpc.js\";\nexport const PeerExchangeCodec = \"/vac/waku/peer-exchange/2.0.0-alpha1\";\nconst log = new Logger(\"peer-exchange\");\n/**\n * Implementation of the Peer Exchange protocol (https://rfc.vac.dev/spec/34/)\n */\nexport class WakuPeerExchange extends BaseProtocol {\n /**\n * @param components - libp2p components\n */\n constructor(components, pubsubTopics) {\n super(PeerExchangeCodec, components, pubsubTopics);\n }\n /**\n * Make a peer exchange query to a peer\n */\n async query(params) {\n const { numPeers, peerId } = params;\n const rpcQuery = PeerExchangeRPC.createRequest({\n numPeers: BigInt(numPeers)\n });\n const peer = await this.components.peerStore.get(peerId);\n if (!peer) {\n return {\n peerInfos: null,\n error: ProtocolError.NO_PEER_AVAILABLE\n };\n }\n let stream;\n try {\n stream = await this.getStream(peer);\n }\n catch (err) {\n log.error(\"Failed to get stream\", err);\n return {\n peerInfos: null,\n error: ProtocolError.NO_STREAM_AVAILABLE\n };\n }\n const res = await pipe([rpcQuery.encode()], lp.encode, stream, lp.decode, async (source) => await all(source));\n try {\n const bytes = new Uint8ArrayList();\n res.forEach((chunk) => {\n bytes.append(chunk);\n });\n const { response } = PeerExchangeRPC.decode(bytes);\n if (!response) {\n log.error(\"PeerExchangeRPC message did not contains a `response` field\");\n return {\n peerInfos: null,\n error: ProtocolError.EMPTY_PAYLOAD\n };\n }\n const peerInfos = await Promise.all(response.peerInfos\n .map((peerInfo) => peerInfo.enr)\n .filter(isDefined)\n .map(async (enr) => {\n return { ENR: await EnrDecoder.fromRLP(enr) };\n }));\n return {\n peerInfos,\n error: null\n };\n }\n catch (err) {\n log.error(\"Failed to decode push reply\", err);\n return {\n peerInfos: null,\n error: ProtocolError.DECODE_FAILED\n };\n }\n }\n}\n/**\n *\n * @returns A function that creates a new peer exchange protocol\n */\nexport function wakuPeerExchange(pubsubTopics) {\n return (components) => new WakuPeerExchange(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerDiscoverySymbol as symbol } from \"@libp2p/interface\";\nimport { Tags } from \"@waku/interfaces\";\nimport { decodeRelayShard, encodeRelayShard, Logger } from \"@waku/utils\";\nimport { PeerExchangeCodec, WakuPeerExchange } from \"./waku_peer_exchange.js\";\nconst log = new Logger(\"peer-exchange-discovery\");\nconst DEFAULT_PEER_EXCHANGE_REQUEST_NODES = 10;\nconst DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS = 10 * 1000;\nconst DEFAULT_MAX_RETRIES = 3;\nexport const DEFAULT_PEER_EXCHANGE_TAG_NAME = Tags.PEER_EXCHANGE;\nconst DEFAULT_PEER_EXCHANGE_TAG_VALUE = 50;\nconst DEFAULT_PEER_EXCHANGE_TAG_TTL = 100_000_000;\nexport class PeerExchangeDiscovery extends TypedEventEmitter {\n components;\n peerExchange;\n options;\n isStarted;\n queryingPeers = new Set();\n queryAttempts = new Map();\n handleDiscoveredPeer = (event) => {\n const { protocols, peerId } = event.detail;\n if (!protocols.includes(PeerExchangeCodec) ||\n this.queryingPeers.has(peerId.toString()))\n return;\n this.queryingPeers.add(peerId.toString());\n this.startRecurringQueries(peerId).catch((error) => log.error(`Error querying peer ${error}`));\n };\n constructor(components, pubsubTopics, options = {}) {\n super();\n this.components = components;\n this.peerExchange = new WakuPeerExchange(components, pubsubTopics);\n this.options = options;\n this.isStarted = false;\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted) {\n return;\n }\n this.dispatchEvent(new CustomEvent(\"waku:peer-exchange:started\", { detail: true }));\n log.info(\"Starting peer exchange node discovery, discovering peers\");\n // might be better to use \"peer:identify\" or \"peer:update\"\n this.components.events.addEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n /**\n * Remove event listener\n */\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping peer exchange node discovery\");\n this.isStarted = false;\n this.queryingPeers.clear();\n this.components.events.removeEventListener(\"peer:identify\", this.handleDiscoveredPeer);\n }\n get [symbol]() {\n return true;\n }\n get [Symbol.toStringTag]() {\n return \"@waku/peer-exchange\";\n }\n startRecurringQueries = async (peerId) => {\n const peerIdStr = peerId.toString();\n const { queryInterval = DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS, maxRetries = DEFAULT_MAX_RETRIES } = this.options;\n log.info(`Querying peer: ${peerIdStr} (attempt ${this.queryAttempts.get(peerIdStr) ?? 1})`);\n await this.query(peerId);\n const currentAttempt = this.queryAttempts.get(peerIdStr) ?? 1;\n if (currentAttempt > maxRetries) {\n this.abortQueriesForPeer(peerIdStr);\n return;\n }\n setTimeout(() => {\n this.queryAttempts.set(peerIdStr, currentAttempt + 1);\n this.startRecurringQueries(peerId).catch((error) => {\n log.error(`Error in startRecurringQueries: ${error}`);\n });\n }, queryInterval * currentAttempt);\n };\n async query(peerId) {\n const { error, peerInfos } = await this.peerExchange.query({\n numPeers: DEFAULT_PEER_EXCHANGE_REQUEST_NODES,\n peerId\n });\n if (error) {\n log.error(\"Peer exchange query failed\", error);\n return { error, peerInfos: null };\n }\n for (const _peerInfo of peerInfos) {\n const { ENR } = _peerInfo;\n if (!ENR) {\n log.warn(\"No ENR in peerInfo object, skipping\");\n continue;\n }\n const { peerId, peerInfo, shardInfo } = ENR;\n if (!peerId || !peerInfo) {\n continue;\n }\n const hasPeer = await this.components.peerStore.has(peerId);\n if (hasPeer) {\n const { hasMultiaddrDiff, hasShardDiff } = await this.checkPeerInfoDiff(peerInfo, shardInfo);\n if (hasMultiaddrDiff || hasShardDiff) {\n log.info(`Peer ${peerId.toString()} has updated multiaddrs or shardInfo, updating`);\n if (hasMultiaddrDiff) {\n log.info(`Peer ${peerId.toString()} has updated multiaddrs, updating`);\n await this.components.peerStore.patch(peerId, {\n multiaddrs: peerInfo.multiaddrs\n });\n }\n if (hasShardDiff && shardInfo) {\n log.info(`Peer ${peerId.toString()} has updated shardInfo, updating`);\n await this.components.peerStore.merge(peerId, {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n });\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n }));\n }\n continue;\n }\n }\n // update the tags for the peer\n await this.components.peerStore.save(peerId, {\n tags: {\n [DEFAULT_PEER_EXCHANGE_TAG_NAME]: {\n value: this.options.tagValue ?? DEFAULT_PEER_EXCHANGE_TAG_VALUE,\n ttl: this.options.tagTTL ?? DEFAULT_PEER_EXCHANGE_TAG_TTL\n }\n },\n ...(shardInfo && {\n metadata: {\n shardInfo: encodeRelayShard(shardInfo)\n }\n }),\n ...(peerInfo.multiaddrs && {\n multiaddrs: peerInfo.multiaddrs\n })\n });\n log.info(`Discovered peer: ${peerId.toString()}`);\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: peerInfo.multiaddrs\n }\n }));\n }\n return { error: null, peerInfos };\n }\n abortQueriesForPeer(peerIdStr) {\n log.info(`Aborting queries for peer: ${peerIdStr}`);\n this.queryingPeers.delete(peerIdStr);\n this.queryAttempts.delete(peerIdStr);\n }\n async checkPeerInfoDiff(peerInfo, shardInfo) {\n const { id: peerId } = peerInfo;\n const peer = await this.components.peerStore.get(peerId);\n const existingMultiaddrs = peer.addresses.map((a) => a.multiaddr.toString());\n const newMultiaddrs = peerInfo.multiaddrs.map((ma) => ma.toString());\n const hasMultiaddrDiff = existingMultiaddrs.some((ma) => !newMultiaddrs.includes(ma));\n let hasShardDiff = false;\n const existingShardInfoBytes = peer.metadata.get(\"shardInfo\");\n if (existingShardInfoBytes) {\n const existingShardInfo = decodeRelayShard(existingShardInfoBytes);\n if (existingShardInfo || shardInfo) {\n hasShardDiff =\n existingShardInfo.clusterId !== shardInfo?.clusterId ||\n existingShardInfo.shards.some((shard) => !shardInfo?.shards.includes(shard));\n }\n }\n return { hasMultiaddrDiff, hasShardDiff };\n }\n}\nexport function wakuPeerExchangeDiscovery(pubsubTopics) {\n return (components) => new PeerExchangeDiscovery(components, pubsubTopics);\n}\n//# sourceMappingURL=waku_peer_exchange_discovery.js.map","import { TypedEventEmitter } from \"@libp2p/interface\";\nimport { peerIdFromString } from \"@libp2p/peer-id\";\nimport { multiaddr } from \"@multiformats/multiaddr\";\nimport { Tags } from \"@waku/interfaces\";\nimport { getWsMultiaddrFromMultiaddrs, Logger } from \"@waku/utils\";\nconst log = new Logger(\"peer-exchange-discovery\");\nexport const DEFAULT_LOCAL_TAG_NAME = Tags.LOCAL;\nconst DEFAULT_LOCAL_TAG_VALUE = 50;\nconst DEFAULT_LOCAL_TAG_TTL = 100_000_000;\nexport class LocalPeerCacheDiscovery extends TypedEventEmitter {\n components;\n options;\n isStarted;\n peers = [];\n constructor(components, options) {\n super();\n this.components = components;\n this.options = options;\n this.isStarted = false;\n this.peers = this.getPeersFromLocalStorage();\n }\n get [Symbol.toStringTag]() {\n return \"@waku/local-peer-cache-discovery\";\n }\n async start() {\n if (this.isStarted)\n return;\n log.info(\"Starting Local Storage Discovery\");\n this.components.events.addEventListener(\"peer:identify\", this.handleNewPeers);\n for (const { id: idStr, address } of this.peers) {\n const peerId = peerIdFromString(idStr);\n if (await this.components.peerStore.has(peerId))\n continue;\n await this.components.peerStore.save(peerId, {\n multiaddrs: [multiaddr(address)],\n tags: {\n [this.options?.tagName ?? DEFAULT_LOCAL_TAG_NAME]: {\n value: this.options?.tagValue ?? DEFAULT_LOCAL_TAG_VALUE,\n ttl: this.options?.tagTTL ?? DEFAULT_LOCAL_TAG_TTL\n }\n }\n });\n this.dispatchEvent(new CustomEvent(\"peer\", {\n detail: {\n id: peerId,\n multiaddrs: [multiaddr(address)]\n }\n }));\n }\n log.info(`Discovered ${this.peers.length} peers`);\n this.isStarted = true;\n }\n stop() {\n if (!this.isStarted)\n return;\n log.info(\"Stopping Local Storage Discovery\");\n this.components.events.removeEventListener(\"peer:identify\", this.handleNewPeers);\n this.isStarted = false;\n this.savePeersToLocalStorage();\n }\n handleNewPeers = (event) => {\n const { peerId, listenAddrs } = event.detail;\n const websocketMultiaddr = getWsMultiaddrFromMultiaddrs(listenAddrs);\n const localStoragePeers = this.getPeersFromLocalStorage();\n const existingPeerIndex = localStoragePeers.findIndex((_peer) => _peer.id === peerId.toString());\n if (existingPeerIndex >= 0) {\n localStoragePeers[existingPeerIndex].address =\n websocketMultiaddr.toString();\n }\n else {\n localStoragePeers.push({\n id: peerId.toString(),\n address: websocketMultiaddr.toString()\n });\n }\n this.peers = localStoragePeers;\n this.savePeersToLocalStorage();\n };\n getPeersFromLocalStorage() {\n try {\n const storedPeersData = localStorage.getItem(\"waku:peers\");\n if (!storedPeersData)\n return [];\n const peers = JSON.parse(storedPeersData);\n return peers.filter(isValidStoredPeer);\n }\n catch (error) {\n log.error(\"Error parsing peers from local storage:\", error);\n return [];\n }\n }\n savePeersToLocalStorage() {\n try {\n localStorage.setItem(\"waku:peers\", JSON.stringify(this.peers));\n }\n catch (error) {\n log.error(\"Error saving peers to local storage:\", error);\n }\n }\n}\nfunction isValidStoredPeer(peer) {\n return (peer &&\n typeof peer === \"object\" &&\n typeof peer.id === \"string\" &&\n typeof peer.address === \"string\");\n}\nexport function wakuLocalPeerCacheDiscovery() {\n return (components, options) => new LocalPeerCacheDiscovery(components, options);\n}\n//# sourceMappingURL=index.js.map","export * from \"./is_defined.js\";\nexport * from \"./random_subset.js\";\nexport * from \"./group_by.js\";\nexport * from \"./to_async_iterator.js\";\nexport * from \"./is_size_valid.js\";\nexport * from \"./sharding/index.js\";\nexport * from \"./push_or_init_map.js\";\nexport * from \"./relay_shard_codec.js\";\nexport * from \"./delay.js\";\nexport function removeItemFromArray(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n }\n return arr;\n}\nexport function getWsMultiaddrFromMultiaddrs(addresses) {\n const wsMultiaddr = addresses.find((addr) => addr.toString().includes(\"ws\") || addr.toString().includes(\"wss\"));\n if (!wsMultiaddr) {\n throw new Error(\"No ws multiaddr found in the given addresses\");\n }\n return wsMultiaddr;\n}\n//# sourceMappingURL=index.js.map","import { noise } from \"@chainsafe/libp2p-noise\";\nimport { bootstrap } from \"@libp2p/bootstrap\";\nimport { identify } from \"@libp2p/identify\";\nimport { mplex } from \"@libp2p/mplex\";\nimport { ping } from \"@libp2p/ping\";\nimport { webSockets } from \"@libp2p/websockets\";\nimport { all as filterAll, wss } from \"@libp2p/websockets/filters\";\nimport { wakuMetadata } from \"@waku/core\";\nimport { DefaultNetworkConfig } from \"@waku/interfaces\";\nimport { derivePubsubTopicsFromNetworkConfig, Logger } from \"@waku/utils\";\nimport { createLibp2p } from \"libp2p\";\nimport { defaultPeerDiscoveries } from \"./discovery.js\";\nconst log = new Logger(\"sdk:create\");\nconst DefaultUserAgent = \"js-waku\";\nconst DefaultPingMaxInboundStreams = 10;\nexport async function defaultLibp2p(pubsubTopics, options, userAgent) {\n if (!options?.hideWebSocketInfo && process?.env?.NODE_ENV !== \"test\") {\n /* eslint-disable no-console */\n console.info(\"%cIgnore WebSocket connection failures\", \"background: gray; color: white; font-size: x-large\");\n console.info(\"%cWaku tries to discover peers and some of them are expected to fail\", \"background: gray; color: white; font-size: x-large\");\n /* eslint-enable no-console */\n }\n const metadataService = pubsubTopics\n ? { metadata: wakuMetadata(pubsubTopics) }\n : {};\n const filter = options?.filterMultiaddrs === false || process?.env?.NODE_ENV === \"test\"\n ? filterAll\n : wss;\n return createLibp2p({\n transports: [webSockets({ filter: filter })],\n streamMuxers: [mplex()],\n connectionEncrypters: [noise()],\n ...options,\n services: {\n identify: identify({\n agentVersion: userAgent ?? DefaultUserAgent\n }),\n ping: ping({\n maxInboundStreams: options?.pingMaxInboundStreams ?? DefaultPingMaxInboundStreams\n }),\n ...metadataService,\n ...options?.services\n }\n }); // TODO: make libp2p include it;\n}\nexport async function createLibp2pAndUpdateOptions(options) {\n const { networkConfig } = options;\n const pubsubTopics = derivePubsubTopicsFromNetworkConfig(networkConfig ?? DefaultNetworkConfig);\n log.info(\"Creating Waku node with pubsub topics\", pubsubTopics);\n const libp2pOptions = options?.libp2p ?? {};\n const peerDiscovery = libp2pOptions.peerDiscovery ?? [];\n if (options?.defaultBootstrap) {\n peerDiscovery.push(...defaultPeerDiscoveries(pubsubTopics));\n }\n if (options?.bootstrapPeers) {\n peerDiscovery.push(bootstrap({ list: options.bootstrapPeers }));\n }\n libp2pOptions.peerDiscovery = peerDiscovery;\n const libp2p = await defaultLibp2p(pubsubTopics, libp2pOptions, options?.userAgent);\n return { libp2p, pubsubTopics };\n}\n//# sourceMappingURL=libp2p.js.map","/**\n * @packageDocumentation\n *\n * Use the `createLibp2p` function to create a libp2p node.\n *\n * @example\n *\n * ```typescript\n * import { createLibp2p } from 'libp2p'\n *\n * const node = await createLibp2p({\n * // ...other options\n * })\n * ```\n */\nimport { generateKeyPair } from '@libp2p/crypto/keys';\nimport { peerIdFromPrivateKey } from '@libp2p/peer-id';\nimport { validateConfig } from './config.js';\nimport { Libp2p as Libp2pClass } from './libp2p.js';\n/**\n * Returns a new instance of the Libp2p interface, generating a new PeerId\n * if one is not passed as part of the options.\n *\n * The node will be started unless `start: false` is passed as an option.\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { tcp } from '@libp2p/tcp'\n * import { mplex } from '@libp2p/mplex'\n * import { noise } from '@chainsafe/libp2p-noise'\n * import { yamux } from '@chainsafe/libp2p-yamux'\n *\n * // specify options\n * const options = {\n * transports: [tcp()],\n * streamMuxers: [yamux(), mplex()],\n * connectionEncrypters: [noise()]\n * }\n *\n * // create libp2p\n * const libp2p = await createLibp2p(options)\n * ```\n */\nexport async function createLibp2p(options = {}) {\n options.privateKey ??= await generateKeyPair('Ed25519');\n const node = new Libp2pClass({\n ...await validateConfig(options),\n peerId: peerIdFromPrivateKey(options.privateKey)\n });\n if (options.start !== false) {\n await node.start();\n }\n return node;\n}\n//# sourceMappingURL=index.js.map","import { WakuNode } from \"../waku/index.js\";\nimport { createLibp2pAndUpdateOptions } from \"./libp2p.js\";\n/**\n * Create a Waku node that uses Waku Light Push, Filter and Store to send and\n * receive messages, enabling low resource consumption.\n * Uses Waku Filter V2 by default.\n */\nexport async function createLightNode(options = {}) {\n const { libp2p, pubsubTopics } = await createLibp2pAndUpdateOptions(options);\n return new WakuNode(pubsubTopics, options, libp2p, {\n store: true,\n lightpush: true,\n filter: true\n });\n}\n//# sourceMappingURL=create.js.map","export function isStaticSharding(config) {\n return (\"clusterId\" in config && \"shards\" in config && !(\"contentTopics\" in config));\n}\nexport function isAutoSharding(config) {\n return \"contentTopics\" in config;\n}\n//# sourceMappingURL=type_guards.js.map","import { enrTree, wakuDnsDiscovery, wakuLocalPeerCacheDiscovery, wakuPeerExchangeDiscovery } from \"@waku/discovery\";\nexport function defaultPeerDiscoveries(pubsubTopics) {\n const dnsEnrTrees = [enrTree[\"SANDBOX\"], enrTree[\"TEST\"]];\n const discoveries = [\n wakuDnsDiscovery(dnsEnrTrees),\n wakuLocalPeerCacheDiscovery(),\n wakuPeerExchangeDiscovery(pubsubTopics)\n ];\n return discoveries;\n}\n//# sourceMappingURL=discovery.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var TelemetryType;\n(function (TelemetryType) {\n TelemetryType[\"LIGHT_PUSH_FILTER\"] = \"LightPushFilter\";\n})(TelemetryType || (TelemetryType = {}));\nvar TelemetryClient = /** @class */ (function () {\n function TelemetryClient(url, intervalPeriod) {\n if (intervalPeriod === void 0) { intervalPeriod = 5000; }\n this.url = url;\n this.intervalPeriod = intervalPeriod;\n this.queue = [];\n this.intervalId = null;\n this.requestId = 0;\n }\n TelemetryClient.prototype.push = function (messages) {\n var _a;\n (_a = this.queue).push.apply(_a, messages);\n };\n TelemetryClient.prototype.start = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n return __generator(this, function (_a) {\n if (!this.intervalId) {\n this.intervalId = setInterval(function () { return __awaiter(_this, void 0, void 0, function () {\n var success;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.queue.length > 0)) return [3 /*break*/, 2];\n return [4 /*yield*/, this.send(this.queue)];\n case 1:\n success = _a.sent();\n if (success) {\n console.log(\"Sent \", this.queue.length, \" telemetry logs\");\n this.queue = [];\n }\n _a.label = 2;\n case 2: return [2 /*return*/];\n }\n });\n }); }, this.intervalPeriod);\n }\n return [2 /*return*/];\n });\n });\n };\n TelemetryClient.prototype.stop = function () {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n this.intervalId = null;\n }\n };\n TelemetryClient.prototype.send = function (messages) {\n return __awaiter(this, void 0, void 0, function () {\n var telemetryRequests, res, e_1;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!window.location.hostname.includes(\"lab.waku.org\")) {\n return [2 /*return*/];\n }\n telemetryRequests = messages.map(function (message) { return ({\n id: ++_this.requestId,\n telemetryType: message.type.toString(),\n telemetryData: message\n }); });\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, fetch(this.url, {\n method: \"POST\",\n body: JSON.stringify(telemetryRequests),\n })];\n case 2:\n res = _a.sent();\n if (res.status !== 201) {\n console.log(\"DEBUG: Error sending messages to telemetry service: \", res.status, res.statusText, res.json);\n return [2 /*return*/, false];\n }\n return [2 /*return*/, true];\n case 3:\n e_1 = _a.sent();\n console.log(\"DEBUG: Error sending messages to telemetry service\", e_1);\n return [2 /*return*/, false];\n case 4: return [2 /*return*/];\n }\n });\n });\n };\n return TelemetryClient;\n}());\nexport { TelemetryClient };\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nexport var generateRandomNumber = function () {\n return Math.floor(Math.random() * 1000000);\n};\nexport var sha256 = function (number) { return __awaiter(void 0, void 0, void 0, function () {\n var encoder, data, buffer;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n encoder = new TextEncoder();\n data = encoder.encode(number.toString());\n return [4 /*yield*/, crypto.subtle.digest(\"SHA-256\", data)];\n case 1:\n buffer = _a.sent();\n return [2 /*return*/, Array.from(new Uint8Array(buffer))\n .map(function (b) { return b.toString(16).padStart(2, \"0\"); })\n .join(\"\")];\n }\n });\n}); };\nvar DEFAULT_EXTRA_DATA = { sdk: \"0.0.29-rc\" };\nexport var DEFAULT_EXTRA_DATA_STR = JSON.stringify(DEFAULT_EXTRA_DATA);\nexport var buildExtraData = function (node, peerId) { return __awaiter(void 0, void 0, void 0, function () {\n var extraData, peer, websocket;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n extraData = __assign({}, DEFAULT_EXTRA_DATA);\n return [4 /*yield*/, node.libp2p.peerStore.all()];\n case 1:\n peer = (_a.sent()).find(function (p) { return p.id.toString() === peerId; });\n if (!peer || peerId === node.libp2p.peerId.toString()) {\n return [2 /*return*/, JSON.stringify(extraData)];\n }\n websocket = peer\n .addresses\n .map(function (addr) { return addr.multiaddr.toString(); })\n .some(function (addr) { return addr.includes(\"ws\") || addr.includes(\"wss\"); });\n return [2 /*return*/, JSON.stringify(__assign(__assign({}, extraData), { peerId: peerId, websocket: websocket, enabledProtocols: peer.protocols }))];\n }\n });\n}); };\n","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { createLightNode, createEncoder, createDecoder, utils, } from \"@waku/sdk\";\nimport { generateKeyPairFromSeed } from \"@libp2p/crypto/keys\";\nimport { fromString } from \"uint8arrays\";\nimport { Type, Field } from \"protobufjs\";\nimport { TelemetryClient, TelemetryType, } from \"./telemetry_client\";\nimport { generateRandomNumber, sha256, buildExtraData, } from \"./util\";\nvar DEFAULT_CONTENT_TOPIC = \"/js-waku-examples/1/message-ratio/utf8\";\nvar DEFAULT_PUBSUB_TOPIC = utils.contentTopicToPubsubTopic(DEFAULT_CONTENT_TOPIC);\nvar TELEMETRY_URL = process.env.TELEMETRY_URL || \"http://localhost:8080/waku-metrics\";\nvar ProtoSequencedMessage = new Type(\"SequencedMessage\")\n .add(new Field(\"hash\", 1, \"string\"))\n .add(new Field(\"total\", 2, \"uint64\"))\n .add(new Field(\"index\", 3, \"uint64\"))\n .add(new Field(\"sender\", 4, \"string\"));\nvar sequenceCompletedEvent = new CustomEvent(\"sequenceCompleted\");\nvar messageSentEvent = new CustomEvent(\"messageSent\");\nvar messageReceivedEvent = new CustomEvent(\"messageReceived\");\nfunction wakuNode() {\n return __awaiter(this, void 0, void 0, function () {\n var seed, privateKey;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n seed = localStorage.getItem(\"seed\");\n if (!!seed) return [3 /*break*/, 2];\n return [4 /*yield*/, sha256(generateRandomNumber())];\n case 1:\n seed = (_a.sent()).slice(0, 32);\n localStorage.setItem(\"seed\", seed);\n _a.label = 2;\n case 2: return [4 /*yield*/, generateKeyPairFromSeed(\"Ed25519\", fromString(seed))];\n case 3:\n privateKey = _a.sent();\n return [2 /*return*/, createLightNode({\n networkConfig: {\n contentTopics: [DEFAULT_CONTENT_TOPIC],\n },\n numPeersToUse: 2,\n defaultBootstrap: true,\n libp2p: {\n privateKey: privateKey,\n },\n })];\n }\n });\n });\n}\nexport function app(telemetryClient) {\n return __awaiter(this, void 0, void 0, function () {\n var node, peerId, encoder, startLightPushSequence, startFilterSubscription;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, wakuNode()];\n case 1:\n node = _a.sent();\n window.waku = node;\n console.log(\"DEBUG: your peer ID is:\", node.libp2p.peerId.toString());\n return [4 /*yield*/, node.start()];\n case 2:\n _a.sent();\n return [4 /*yield*/, node.waitForPeers()];\n case 3:\n _a.sent();\n peerId = node.libp2p.peerId.toString();\n encoder = createEncoder({\n contentTopic: DEFAULT_CONTENT_TOPIC,\n });\n node.libp2p.addEventListener(\"peer:discovery\", function (event) { return __awaiter(_this, void 0, void 0, function () {\n var discoveredPeerId, timestamp, extraData, hash;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n discoveredPeerId = event.detail.id.toString();\n timestamp = Math.floor(new Date().getTime() / 1000);\n return [4 /*yield*/, buildExtraData(node, discoveredPeerId)];\n case 1:\n extraData = _a.sent();\n return [4 /*yield*/, sha256(\"\".concat(peerId, \"-\").concat(discoveredPeerId, \"-\").concat(timestamp))];\n case 2:\n hash = _a.sent();\n telemetryClient.push([\n {\n type: TelemetryType.LIGHT_PUSH_FILTER,\n protocol: \"discovery\",\n timestamp: timestamp,\n createdAt: timestamp,\n seenTimestamp: timestamp,\n peerId: peerId,\n contentTopic: DEFAULT_CONTENT_TOPIC,\n pubsubTopic: DEFAULT_PUBSUB_TOPIC,\n ephemeral: false,\n messageHash: hash,\n errorMessage: \"\",\n extraData: extraData,\n },\n ]);\n return [2 /*return*/];\n }\n });\n }); });\n startLightPushSequence = function (numMessages_1) {\n var args_1 = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args_1[_i - 1] = arguments[_i];\n }\n return __awaiter(_this, __spreadArray([numMessages_1], args_1, true), void 0, function (numMessages, period) {\n var sequenceHash, sequenceTotal, sequenceIndex, sendMessage;\n var _this = this;\n if (period === void 0) { period = 3000; }\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, sha256(generateRandomNumber())];\n case 1:\n sequenceHash = _a.sent();\n sequenceTotal = numMessages;\n sequenceIndex = 0;\n sendMessage = function () { return __awaiter(_this, void 0, void 0, function () {\n var messageHash, timestamp, message, payload, result, error_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 3, , 4]);\n return [4 /*yield*/, sha256(\"\".concat(sequenceHash, \"-\").concat(sequenceIndex, \"-\").concat(sequenceTotal))];\n case 1:\n messageHash = _a.sent();\n timestamp = Math.floor(new Date().getTime() / 1000);\n message = ProtoSequencedMessage.create({\n hash: messageHash,\n total: sequenceTotal,\n index: sequenceIndex,\n sender: peerId,\n });\n payload = ProtoSequencedMessage.encode(message).finish();\n return [4 /*yield*/, node.lightPush.send(encoder, {\n payload: payload,\n timestamp: new Date(),\n }, { autoRetry: true })];\n case 2:\n result = _a.sent();\n console.log(\"DEBUG: light push successes: \", result.successes.length);\n console.log(\"DEBUG: light push failures: \", result.failures.length);\n // Increment sequence\n sequenceIndex++;\n if (sequenceIndex < sequenceTotal) {\n setTimeout(sendMessage, period); // Schedule the next send\n }\n else {\n document.dispatchEvent(sequenceCompletedEvent);\n }\n return [3 /*break*/, 4];\n case 3:\n error_1 = _a.sent();\n console.error(\"DEBUG: Error sending message\", error_1);\n return [3 /*break*/, 4];\n case 4: return [2 /*return*/];\n }\n });\n }); };\n sendMessage(); // Start the recursive sending\n return [2 /*return*/];\n }\n });\n });\n };\n startFilterSubscription = function () { return __awaiter(_this, void 0, void 0, function () {\n var decoder, subscriptionCallback;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n decoder = createDecoder(DEFAULT_CONTENT_TOPIC);\n subscriptionCallback = function (message) { return __awaiter(_this, void 0, void 0, function () {\n var decodedMessage, timestamp, messageElement;\n return __generator(this, function (_a) {\n decodedMessage = ProtoSequencedMessage.decode(message.payload);\n if (decodedMessage.sender === peerId) {\n return [2 /*return*/];\n }\n timestamp = Math.floor(new Date().getTime() / 1000);\n messageElement = document.createElement(\"div\");\n messageElement.textContent = \"Message: \".concat(decodedMessage.hash);\n document.dispatchEvent(messageReceivedEvent);\n return [2 /*return*/];\n });\n }); };\n return [4 /*yield*/, node.filter.subscribe(decoder, subscriptionCallback)];\n case 1:\n _a.sent();\n return [2 /*return*/];\n }\n });\n }); };\n return [2 /*return*/, {\n node: node,\n startLightPushSequence: startLightPushSequence,\n startFilterSubscription: startFilterSubscription,\n }];\n }\n });\n });\n}\n(function () { return __awaiter(void 0, void 0, void 0, function () {\n var telemetryClient, _a, node, startLightPushSequence, startFilterSubscription;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n telemetryClient = new TelemetryClient(TELEMETRY_URL, 5000);\n return [4 /*yield*/, app(telemetryClient)];\n case 1:\n _a = _b.sent(), node = _a.node, startLightPushSequence = _a.startLightPushSequence, startFilterSubscription = _a.startFilterSubscription;\n startFilterSubscription();\n document.addEventListener(sequenceCompletedEvent.type, function () {\n return startLightPushSequence(10, 3000);\n });\n startLightPushSequence(10, 3000);\n return [2 /*return*/];\n }\n });\n}); })();\n"],"names":["module","exports","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","charAt","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","undefined","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","inquire","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","Float32Array","f32","f8b","le","writeFloat_f32_cpy","val","buf","pos","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","moduleName","mod","eval","e","path","isAbsolute","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","call","utf8","len","read","write","c1","c2","formatArgs","useColors","namespace","humanize","diff","color","lastC","match","save","namespaces","storage","setItem","removeItem","error","load","r","getItem","process","env","DEBUG","window","type","__nwjs","navigator","userAgent","toLowerCase","m","document","documentElement","style","WebkitAppearance","firebug","exception","table","parseInt","localStorage","localstorage","destroy","warned","warn","colors","debug","formatters","v","message","createDebug","prevTime","namespacesCache","enabledCache","enableOverride","enabled","self","curr","Date","ms","prev","coerce","unshift","format","formatter","selectColor","extend","defineProperty","enumerable","configurable","get","set","init","delimiter","newDebug","matchesTemplate","search","template","searchIndex","templateIndex","starIndex","matchIndex","default","stack","disable","names","skips","map","enable","trim","filter","Boolean","ns","name","skip","forEach","key","hash","abs","event_iterator_1","EventIterator","EventQueue","constructor","pullQueue","pushQueue","eventHandlers","isPaused","isStopped","resolution","done","placeholder","highWaterMark","highWater","stop","remove","fail","rejection","catch","then","removeCallback","Symbol","asyncIterator","next","result","lowWaterMark","lowWater","return","listen","queue","event","freeze","has","hasOwnProperty","Events","EE","context","once","addListener","emitter","TypeError","listener","_events","_eventsCount","clearEvent","create","__proto__","eventNames","events","getOwnPropertySymbols","concat","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","removeListener","removeAllListeners","prefixed","max","cache","_cache","update","clear","root","HI_BASE32_NO_NODE_JS","versions","node","global","COMMON_JS","HI_BASE32_NO_COMMON_JS","AMD","BASE32_ENCODE_CHAR","BASE32_DECODE_CHAR","blocks","throwInvalidUtf8","position","partial","substr","decodeAsBytes","base32Str","v1","v2","v3","v4","v5","v6","v7","v8","bytes","count","remain","asciiOnly","str","followingChars","toUtf8String","indexOf","input","notString","ArrayBuffer","encodeBytes","encodeAscii","code","encodeUtf8","asBytes","base32","electron","getPrototypeOf","INPUT_ERROR","WINDOW","JS_SHA3_NO_WINDOW","WEB_WORKER","JS_SHA3_NO_NODE_JS","JS_SHA3_NO_COMMON_JS","ARRAY_BUFFER","JS_SHA3_NO_ARRAY_BUFFER","HEX_CHARS","CSHAKE_PADDING","SHIFT","RC","BITS","SHAKE_BITS","OUTPUT_TYPES","CSHAKE_BYTEPAD","isArray","obj","isView","JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW","formatMessage","empty","cloneArray","array","newArray","createOutputMethod","bits","padding","outputType","Keccak","createShakeOutputMethod","outputBits","createCshakeOutputMethod","s","methods","createKmacOutputMethod","createOutputMethods","method","createMethod","algorithms","w","bytepad","Kmac","methodNames","algorithm","methodName","newMethodName","reset","finalized","block","blockCount","byteCount","outputBlocks","extraBytes","isString","lastByteIndex","f","x","right","o","encodeString","strs","paddingBytes","zeros","finalize","hex","arrayBuffer","Uint32Array","digest","h","c0","c3","c4","c5","c6","c7","c8","c9","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","b10","b11","b12","b13","b14","b15","b16","b17","b18","b19","b20","b21","b22","b23","b24","b25","b26","b27","b28","b29","b30","b31","b32","b33","b34","b35","b36","b37","b38","b39","b40","b41","b42","b43","b44","b45","b46","b47","b48","b49","isOptionObject","propertyIsEnumerable","object","writable","globalThis","defaultMergeOptions","concatArrays","ignoreUndefined","getEnumerableOwnPropertyKeys","symbols","symbol","clone","cloneOptionObject","mergeKeys","merged","config","merge","resultIndex","indices","k","includes","_","option","d","plural","msAbs","isPlural","exec","parseFloat","parse","isFinite","long","fmtShort","library","_validBytes","isInteger","_x86Multiply","_x86Rotl","_x86Fmix","_x64Add","_x64Multiply","_x64Rotl","_x64LeftShift","_x64Xor","_x64Fmix","x86","hash32","seed","inputValidation","remainder","h1","k1","hash128","h2","h3","h4","k2","k3","k4","x64","murmurHash3","Netmask","atob","chr","chr0","chrA","chra","ip2long","long2ip","ip","ref","substring","base","dmax","net","mask","maskLong","error1","bitmask","netLong","hostmask","first","last","broadcast","contains","lastLong","common","timeType","commonRe","json","nested","google","protobuf","Any","fields","type_url","id","Duration","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","kind","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","values","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","file","converter","Enum","util","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","fromObject","mtype","fieldsArray","safeProp","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","valuesById","low","high","unsigned","toNumber","arrayDefault","hasKs2","_fieldsArray","group","types","defaults","basic","packed","rfield","required","missing","wireType","mapKey","genTypePartial","optional","ReflectionObject","className","Namespace","comment","comments","valuesOptions","reserved","fromJSON","enm","toJSON","toJSONOptions","keepComments","add","isReservedId","isReservedName","allow_alias","Field","Type","ruleRe","isObject","defaultValue","Long","extensionField","declaringField","_packed","getOption","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","newBuffer","emptyObject","emptyArray","ctor","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","_configure","Type_","build","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","configure","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","_nestedArray","clearCache","addJSON","toArray","nestedArray","nestedJson","getEnum","setOptions","onAdd","onRemove","define","ptr","part","resolveAll","lookup","filterTypes","parentAlreadyChecked","found","lookupEnum","lookupService","Service_","Enum_","defineProperties","_handleAdd","_handleRemove","setParsedOption","propName","opt","find","newValue","setProperty","newOpt","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","preferTrailingComment","tn","alternateCommentMode","peek","cmnt","head","isProto3","applyCase","camelCase","illegal","insideTryCatch","line","readString","readValue","acceptTypeRef","parseNumber","readRanges","target","acceptStrings","parseId","dummy","ifBlock","parseOption","parseInlineOptions","acceptNegative","parsePackage","parseImport","whichImports","parseSyntax","parseCommon","parseType","parseEnum","service","commentText","parseMethod","parseService","reference","parseField","parseExtension","fnIf","fnElse","trailingLine","valueType","parseMapField","parseOneOf","extensions","endsWith","startsWith","lcFirst","ucFirst","parseGroup","parseEnumValue","isCustom","parseOptionValue","objectResult","lastValue","prevValue","simpleValue","LongBits","indexOutOfRange","writeLength","RangeError","create_array","Buffer","isBuffer","readLongVarint","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skipType","BufferReader_","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","deferred","files","SYNC","resolvePath","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","parsed","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","extendedType","sisterField","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","isReserved","q","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","unescape","lastCommentLine","stringDelim","subject","setComment","isLeading","lineEmpty","leading","commentOffset","lines","text","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","re","lastIndex","repeat","isDoc","isLeadingComment","expected","actual","ret","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","wrapper","originalThis","fork","ldelim","typeName","bake","safePropBackslashRe","safePropQuoteRe","toUpperCase","camelCaseRe","a","decorateRoot","decorateEnumIndex","dst","setProp","zero","zzEncode","zeroHash","from","fromString","toLong","fromHash","toHash","part0","part1","part2","src","newError","CustomError","captureStackTrace","pool","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","invalid","genVerifyKey","genVerifyValue","oneofProp","Op","noop","State","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength","BufferSourceConverter","isArrayBuffer","data","toArrayBuffer","byteOffset","toUint8Array","toView","isArrayBufferView","isBufferSource","isEqual","aView","bView","buffers","res","view","STRING_TYPE","HEX_REGEX","BASE64_REGEX","BASE64URL_REGEX","Utf8Converter","encodeURIComponent","uintArray","encodedString","decodeURIComponent","escape","Utf16Converter","littleEndian","dataView","DataView","getUint16","setUint16","Convert","isHex","isBase64","isBase64Url","ToString","enc","ToUtf8String","ToBinary","ToHex","ToBase64","ToBase64Url","FromString","FromUtf8String","FromBinary","FromHex","FromBase64","FromBase64Url","btoa","formatted","formatString","base64url","Base64Padding","DEFAULT_UTF8_ENCODING","stringLength","resultView","byte","hexString","ToUtf16String","FromUtf16String","padCount","RetryOperation","operation","timeouts","forever","retries","unref","maxRetryTime","opts","factor","minTimeout","maxTimeout","randomize","createTimeout","attempt","random","timeout","wrap","original","op","pop","retry","mainError","_originalTimeouts","_timeouts","_options","_maxRetryTime","_fn","_errors","_attempts","_operationTimeout","_operationTimeoutCb","_timeout","_operationStart","_timer","_cachedTimeouts","clearTimeout","currentTime","getTime","timeoutOps","try","errors","attempts","counts","mainErrorCount","__webpack_module_cache__","leafPrototypes","getProto","__webpack_require__","moduleId","cachedModule","__webpack_modules__","amdO","mode","__esModule","def","current","getOwnPropertyNames","definition","toStringTag","N1","N2","N3","N4","N5","N6","N7","MSB","REST","encodingLength","MAX_SAFE_INTEGER","encodeUint8Array","decodeUint8Array","encodeUint8ArrayList","decodeUint8ArrayList","d8b","MAX_SAFE_NUMBER_INTEGER","BigInt","MIN_SAFE_NUMBER_INTEGER","MIN_SAFE_INTEGER","toBigInt","fromBigInt","negative","TWO_32","readFixed32End","Uint8ArrayReader","int64Number","int64String","uint64Number","uint64String","sint64Number","sint64String","fixed64Number","fixed64String","sfixed64Number","sfixed64String","decodeMessage","codec","createReader","ALPHABET","BASE_MAP","xc","BASE","LEADER","FACTOR","iFACTOR","decodeUnsafe","psz","zeroes","b256","carry","it3","it4","vch","pbegin","pend","b58","it1","it2","Encoder","baseEncode","Decoder","baseDecode","prefixCodePoint","codePointAt","or","ComposedDecoder","decoders","left","Codec","baseX","alphabet","rfc4648","bitsPerChar","pad","out","codes","written","SyntaxError","base10","base16","base16upper","base2","alphabetBytesToChars","reduce","alphabetCharsToBytes","codePoint","base256emoji","byts","char","byt","base32upper","base32pad","base32padupper","base32hex","base32hexupper","base32hexpad","base32hexpadupper","base32z","base36","base36upper","base58btc","base58flickr","base64pad","base64urlpad","base8","identity","TextDecoder","TextEncoder","textEncoder","textDecoder","MSBALL","INT","MSB$1","REST$1","N8","N9","num","oldOffset","counter","encodeTo","int","sizeOffset","digestOffset","Digest","multihash","Hasher","sha","async","crypto","subtle","link","version","cid","toStringV0","baseCache","toStringV1","WeakMap","Map","CID","asCID","toV0","DAG_PB_CODE","SHA_256_CODE","createV0","toV1","createV1","equals","other","unknown","aa","bb","ii","for","encodeCID","cidSymbol","decodeFirst","specs","inspectBytes","prefixSize","multihashSize","multihashBytes","digestBytes","digestSize","multihashCode","initialBytes","parseCIDtoBytes","codeOffset","hashOffset","bases","createCodec","ascii","latin1","bufferPool","Uint8ArrayWriter","writeVarint32","super","encodeMessage","lengthDelimited","CODEC_TYPES","RateLimitProof","WakuMessage","FilterRequest","MessagePush","FilterRpc","TopicOnlyMessage","FilterSubscribeRequest","PushRequest","PushResponse","WakuMessageKeyValue","PeerInfo","PeerExchangeQuery","PeerExchangeResponse","WakuMetadataRequest","WakuMetadataResponse","enumeration","findValue","VARINT","enumValue","LENGTH_DELIMITED","MaxLengthError","MaxSizeError","isDefined","groupByContentTopic","groupedDecoders","decs","contentTopic","wait","_codec","proof","merkleRoot","epoch","shareX","shareY","nullifier","rlnIdentifier","tag","payload","timestamp","meta","rateLimitProof","ephemeral","limits","ContentFilter","subscribe","topic","contentFilters","contentFilters$","messages","messages$","requestId","FilterSubscribeType","__FilterSubscribeTypeValues","filterSubscribeType","pubsubTopic","contentTopics","SUBSCRIBER_PING","FilterSubscribeResponse","statusCode","statusDesc","wakuMessage","isSuccess","info","PushRpc","messageHash","StoreQueryRequest","includeData","timeStart","timeEnd","messageHashes","paginationCursor","paginationForward","paginationLimit","StoreQueryResponse","enr","numPeers","peerInfos","peerInfos$","PeerExchangeRPC","query","clusterId","shards","anumber","isSafeInteger","lengths","ahash","outputLen","blockLen","aexists","instance","checkFinished","destroyed","finished","createView","arr","rotr","word","toBytes","Hash","_cloneInto","hashCons","hashC","msg","tmp","bytesLength","getRandomValues","randomBytes","Maj","HashMD","padOffset","isLE","take","roundClean","digestInto","aoutput","fill","setBigUint64","_32n","_u32_max","wh","wl","setUint32","oview","outLen","state","to","SHA256_K","SHA256_IV","SHA256_W","SHA256","A","B","C","D","E","F","G","H","getUint32","W15","W2","s0","s1","T1","T2","Protocols","Tags","EPeersByDiscoveryEvents","EConnectionStateEvents","DNS_DISCOVERY_TAG","DefaultNetworkConfig","HealthStatus","bytesToUtf8","byteArrays","totalLength","acc","shardInfoToPubsubTopics","shardInfo","Set","contentTopicToPubsubTopic","application","pubsubTopicToSingleShardInfo","pubsubTopics","shard","pubsubTopicsToShardInfo","shardInfoSet","clusterIds","ensurePubsubTopicIsConfigured","configuredTopics","networkShards","generation","topicName","ensureValidContentTopic","dataview","getBigUint64","contentTopicToShardIndex","determinePubsubTopic","pubsubTopicShardInfo","singleShardInfoToPubsubTopic","decodeRelayShard","byteIndex","bitIndex","getUint8","numIndices","encodeRelayShard","setUint8","APP_NAME","Logger","_info","_warn","_error","createDebugNamespace","level","logger","OneMillion","DecodedMessage","proto","_rawTimestamp","metaSetter","toWire","toProtoObj","protoMessage","valueOf","createEncoder","fromWireToProtoObj","fromProtoObj","createDecoder","entry","arrays","output","findBufAndOffset","bufs","bufEnd","isUint8ArrayList","Uint8ArrayList","appendAll","iterator","append","prepend","prependAll","reverse","consume","trunc","beginInclusive","endExclusive","_subList","sublist","list","bufStart","sliceStartInBuf","sliceEndsInBuf","needle","M","rightmostPositions","Int32Array","lastPatIndex","getInt8","setInt8","getInt16","setInt16","getInt32","setInt32","getBigInt64","setBigInt64","getFloat32","setFloat32","getFloat64","setFloat64","fromUint8Arrays","thing","defaultEncoder","lengthLength","lengthBuf","encodeLength","lengthEncoder","maybeYield","single","InvalidMessageLengthError","InvalidDataLengthError","InvalidDataLengthLengthError","UnexpectedEOFError","ReadMode","defaultDecoder","LENGTH","dataLength","lengthDecoder","maxLengthLength","maxDataLength","dataLengthLength","onLength","DATA","onData","pDefer","promise","fromReader","FixedFIFO","top","btm","hwm","isEmpty","FIFO","splitLimit","calculateSize","AbortError","pushable","getNext","onNext","ended","onEnd","drain","bufferNext","objectMode","bufferError","queueMicrotask","throw","readableLength","onEmpty","signal","throwIfAborted","cancel","addEventListener","race","removeEventListener","_pushable","sources","syncSources","all","item","pipe","rest","isDuplex","duplex","isIterable","fns","sink","duplexPipelineFn","rawPipe","stream","sourceWrap","selectOpenConnection","connections","timeline","at","STREAM_LOCK_KEY","StreamManager","multicodec","getConnections","ongoingCreation","streamPool","handlePeerUpdateStreamPool","getStream","peer","peerId","scheduledStream","delete","getOpenStreamForCodec","lockStream","createStream","connection","lastError","newStream","createStreamWithLock","detail","protocols","scheduleNewStream","streams","protocol","writeStatus","isStreamLocked","metadata","BaseProtocol","components","addLibp2pEventListener","removeLibp2pEventListener","streamManager","connectionManager","randomUUID","rnds8","rng","byteToHex","rnds","unsafeStringify","FilterPushRpc","FilterSubscribeRpc","createSubscribeRequest","SUBSCRIBE","createUnsubscribeRequest","UNSUBSCRIBE","createUnsubscribeAllRequest","UNSUBSCRIBE_ALL","createSubscriberPingRequest","FilterCodecs","FilterCore","handleIncomingMessage","libp2p","handle","onRequest","maxInboundStreams","success","failure","GENERIC_FAIL","REMOTE_PEER_REJECTED","unsubscribe","NO_STREAM_AVAILABLE","unsubscribeRequest","unsubscribeAll","NO_RESPONSE","ping","streamData","remotePeer","createRequest","LightPushCodec","LightPushCore","preparePushMessage","EMPTY_PAYLOAD","isWireSizeUnderCap","isMessageSizeUnderCap","SIZE_TOO_BIG","ENCODE_FAILED","preparationError","DECODE_FAILED","rlnErrorCase","rlnErrorMap","RLN_IDENTITY_MISSING","RLN_MEMBERSHIP_INDEX","RLN_LIMIT_MISSING","infoLowerCase","errorKey","RLN_PROOF_GENERATION","matchRLNErrorMessage","EmptyMessage","ONE_MILLION","StoreCodec","StoreCore","queryPerPage","queryOpts","currentCursor","storeQueryRequest","storeQueryResponse","errorMessage","decodedMessages","protoMsg","wire","TypedEventEmitter","EventTarget","dispatchEvent","safeDispatchEvent","CustomEvent","KeepAliveManager","relay","pingKeepAliveTimers","relayKeepAliveTimers","pingKeepAlive","pingPeriodSecs","relayKeepAlive","relayPeriodSecs","peerIdStr","interval","setInterval","services","peerStore","intervals","scheduleRelayPings","clearInterval","stopAll","timer","connectionsExist","getMeshPeers","getPeerPing","ConnectionManager","keepAliveManager","dialAttemptsForPeer","dialErrorsForPeer","currentActiveParallelDialCount","pendingPeerDialQueue","isP2PNetworkConnected","isConnected","onLine","onEventHandlers","stopNetworkStatusListener","dropConnection","hangUp","getPeersByDiscovery","peersDiscovered","peersConnected","conn","peersDiscoveredByBootstrap","peersDiscoveredByPeerExchange","peersDiscoveredByLocal","peersConnectedByBootstrap","peersConnectedByPeerExchange","peersConnectedByLocal","tags","getTagNamesForPeer","BOOTSTRAP","PEER_EXCHANGE","LOCAL","DISCOVERED","CONNECTED","maxDialAttemptsForPeer","maxBootstrapPeersAllowed","maxParallelDials","startEventListeners","dialPeerStorePeers","getConnectedPeers","peerIDs","getPeers","dialPromises","peerInfo","attemptDial","startPeerDiscoveryListener","startPeerConnectionListener","startPeerDisconnectionListener","startNetworkStatusListener","dialPeer","dialAttempt","dial","AggregateError","processDialQueue","attemptDnsDiscovery","dnsDiscovery","findPeers","shouldDialPeer","dispatchDiscoveryEvent","PEER_CONNECT_BOOTSTRAP","PEER_CONNECT_PEER_EXCHANGE","setP2PNetworkConnected","setP2PNetworkDisconnected","dispatchWakuConnectionEvent","isPeerTopicConfigured","getPeerShardInfo","isPeerDialableBasedOnBootstrapStatus","some","tagName","isBootstrap","PEER_DISCOVERY_BOOTSTRAP","PEER_DISCOVERY_PEER_EXCHANGE","shardInfoBytes","CONNECTION_STATUS","HealthManager","static","health","overallStatus","Unhealthy","protocolStatuses","getInstance","getHealthStatus","getProtocolStatus","updateProtocolHealth","connectedPeers","getNameFromMulticodec","MinimallyHealthy","SufficientlyHealthy","lastUpdate","updateOverallHealth","Filter","LightPush","Store","statuses","getHealthManager","MetadataCodec","Metadata","libp2pComponents","handshakesConfirmed","registrar","NO_PEER_AVAILABLE","encodedResponse","decodeMetadataResponse","savePeerShardInfo","confirmOrAttemptHandshake","encodedShardInfo","wakuMetadata","peerIdSymbol","isPeerId","parser","readAtomically","parseWith","peekChar","readChar","readGivenChar","readSeparator","sep","inner","readNumber","radix","maxDigits","allowZeroPrefix","maxBytes","digitCount","leadingChar","hasLeadingZero","maxValue","digit","readIPv4Addr","ix","readIPv6Addr","readGroups","groups","ipv4","headSize","headIp4","limit","tailSize","readIPAddr","parseIPv4","new","parseIPv6","parseIP","ipv4Prefix","maskIp","allFF","cidrMask","ones","ipOrCidr","network","address","maskString","ipLength","parseCidr","ipResult","maskResult","containsIp","entries","simpleMaskLength","maskToHex","padStart","ipToString","isIPv4","isIPv6","isIP","isV4","isV6","sections","v4Buffer","argv","V","convertToString","ipBuff","ipString","bytes2ip","bytes2str","bytes2port","bytes2mh","addrBytes","portBytes","bytes2onion","bytes2mb","convertToBytes","ip2bytes","str2bytes","port2bytes","mh","mh2bytes","addr","port","portBuf","onion2bytes","onion32bytes","mbstr","mb","anybaseDecoder","mb2bytes","row","resolvable","createProtocol","bytesToMultiaddrParts","tuples","stringTuples","sizeForAddr","stringAddr","stringTuplesToString","tup","cleanPath","tuplesToBytes","inspect","DNS_CODES","NoAvailableResolverError","Multiaddr","stringToMultiaddrParts","isMultiaddr","toOptions","family","transport","host","zone","tcp","udp","ip4","ip6","dns6","ip6zone","protos","assign","protoCodes","protoNames","encapsulate","decapsulate","addrString","decapsulateCode","getPeerId","p2p","tuple","getPath","resolvableProto","resolver","resolvers","nodeAddress","isThinWaistAddress","pubsubTopicBytes","contentTopicBytes","timestampBytes","bigIntTimestamp","numberToBytes","tryConvertTimestampToBytes","SubscriptionMonitor","peers","isStarted","peerManager","activeSubscriptions","keepAliveIntervalId","pingFailedAttempts","receivedMessagesFormPeer","receivedMessages","verifiedPeers","onConnectionChange","onPeerConnected","onPeerDisconnected","reservedContentTopic","startKeepAlive","startConnectionListener","stopKeepAlive","stopConnectionListener","stopPeerConnectionListener","notifyMessageReceived","buildMessageHash","messageHashStr","keepAliveIntervalMs","_event","_peer","requestRenew","renewOnFirstFail","newPeer","pingsBeforePeerRenewed","Subscription","monitor","subscriptionCallbacks","lightPush","decodersArray","failures","TOPIC_DECODER_MISMATCH","successes","enableLightPushFilterCheck","decodersGroupedByCT","promises","results","allSettled","finalResult","handleResult","subscriptionCallback","processIncomingMessage","decodePromises","dec","decoded","decodedMessage","any","pushMessage","promiseResult","reason","coreResult","buildConfig","subscription","getActiveSubscription","uniquePubsubTopics","getUniquePubsubTopics","INVALID_DECODER_TOPICS","createSubscription","setActiveSubscription","subscribeWithUnsubscribe","toSubscriptionIterator","receiver","iteratorOptions","isWithTimeout","timeoutMs","startTime","now","toAsyncIterator","DEFAULT_SEND_OPTIONS","autoRetry","maxAttempts","TOPIC_NOT_CONFIGURED","attemptRetries","CONNECTION_LOCK_TAG","PeerManager","numPeersToUse","onConnected","onDisconnected","getLockedConnections","mapConnectionToPeer","lockedConnections","neededPeers","getUnlockedConnections","lockConnection","lockPeerIfNeeded","isConnectionLocked","queryGenerator","decodersAsMap","validateDecodersAndPubsubTopic","responseGenerator","queryWithOrderedCallback","processMessages","queryWithPromiseCallback","abort","page","_promises","msgPromise","processedMessages","createCursor","uniquePubsubTopicsInQuery","pubsubTopicForQuery","waitForConnectedPeer","metadataService","awaitTimeout","rejectReason","_resolve","WakuNode","store","protocolsEnabled","lightpush","wakuLightPush","wakuFilter","getProtocols","_protocols","mapToPeerIdOrMultiaddr","Relay","codecs","gossipSub","multicodecs","dialProtocol","waitForPeers","waku","getEnabledProtocols","enabledCodes","protocolToCodec","mapProtocolsToCodecs","every","waitForMetadata","rejectOnTimeout","waitForRemotePeer","UnexpectedPeerError","InvalidPublicKeyError","InvalidPrivateKeyError","ConnectionClosingError","ConnectionClosedError","ConnectionFailedError","MuxerClosedError","StreamResetError","StreamStateError","NotFoundError","InvalidPeerIdError","InvalidMultiaddrError","InvalidCIDError","InvalidMultihashError","UnsupportedProtocolError","InvalidMessageError","TimeoutError","NotStartedError","DialError","LimitedConnectionError","TooManyInboundProtocolStreamsError","TooManyOutboundProtocolStreamsError","U32_MASK64","fromBig","u64","lst","Ah","Al","toBig","shrSH","_l","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","rotr32H","_h","rotr32L","rotlSH","rotlSL","rotlBH","rotlBL","Bh","Bl","add3L","Cl","add3H","Ch","add4L","Dl","add4H","Dh","add5H","Eh","add5L","El","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA512","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","s1l","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_0n","_1n","_2n","abool","title","numberToHexUnpadded","hexToNumber","_0","_9","ch","hl","al","ai","n1","n2","expectedLength","sum","isPosBig","bitLen","bitMask","u8n","u8fr","createHmacDrbg","hashLen","qByteLen","hmacFn","reseed","sl","pred","validatorFns","bigint","function","boolean","stringOrUint8Array","Fp","isValid","validateObject","validators","optValidators","checkField","isOptional","checkVal","memoized","arg","computed","_3n","_4n","_5n","_8n","power","modulo","pow2","invert","number","y","u","FIELD_FIELDS","nLength","nBitLength","_nBitLength","nByteLength","ORDER","redef","BYTES","sqrtP","MASK","ZERO","ONE","is0","isOdd","neg","eql","lhs","rhs","sqr","sub","mul","FpPow","div","sqrN","addN","subN","mulN","inv","sqrt","P","p1div4","nv","legendreC","Q","S","Z","Q1div2","g","t2","ge","tonelliShanks","FpSqrt","invertBatch","nums","lastMultiplied","inverted","reduceRight","FpInvertBatch","cmov","fromBytes","getFieldBytesLength","fieldOrder","bitLength","getMinHashLength","constTimeNegate","condition","negate","validateW","W","calcWOpts","windows","windowSize","pointPrecomputes","pointWindowSizes","getW","wNAF","hasPrecomputes","elm","unsafeLadder","precomputeWindow","points","precomputes","maxNumber","shiftBy","wbits","offset1","offset2","cond1","cond2","wNAFUnsafe","getPrecomputes","transform","comp","wNAFCached","wNAFCachedUnsafe","setWindowSize","fieldN","scalars","validateMSMPoints","validateMSMScalars","buckets","scalar","resI","sumI","validateBasic","curve","Gx","Gy","VERIFY_DEFAULT","zip215","ED25519_P","ED25519_SQRT_M1","ed25519_pow_2_252_3","_10n","_20n","_40n","_80n","b80","b160","b240","b250","pow_p_5_8","adjustScalarBytes","uvRatio","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519Defaults","ed25519","curveDef","CURVE","domain","mapToCurve","validateOpts","prehash","cHash","cofactor","modP","Fn","phflag","aCoordinate","assertPoint","Point","toAffineMemo","iz","ex","ey","ez","z","ax","ay","zz","assertValidMemo","X","Y","et","T","X2","Y2","Z2","Z4","aX2","toAffine","fromAffine","normalizeZ","toInv","msm","_setWindowSize","wnaf","assertValidity","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","x1y1","X3","Y3","T3","Z3","subtract","multiply","CURVE_ORDER","multiplyUnsafe","I","isSmallOrder","isTorsionFree","clearCofactor","fromHex","normed","lastByte","y2","isXOdd","isLastByteOdd","fromPrivateKey","privKey","getExtendedPublicKey","point","toRawBytes","toHex","modN","modN_LE","hashed","pointBytes","hashDomainToScalar","msgs","verifyOpts","getPublicKey","R","sig","publicKey","SB","ExtendedPoint","utils","randomPrivateKey","precompute","x25519","montgomeryBits","powPminus2","Gu","montgomeryBytes","fieldLen","cswap","swap","x_2","x_3","a24","encodeUCoordinate","scalarMult","pointU","uEnc","decodeUCoordinate","_scalar","decodeScalar","pu","x_1","sw","z_2","z_3","k_t","AA","BB","DA","CB","dacb","da_cb","z2","montgomeryLadder","GuBytes","scalarMultBase","getSharedSecret","privateKey","montgomery","concatKeys","privateKeyRaw","Ed25519PublicKey","raw","ensureEd25519Key","toMultihash","publicKeyToProtobuf","toCID","Ed25519PrivateKey","unmarshalEd25519PublicKey","KeyType","__KeyTypeValues","PublicKey","PrivateKey","Data","utilFromBase","inputBuffer","inputBase","utilToBase","internalReserved","internalValue","biggest","retBuf","retView","basis","utilConcatView","views","outputLength","prevLength","utilDecodeTC","valueHex","condition1","condition2","warnings","bigIntBuffer","bigIntView","bigInt","smallIntBuffer","smallIntView","padNumber","inputNumber","fullLength","dif","assertBigInt","baseBlock","inputOffset","inputLength","ViewWriter","items","final","powers2","digitsString","EMPTY_BUFFER","EMPTY_VIEW","END_OF_CONTENT_NAME","OCTET_STRING_NAME","BIT_STRING_NAME","HexBlock","BaseClass","_a","isHexOnly","valueHexView","fromBER","endLength","blockLength","toBER","sizeOnly","NAME","LocalBaseBlock","EMPTY_STRING","valueBeforeDecode","valueBeforeDecodeView","blockName","ValueBlock","LocalIdentificationBlock","idBlock","_b","_c","_d","tagClass","tagNumber","isConstructed","firstOctet","encodedBuf","encodedView","curView","inputView","intBuffer","tagNumberMask","intTagNumberBuffer","tagNumberBufferMaxLength","tempBufferView","LocalLengthBlock","lenBlock","isIndefiniteForm","longFormUsed","lenOffset","lengthBufferView","typeStore","BaseBlock","primitiveSchema","parameters","valueBlockType","valueBlock","resultOffset","_writer","prepareIndefiniteForm","idBlockBuf","valueBlockBuf","lenBlockBuf","onAsciiEncoding","inputBuffer1","inputBuffer2","view1","view2","Constructed","BaseStringBlock","stringValueBlockType","getValue","setValue","fromBuffer","LocalPrimitiveValueBlock","_a$w","_a$v","_a$u","_a$t","_a$s","_a$r","_a$q","_a$p","_a$o","_a$n","_a$m","_a$l","_a$k","_a$j","_a$i","_a$h","_a$g","_a$f","_a$e","_a$d","_a$c","_a$b","_a$a","_a$9","_a$8","_a$7","_a$6","_a$5","_a$4","_a$3","_a$2","_a$1","Primitive","localFromBER","incomingOffset","returnObject","newASN1Type","EndOfContent","Integer","BitString","OctetString","Null","ObjectIdentifier","Enumerated","Utf8String","RelativeObjectIdentifier","TIME","Sequence","NumericString","PrintableString","TeletexString","VideotexString","IA5String","UTCTime","GeneralizedTime","GraphicString","VisibleString","GeneralString","UniversalString","CharacterString","BmpString","DATE","TimeOfDay","DateTime","newObject","inputObject","newType","localChangeType","LocalConstructedValueBlock","currentOffset","LocalEndOfContentValueBlock","override","LocalBooleanValueBlock","octet","LocalOctetStringValueBlock","currentBlockName","asn","content","LocalBitStringValueBlock","unusedBits","bitsStr","viewAdd","second","firstView","secondView","firstViewCopy","firstViewCopyLength","secondViewCopy","secondViewCopyLength","power2","digits","viewSub","LocalIntegerValueBlock","_valueDec","setValueHex","valueDec","modValue","tempBuf","tempView","fromDER","toDER","updatedView","firstBit","currentByte","bitNumber","asn1View","flag","byteNumber","bigIntValue","secondInt","convertToDER","integer","convertFromDER","LocalSidValueBlock","isFirstSid","valueBigInt","sidValue","LocalObjectIdentifierValueBlock","sidBlock","retBuffers","valueBuf","pos1","pos2","sid","plus","parsedSID","sidStr","sidArray","LocalRelativeSidValueBlock","LocalRelativeObjectIdentifierValueBlock","LocalStringValueBlock","LocalSimpleStringValueBlock","LocalSimpleStringBlock","inputString","strLen","LocalUtf8StringValueBlock","LocalBmpStringValueBlock","LocalUniversalStringValueBlock","copyBuffer","valueView","strLength","codeBuf","codeView","valueDate","year","month","day","hour","minute","fromDate","toBuffer","inputDate","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","toDate","UTC","parserArray","outputArray","toISOString","millisecond","getUTCMilliseconds","isUTC","timeString","dateTimeString","fractionPart","hourDifference","minuteDifference","multiplier","differencePosition","differenceString","fractionPointPosition","fractionPartCheck","fractionResult","tempDate","getUTCDay","SigningError","VerificationError","WebCryptoMissingError","win","nativeCrypto","RSAPublicKey","_key","_raw","_multihash","webcrypto","importKey","RSAPrivateKey","jwk","dp","dq","qi","der","bufToBn","jwkToPkix","asn1jsIntegerToBase64","u8","pkixToRSAPublicKey","kty","pkixToJwk","RSA","HMAC","iHash","oHash","hmac","validateSigVerOpts","lowS","b2n","h2b","DERErr","DER","Err","_tlv","dataLen","lenLen","lengthBytes","_int","toSig","tlv","seqBytes","seqLeftBytes","rBytes","rLeftBytes","sBytes","sLeftBytes","hexFromSig","seq","weierstrass","bits2int","bits2int_modN","compressedLen","uncompressedLen","invN","ProjectivePoint","normPrivateKeyToScalar","weierstrassEquation","isWithinCurveOrder","allowedPrivateKeyLengths","wrapPrivateKey","allowInfinityPoint","endo","beta","splitScalar","validatePointOpts","_isCompressed","x2","x3","N","assertPrjPoint","px","py","pz","hasEvenY","U1","U2","t0","t1","t3","t4","t5","sc","k1neg","k2neg","k1p","k2p","fake","f1p","f2p","multiplyAndAddUnsafe","isCompressed","_bits","weierstrassPoints","cat","sqrtError","suffix","numToNByteStr","isBiggerThanHalfOrder","slcNum","Signature","recovery","fromCompact","addRecoveryBit","recoverPublicKey","msgHash","rec","radj","ir","u1","u2","hasHighS","normalizeS","toDERRawBytes","toDERHex","toCompactRawBytes","toCompactHex","isValidPrivateKey","minLen","reduced","mapHashToField","isProbPub","delta","ORDER_MASK","int2octets","defaultSigOpts","defaultVerOpts","privateA","publicB","k2sig","extraEntropy","ent","h1int","seedArgs","kBytes","ik","normS","prepSig","drbg","signature","sg","isObj","_sig","derError","is","getHash","secp256k1P","secp256k1N","divNearest","Fpk1","_6n","_11n","_22n","_23n","_44n","_88n","b88","b176","b220","b223","secp256k1","defHash","createCurve","POW_2_128","isPromise","finally","Secp256k1PublicKey","validateSecp256k1PublicKey","compressSecp256k1PublicKey","Secp256k1PrivateKey","validateSecp256k1PrivateKey","computeSecp256k1PublicKey","unmarshalSecp256k1PublicKey","generateKeyPair","generateEd25519KeyPair","privateKeyBytes","generateSecp256k1KeyPair","pair","generateKey","modulusLength","publicExponent","exportKey","generateRSAKey","generateRSAKeyPair","generateKeyPairFromSeed","generateEd25519KeyPairFromSeed","publicKeyFromProtobuf","Ed25519","serviceCapabilities","serviceDependencies","PeerIdImpl","RSAPeerId","Ed25519PeerId","Secp256k1PeerId","URLPeerId","url","peerIdFromString","peerIdFromMultihash","peerIdFromPublicKey","isSha256Multihash","isIdentityMultihash","publicKeyFromMultihash","URL","peerIdFromCID","raceSignal","aborted","errorCode","errorName","QueuelessPushable","readNext","haveNext","nextResult","byteStream","readBuffer","abortPromise","unwrap","originalStream","yieldBytes","lpStream","decodeLength","lengthBuffer","writeV","flatMap","piped","NOISE_MSG_MAX_LENGTH_BYTES","DUMP_SESSION_KEYS","exists","copyBytes","wrapCipher","clean","_utf8ToBytes","sigma16","sigma32","sigma16_32","sigma32_32","MAX_COUNTER","U32_EMPTY","createCipher","core","allowShortKeys","extendNonceFn","counterLength","counterRight","rounds","nonce","toClean","sigma","k32","nonceNcLen","nc","n32","isAligned","d32","o32","pos32","posj","runCipher","u8to16","Poly1305","Uint16Array","t6","t7","isLast","hibit","r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","h0","h5","h6","h7","h8","h9","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","opos","poly1305","wrapConstructorWithKey","chachaCore","cnt","y00","y01","y02","y03","y04","y05","y06","y07","y08","y09","y10","y11","y12","y13","y14","y15","x00","x01","x02","x03","x04","x05","x06","x07","x08","x09","x10","x11","x12","x13","x14","x15","oi","chacha20","xchacha20","ZEROS16","updatePadded","ZEROS32","computeTag","AAD","authKey","_poly1305_aead","xorStream","encrypt","plaintext","plength","clength","decrypt","ciphertext","passedTag","chacha20poly1305","blockSize","nonceLength","tagLength","HKDF_COUNTER","defaultCrypto","hashSHA256","getHKDF","ck","ikm","prk","salt","extract","okm","HMACTmp","expand","generateX25519KeyPair","secretKey","generateX25519KeyPairFromSeed","generateX25519SharedKey","chaCha20Poly1305Encrypt","ad","chaCha20Poly1305Decrypt","uint16BEEncode","uint16BEDecode","logLocalStaticKeys","keyLogger","logLocalEphemeralKeys","logRemoteEphemeralKey","logCipherState","cs1","cs2","getUint64","Nonce","increment","getBytes","assertValue","ZEROLEN","CipherState","hasKey","encryptWithAd","decryptWithAd","SymmetricState","cs","protocolName","protocolNameBytes","hashProtocolName","mixKey","tempK","hkdf","mixHash","encryptAndHash","decryptAndHash","tempK1","tempK2","AbstractHandshakeState","ss","rs","initiator","prologue","writeE","generateKeypair","writeS","writeEE","dh","writeES","writeSE","readE","readS","cipherLength","temp","readEE","readES","readSE","XXHandshakeState","writeMessageA","writeMessageB","encS","writeMessageC","readMessageA","readMessageB","consumed","readMessageC","NoiseExtensions","NoiseHandshakePayload","createHandshakePayload","staticPublicKey","identitySig","getSignaturePayload","identityKey","decodeHandshakePayload","payloadBytes","remoteStaticKey","remoteIdentityKey","signaturePayload","webtransportCerthashes","Noise","staticKey","metrics","staticNoiseKey","prologueBytes","_crypto","keypair","wrapCrypto","xxHandshakeSuccesses","registerCounter","help","xxHandshakeErrors","encryptedPackets","decryptedPackets","decryptErrors","registerMetrics","secureOutbound","wrappedConnection","handshake","performHandshakeInitiator","createSecureConnection","remoteExtensions","secureInbound","performHandshakeResponder","xx","trace","receivedPayload","forComponent","secure","user","duplexPair","encryptStream","encrypted","decryptStream","noise","peerDiscoverySymbol","DNS4","DNS6","DNSADDR","IP","TCP","and","UDP","UTP","QUIC","QUICV1","_WebSockets","_WebSocketsSecure","HTTP","HTTPS","_WebRTCDirect","WebRTCDirect","_WebTransport","WebTransport","P2PWebRTCStar","P2PWebRTCDirect","Reliable","_P2P","_Circuit","CircuitRecursive","Circuit","P2P","makeMatchesFunction","partialMatch","ma","matches","pnames","Bootstrap","_init","candidate","peerData","multiaddrs","_discoverBootstrapPeers","tagValue","ttl","tagTTL","openConnection","ENVELOPE_PAYLOAD_TYPE_PEER_RECORD","Envelope","PeerRecord","AddressInfo","multiaddr","addresses","addresses$","peerRecord","seqNumber","DOMAIN","CODEC","marshaled","marshal","localeCompare","arrayEquals","payloadType","InvalidSignatureError","RecordEnvelope","envelopeData","record","signData","formatSignaturePayload","envelope","createFromProtobuf","validate","domainUint8Array","domainLength","payloadTypeLength","payloadLength","NETMASK_RANGES","ipRange","ipv4Check","ipAddr","isPrivateIp","octet34","octet12","ipv4MappedIpv6Check","ipv4EmbeddedIpv6Check","ipv6Check","isPrivate","func","vals","pattern","literal","certhash","matcher","matchers","fmt","toParts","exactMatch","_DNS4","_DNS6","_DNSADDR","_DNS","_IP4","_IP6","_IP","_IP_OR_DOMAIN","IP_OR_DOMAIN","_TCP","_UDP","_QUIC","_QUICV1","QUIC_V0_OR_V1","_WEB","pbStream","lp","pb","Identify","protocolVersion","agentVersion","listenAddrs","observedAddr","signedPeerRecord","isEnvWithDom","nodeType","isElectron","isBrowser","isElectronMain","isElectronRenderer","release","isWebWorker","importScripts","WorkerGlobalScope","isReactNative","product","defaultValues","AbstractIdentify","started","addressManager","maxOutboundStreams","maxMessageSize","maxObservedAddresses","runOnLimitedConnection","nodeInfo","protocolPrefix","AgentVersion","ProtocolVersion","handleProtocol","unhandle","runOnConnectionOpen","identify","_identify","AbortSignal","close","maybeAddObservedAddress","isCertified","peerRecordEnvelope","openAndCertify","envelopePeer","existingPeer","storedEnvelope","storedRecord","patch","consumeIdentifyMessage","cleanObservedAddr","getCleanMultiaddr","isGlobalUnicast","addObservedAddr","getAddresses","seal","remoteAddr","closeSource","getIterator","createAbortError","clearMethods","defaultClear","defaultSet","milliseconds","timeoutId","settle","rejectFunction","signalListener","delayPromise","createDelay","RateLimitError","remainingPoints","msBeforeNext","consumedPoints","isFirstInDuration","props","QueueFullError","RateLimiter","memoryStorage","duration","blockDuration","execEvenly","execEvenlyMinDelayMs","keyPrefix","MemoryStorage","pointsToConsume","rlKey","getKey","secDuration","_getKeySecDuration","incrby","delayMs","penalty","reward","msDuration","initPoints","customDuration","parseKey","durationSec","existing","msBeforeExpires","expiresAt","durationMs","MessageTypes","MessageTypeNames","InitiatorMessageTypes","NEW_STREAM","MESSAGE","MESSAGE_INITIATOR","CLOSE","CLOSE_INITIATOR","RESET","RESET_INITIATOR","ReceiverMessageTypes","MESSAGE_RECEIVER","CLOSE_RECEIVER","RESET_RECEIVER","MAX_MSG_SIZE","_buffer","_headerInfo","_maxMessageSize","_maxUnprocessedMessageQueueSize","maxUnprocessedMessageQueueSize","_decodeHeader","readVarInt","POOL_SIZE","_pool","_poolOffset","header","StreamInputBufferError","AbstractStream","direction","readStatus","sinkController","sinkEnd","closed","endErr","streamSource","onCloseRead","onCloseWrite","onReset","onAbort","sendCloseWriteTimeout","sendingData","AbortController","onSourceEnd","sendNewStream","abortListener","sendData","sendCloseWrite","onSinkEnd","closeRead","closeWrite","sendCloseRead","sendReset","_closeSinkAndSource","_closeSink","_closeSource","remoteCloseWrite","remoteCloseRead","sourcePush","sourceReadableLength","MplexStream","streamId","maxDataSize","toSend","printMessage","MplexStreamMuxer","_streamId","_streams","_source","closeController","rateLimiter","closeTimeout","initiators","receivers","_createSink","disconnectThreshold","registry","_newStream","_newReceiverStream","maxMsgSize","onStreamEnd","_handleIncoming","onIncomingStream","maxBufferSize","maxStreamBufferSize","Mplex","createStreamMuxer","mplex","PingService","handleMessage","received","transportSymbol","FaultTolerance","ASSUME_HTTP_CODES","extractSNI","extractTuple","extractPort","hasTLS","interpretNext","headProtoCode","headProtoVal","restMa","interpreter","interpreters","restVal","tailProto","dnsaddr","dns4","dns","ipfs","http","maHasTLS","sni","baseVal","tls","https","ws","wss","socket","cleanup","handleOpen","handleErr","closeOnEnd","ready","CLOSING","CLOSED","wasClean","connect","location","wsUrl","httpProto","wsProto","connectedSource","binaryType","connected","connError","cleanUp","cont","onOpen","onError","onMessage","remoteAddress","remotePort","hostname","CONNECTING","OPEN","terminate","websocket","CustomProgressEvent","Event","dialerEvents","registerCounterGroup","label","maConn","metricPrefix","socketToMaConn","_connect","upgrader","upgradeOutbound","cOpts","errorPromise","rawSocket","uri","onProgress","createListener","listenFilter","dialFilter","webSockets","getDOMException","DOMException","getAbortedReason","pTimeout","fallback","customTimers","abortHandler","cancelablePromise","POSITIVE_INFINITY","timeoutError","PriorityQueue","enqueue","run","element","priority","step","it","lowerBound","setPriority","findIndex","ReferenceError","dequeue","PQueue","carryoverConcurrencyCount","intervalCap","concurrency","autoStart","queueClass","throwOnTimeout","delay","canInitializeInterval","job","newConcurrency","function_","addAll","functions","pause","onSizeLessThan","onIdle","sizeBy","getTypes","DEFAULT_TYPES","RecordType","toDNSResponse","Status","TC","flag_tc","RD","flag_rd","RA","flag_ra","AD","flag_ad","CD","flag_cd","Question","questions","question","Answer","answers","answer","TTL","dnsJsonOverHttps","httpQueue","queryConcurrency","fqdn","searchParams","URLSearchParams","headers","accept","statusText","CachedAnswers","lru","maxSize","hashlru","foundAllAnswers","cached","getAnswers","cachedAnswers","expires","cacheSize","tld","dnsaddrCode","RecursionLimitError","dnsaddrResolver","recursionLimit","maxRecursiveDepth","TXT","DefaultConfig","announce","noAnnounce","announceFilter","transportManager","faultTolerance","FATAL_ALL","validateConfig","resultingOptions","connectionProtector","LIBP2P_FORCE_PNET","contentRoutingSymbol","peerRoutingSymbol","fmtLong","isError","toNamespace","regexp","RegExp","setupFormatters","defaultLogger","createDisabledLogger","notEmpty","mapIterable","iter","PeerSet","predicate","intersection","difference","union","observable","worker","WORKER_REQUEST_READ_LOCK","WORKER_RELEASE_READ_LOCK","MASTER_GRANT_READ_LOCK","WORKER_REQUEST_WRITE_LOCK","WORKER_RELEASE_WRITE_LOCK","MASTER_GRANT_WRITE_LOCK","handleWorkerLockRequest","masterEvent","releaseType","grantType","requestEvent","identifier","MessageEvent","handler","postMessage","releaseEventListener","releaseEvent","makeWorkerLockRequest","responseEvent","defaultOptions","singleProcess","mutexes","implementation","createReleaseable","Peer","Address","Tag","bytesToPeer","expiry","Peer$metadataEntry","Peer$tagsEntry","tags$value","pathSepS","pathSepB","pathSep","Key","_buf","uint8Array","withNamespaces","asKey","less","list1","list2","baseNamespace","namespaceType","namespaceValue","child","isAncestorOf","isDecendantOf","isTopLevel","NAMESPACE_COMMON","peerIdToDatastoreKey","b32key","dedupeFilterAndSortAddresses","addressMap","maStr","existingAddr","toPeerPB","strategy","createSortedMap","validateMetadata","validateTag","mapTag","metadataEntries","tagsEntries","mergedTags","addressFilter","decodePeer","PersistentStore","datastore","lock","isWorker","readLock","writeLock","masterQueue","readQueue","localReadQueue","readPromise","createMutex","existingBuf","peerPb","filters","orders","mapQuery","previous","updated","put","PersistentPeerStore","consumePeerRecord","expectedPeer","peekable","iterable","sorter","BaseDatastore","putMany","getMany","deleteMany","batch","puts","dels","commit","_all","_allKeys","queryKeys","MemoryDatastore","defaultAddressFilter","addrs","stripPeerId","observedPeerIdStr","DefaultAddressManager","observed","_updatePeerStoreAddresses","debounce","getAnnounceAddrs","getAddrs","confident","getListenAddrs","getObservedAddrs","confirmObservedAddr","startingConfidence","removeObservedAddr","addrSet","isStartable","MissingServiceError","UnmetServiceDependenciesError","NoContentRoutersError","NoPeerRoutersError","QueriedForSelfError","UnhandledProtocolError","DuplicateProtocolHandlerError","DialDeniedError","NoValidAddressesError","ConnectionInterceptedError","ConnectionDeniedError","MuxerUnavailableError","EncryptionFailedError","TransportUnavailableError","DefaultComponents","_started","_invokeStartableMethod","startable","beforeStart","afterStart","beforeStop","afterStop","OPTIONAL_SERVICES","NON_SERVICE_PROPERTIES","getServiceCapabilities","getServiceDependencies","getServiceName","connectionGater","gater","denyDialPeer","denyDialMultiaddr","denyInboundConnection","denyOutboundConnection","denyInboundEncryptedConnection","denyOutboundEncryptedConnection","denyInboundUpgradedConnection","denyOutboundUpgradedConnection","filterMultiaddrForPeer","PeerMap","getPeerAddress","maPeerIdStr","maPeerId","DEFAULT_CLOSABLE_PROTOCOLS","maxConnections","allow","ConnectionPruner","maybePruneConnections","_maybePruneConnections","numConnections","peerValues","sortedConnections","sortConnections","toPrune","toClose","streamProtocols","closableProtocols","safelyCloseConnectionIfUnused","connectionALifespan","connectionBLifespan","peerAValue","peerBValue","LAST_DIAL_FAILURE_KEY","LAST_DIAL_SUCCESS_KEY","raceEvent","eventName","removeListeners","eventListener","errorEvent","errorEventListener","JobRecipient","Job","recipients","controller","created","recipient","Queue","metricName","registerMetricGroup","calculate","running","tryToStartAnother","toGenerator","onQueueJobComplete","onQueueError","onQueueIdle","onSignalAbort","anySignal","signals","reliableTransportsFirst","isATCP","isBTCP","isAWebSocketSecure","isBWebSocketSecure","isAWebSocket","isBWebSocket","isAWebRTC","isBWebRTC","isAWebRTCDirect","isBWebRTCDirect","isAWebTransport","isBWebTransport","publicAddressesFirst","isAPrivate","isBPrivate","certifiedAddressesFirst","circuitRelayAddressesLast","isACircuit","isBCircuit","DialQueue","addressSorter","maxPeerAddrsToDial","maxDialQueueLength","dialTimeout","shutDownController","peerIdOrMultiaddr","existingConnection","flat","force","existingDial","createDialAbortController","addrsToDial","calculateMultiaddrs","dialed","DEFAULT_DIAL_PRIORITY","userSignal","peerRouting","findPeer","resolvedAddresses","resolveMultiaddrs","peerIdMultiaddr","lastProto","filteredAddrs","dialTransportForMultiaddr","addrPeerId","dedupedAddrs","dedupedMultiaddrs","gatedAdrs","sortedGatedAddrs","isDialable","KEEP_ALIVE","PeerQueue","objectToString","errorMessages","originalError","decorateErrorWithCounts","attemptNumber","retriesLeft","ReconnectQueue","retryInterval","backoffFactor","maxParallelReconnects","maybeReconnect","hasKeepAliveTag","onFailedAttempt","shouldRetry","isNetworkError","finalError","pRetry","keepAlivePeers","DefaultConnectionManager","deny","maxIncomingPendingConnections","incomingPendingConnections","outboundPendingConnections","dialQueue","reconnectQueue","connectionPruner","inboundConnectionRateLimiter","onConnect","onDisconnect","inboundConnectionThreshold","reconnectRetries","reconnectRetryInterval","reconnectBackoffFactor","metric","inbound","outbound","conns","allStreams","objs","startables","tasks","connectionList","_onConnect","isNewPeer","storedConns","filteredPeerConns","getConnectionsMap","peerConnections","trackedConnection","closeConnections","acceptIncomingConnection","afterUpgradeInbound","getDialQueue","statusMap","errored","complete","MovingAverage","movingAverage","variance","deviation","forecast","timespan","previousTime","alpha","pt","exp","time","incr","AdaptiveTimeout","timeoutMultiplier","failureMultiplier","getTimeoutSignal","timeoutFactor","sendTimeout","timeoutSignal","failureMovingAverage","failureDeviation","failureForecast","failureVariance","successMovingAverage","successDeviation","successForecast","successVariance","ConnectionMonitor","heartbeatInterval","pingIntervalMs","abortController","abortConnectionOnPingFailure","pingInterval","pingTimeout","bs","rtt","CompoundContentRouting","routers","findProviders","seen","router","provide","Fingerprint","fp","fingerprintSize","fnv","hashV","getRandomInt","Bucket","fingerprint","FNV_PRIMES","FNV_OFFSETS","cachedEncoder","utf8Buffer","fnvPrime","remaining","encodeInto","asUintN","fnv1aEncodeInto","fnv1aUint8Array","fnv1a","numberToBuffer","CuckooFilter","bucketSize","filterSize","rand","swapped","inJ","inK","reliable","MAX_LOAD","optimize","maxItems","errorRate","calculateBucketSize","log2","ScalableCuckooFilter","scale","filterSeries","cuckoo","curSize","DefaultPeerRouting","getClosestPeers","createScalableCuckooFilter","ordered","ops","sourceErr","slotAvailable","resultAvailable","sourceFinished","opErred","valuesAvailable","yieldOrderedValues","ok","yieldUnOrderedValues","task","parallel","useCache","RandomWalk","walking","walkers","shutdownController","walkController","needNext","walk","startWalk","DefaultRegistrar","topologies","_onDisconnect","_onPeerUpdate","_onPeerIdentify","getHandler","getTopologies","register","topology","unregister","removed","notifyOnLimitedConnection","TrackedMap","registerMetric","updateComponentMetric","deleted","DefaultTransportManager","transports","trackedMap","getTransports","of","getListeners","listenTransportForMultiaddr","couldNotListen","supportedAddrs","NO_FATAL","removeAll","PROTOCOL_ID","MAX_PROTOCOL_LENGTH","NewLine","negotiateFully","originalSink","originalSource","negotiated","negotiating","doneNegotiating","sentProtocol","sendingProtocol","doneSendingProtocol","readProtocol","readingProtocol","doneReadingProtocol","negotiate","doSendProtocol","doReadProtocol","sentData","protocolString","originalCloseRead","originalCloseWrite","originalClose","optimisticSelect","p1","p2","connectionSymbol","ConnectionImpl","multiplexer","encryption","_close","_abort","_getStreams","getStreams","countStreams","streamCount","DefaultUpgrader","connectionEncrypters","streamMuxers","inboundUpgradeTimeout","outboundUpgradeTimeout","inboundStreamProtocolNegotiationTimeout","outboundStreamProtocolNegotiationTimeout","encrypter","muxer","dials","shouldBlockConnection","denyOperation","upgradeInbound","_performUpgrade","idStr","remotePeerId","encryptedConn","upgradedConn","muxerFactory","cryptoProtocol","trackMultiaddrConnection","protectedConn","skipProtection","protector","protect","skipEncryption","_encryptInbound","_encryptOutbound","multiplexed","_multiplexInbound","_multiplexOutbound","_createConnection","muxedStream","incomingLimit","findIncomingStreamLimit","trackProtocolStream","_onStream","outgoingLimit","findOutgoingStreamLimit","_timeline","Proxy","Reflect","upgraded","__maConnTimeline","muxers","Libp2p","contentRouting","originalDispatch","internalResult","externalResult","defaultComponents","configureComponent","persistentPeerStore","connectionMonitor","peerRouters","contentRouters","peerDiscovery","createService","capability","checkServiceDependencies","component","peerSet","getMultiaddrs","peerKey","DEFAULT_NODE_REQUIREMENTS","USE_ENDOMORPHISM","ShaError","assertJacPoint","JacobianPoint","toAffineBatch","scratch","Z1Z1","Z2Z2","S1","S2","x1b","HH","HHH","P0","normalizeScalar","affinePoint","_WINDOW_SIZE","invZ","iz1","iz2","iz3","fromCompressedHex","isShort","bytesToNumber","isValidFieldElement","rt","isYOdd","fromUncompressedHex","normalizePrivateKey","fromSignature","normalizeSignature","truncateHash","rinv","numTo32bStr","toHexX","toRawX","aP","bQ","sliceDER","parseDERInt","rBytesLeft","parseDERSignature","HALF","sHex","rHex","sHexL","rHexL","sLen","rLen","uint8a","POW_2_256","hexByte","truncateOnly","groupLen","bits2int_2","_sha256Sync","_hmacSha256Sync","HmacDrbg","hmacSha256","hmacSync","checkSync","reseedSync","generate","generateSync","kmdToSig","kinv","bits2octets","z1","vopts","strict","web","bytesToHex","hexToBytes","concatBytes","_bigintTo32Bytes","_normalizePrivateKey","hashToPrivateKey","sha256","createHash","ckey","createHmac","sha256Sync","hmacSha256Sync","taggedHash","tagP","tagH","taggedHashSync","_JacobianPoint","keccak256","sha3","verifySignature","normalizePublicKey","sinv","ERR_INVALID_ID","locationMultiaddrFromEnrFields","isIpv6","ipVal","protoName","protoVal","ipFamily","ipBytes","protocolBytes","multiaddrFromFields","encodeMultiaddrs","encodeWaku2","RawEnr","kvs","rsv","getStringValue","setStringValue","getNumberAsStringValue","setNumberAsStringValue","tcp6","udp6","multiaddrBytes","decodeMultiaddrs","deleteUndefined","waku2","decodeWaku2","initSigArgs","canonical","recSig","recovered","finalizeSig","TransportProtocol","TransportProtocolPerIpVersion","pubKey","createPeerIdFromPublicKey","nodeId","uncompressedPubkey","getLocationMultiaddr","setLocationMultiaddr","getAllLocationMultiaddrs","_multiaddrs","getFullMultiaddr","locationMultiaddr","getFullMultiaddrs","_permanentCensorErrors","_censorErrors","LogLevels","warning","_logLevel","_globalLogger","_normalizeError","form","_checkNormalize","LogLevel","ErrorCode","HEX","_log","logLevel","throwArgumentError","levels","INFO","WARNING","makeError","UNKNOWN_ERROR","messageDetails","NUMERIC_FAULT","fault","CALL_EXCEPTION","INSUFFICIENT_FUNDS","MISSING_NEW","NONCE_EXPIRED","REPLACEMENT_UNDERPRICED","TRANSACTION_REPLACED","UNPREDICTABLE_GAS_LIMIT","throwError","INVALID_ARGUMENT","argument","assert","assertArgument","checkNormalize","UNSUPPORTED_OPERATION","checkSafeUint53","checkArgumentCount","expectedCount","MISSING_ARGUMENT","UNEXPECTED_ARGUMENT","checkNew","checkAbstract","globalLogger","setCensorship","censorship","permanent","setLogLevel","isHexable","addSlice","arrayify","allowMissingPrefix","toHexString","isHexString","hexPad","HexCharacters","hexlify","arrayifyInteger","unarrayifyInteger","_encode","_decodeChildren","childOffset","_decode","BUFFER_OVERRUN","EnrDecoder","encoded","RECORD_PREFIX","fromRLP","checkValues","_seq","decodeSeq","rlpEncodedBytes","checkSignature","fromValues","v4Regex","v6Regex","isFormat","buff","hexN","decN","prevColon","useDec","sizeOf","toType","rcode","opcode","klass","toClass","toCode","SURROGATE_A","SURROGATE_B","nextCode","numA","isU8Arr","bytelength","P_24","P_16","P_8","readUInt32BE","readUInt16BE","writeUInt32BE","writeUInt16BE","targetStart","sourceStart","sourceEnd","nb","sourceLen","_copyActual","consumedBytes","jumped","jumpOffset","flags","authorities","additionals","flag_qr","flag_aa","flag_z","runknown","dLen","rns","dd","rsoa","mname","rname","serial","refresh","expire","minimum","rtxt","rnull","rhinfo","cpu","os","rptr","rsrv","weight","rcaa","issuerCritical","ISSUER_CRITICAL","rmx","preference","exchange","ra","raaaa","roption","spl","sourcePrefixLength","fam","ipBuf","ipLen","scopePrefixLength","tagsLen","padded","ropt","rdlen","encodingLengthList","encodeList","rdnskey","keydata","PROTOCOL_DNSSEC","ZONE_KEY","SECURE_ENTRYPOINT","rrrsig","typeCovered","labels","originalTTL","expiration","inception","keyTag","signersName","rrp","mbox","txt","typebitmap","typelist","typesByWindow","typeid","windowBuf","windowLength","extents","rnsec","nextDomain","rrtypes","rnsec3","iterations","saltLength","hashLength","rds","digestdata","digestType","renc","udpPayloadSize","extendedRcode","ednsVersion","class","flush","flag_do","packet","allocing","decodeList","sanitizeSingle","sanitized","make","charset","paddingMode","byCharCode","byNum","padCode","safeLen","safeEnd","base64URL","require","HTTPStatusError","endpoint","ResponseError","cause","reduceError","baseParts","httpFlags","updFlags","parseFlags","regex","InvalidProtocolError","supportedProtocols","BaseEndpoint","isHTTP","pk","UDPEndpoint","ipv6","UDP4Endpoint","UDP6Endpoint","safeHost","HTTPEndpoint","v6Parts","toEndpoint","post","parseEndpoint","contentType","requestRaw","abortSignal","setRequestHeader","ontimeout","onerror","onload","onabort","cors","endpoints","resolverByName","byName","endpointByName","backup","description","country","lat","UPDATE_URL","isNameString","wellknown","updateURL","persist","localStoragePrefix","maxAge","_dataP","_data","outdated","cacheKey","maxTime","filterDoh","filterDns","queryN","singleQuery","toMultiQuery","queryDoh","queryOne","DnsOverHttps","_endpoints","resolveTXT","sd","ENRTree","parseAndVerifyRoot","ROOT_PREFIX","rootValues","parseRootValues","decodedPublicKey","signedComponent","signedComponentBuffer","eRoot","lRoot","parseTree","tree","TREE_PREFIX","parseBranch","branch","BRANCH_PREFIX","isSatisfied","wanted","addCapabilities","total","helpsSatisfyCapabilities","missingCapabilities","DnsNodeDiscovery","_DNSTreeCache","_errorTolerance","dnsOverHttp","dnsClient","enrTreeUrls","wantedNodeCapabilityCount","networkIndex","visits","errorTolerance","getNode","maxSearches","totalSearches","fetchNodesUntilCapabilitiesFulfilled","_search","getNextPeer","peerNodeIds","yieldNodesUntilCapabilitiesFulfilled","subdomain","_getTXTRecord","branches","entryType","getEntryType","circularRefs","selectRandomPath","PeerDiscoveryDns","nextPeer","_components","enrUrls","peerEnr","tagsToUpdate","isPeerChanged","wakuDnsDiscovery","PeerExchangeCodec","WakuPeerExchange","rpcQuery","ENR","DEFAULT_PEER_EXCHANGE_QUERY_INTERVAL_MS","DEFAULT_MAX_RETRIES","DEFAULT_PEER_EXCHANGE_TAG_NAME","PeerExchangeDiscovery","peerExchange","queryingPeers","queryAttempts","handleDiscoveredPeer","startRecurringQueries","queryInterval","maxRetries","currentAttempt","abortQueriesForPeer","_peerInfo","hasMultiaddrDiff","hasShardDiff","checkPeerInfoDiff","existingMultiaddrs","newMultiaddrs","existingShardInfoBytes","existingShardInfo","wakuPeerExchangeDiscovery","DEFAULT_LOCAL_TAG_NAME","LocalPeerCacheDiscovery","getPeersFromLocalStorage","handleNewPeers","savePeersToLocalStorage","websocketMultiaddr","wsMultiaddr","getWsMultiaddrFromMultiaddrs","localStoragePeers","existingPeerIndex","storedPeersData","isValidStoredPeer","defaultLibp2p","hideWebSocketInfo","createLibp2p","filterMultiaddrs","pingMaxInboundStreams","createLightNode","networkConfig","isAutoSharding","derivePubsubTopicsFromNetworkConfig","libp2pOptions","defaultBootstrap","defaultPeerDiscoveries","bootstrapPeers","createLibp2pAndUpdateOptions","TelemetryType","__awaiter","thisArg","_arguments","generator","fulfilled","rejected","__generator","sent","trys","Iterator","verb","TelemetryClient","intervalPeriod","intervalId","_this","telemetryRequests","e_1","telemetryType","telemetryData","__assign","generateRandomNumber","DEFAULT_EXTRA_DATA","sdk","buildExtraData","extraData","enabledProtocols","DEFAULT_CONTENT_TOPIC","DEFAULT_PUBSUB_TOPIC","ProtoSequencedMessage","sequenceCompletedEvent","messageReceivedEvent","wakuNode","app","telemetryClient","startLightPushSequence","startFilterSubscription","discoveredPeerId","LIGHT_PUSH_FILTER","createdAt","seenTimestamp","numMessages_1","args_1","_i","pack","ar","__spreadArray","numMessages","period","sequenceHash","sequenceTotal","sequenceIndex","sendMessage","error_1","sender","createElement","textContent"],"sourceRoot":""} \ No newline at end of file diff --git a/experimental/rln-js/index.js b/experimental/rln-js/index.js index a684cdd..e6786e0 100644 --- a/experimental/rln-js/index.js +++ b/experimental/rln-js/index.js @@ -9,25 +9,47 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ "./node_modules/@chainsafe/bls-keystore/lib/checksum.js": -/*!**************************************************************!*\ - !*** ./node_modules/@chainsafe/bls-keystore/lib/checksum.js ***! - \**************************************************************/ +/***/ "./node_modules/@chainsafe/bls-keystore/lib/checksum/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/checksum/index.js ***! + \********************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.verifyChecksum = exports.checksum = exports.defaultSha256Module = void 0;\nconst sha256_1 = __webpack_require__(/*! ethereum-cryptography/sha256 */ \"./node_modules/ethereum-cryptography/sha256.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\n// default checksum configuration\nfunction defaultSha256Module() {\n return {\n function: \"sha256\",\n };\n}\nexports.defaultSha256Module = defaultSha256Module;\n// checksum operations\nfunction checksumData(key, ciphertext) {\n return (0, utils_1.concatBytes)(key.slice(16), ciphertext);\n}\nfunction checksum(mod, key, ciphertext) {\n if (mod.function === \"sha256\") {\n return Promise.resolve((0, sha256_1.sha256)(checksumData(key, ciphertext)));\n }\n else {\n throw new Error(\"Invalid checksum type\");\n }\n}\nexports.checksum = checksum;\nfunction verifyChecksum(mod, key, ciphertext) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"sha256\") {\n return (0, utils_1.equalsBytes)((0, utils_1.hexToBytes)(mod.message), (0, sha256_1.sha256)(checksumData(key, ciphertext)));\n }\n else {\n throw new Error(\"Invalid checksum type\");\n }\n });\n}\nexports.verifyChecksum = verifyChecksum;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/checksum.js?"); +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.verifyChecksum = exports.checksum = exports.defaultSha256Module = void 0;\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\nconst sha256_1 = __webpack_require__(/*! ./sha256 */ \"./node_modules/@chainsafe/bls-keystore/lib/checksum/sha256.js\");\n// default checksum configuration\nfunction defaultSha256Module() {\n return {\n function: \"sha256\",\n };\n}\nexports.defaultSha256Module = defaultSha256Module;\n// checksum operations\nfunction checksumData(key, ciphertext) {\n return (0, utils_1.concatBytes)(key.slice(16), ciphertext);\n}\nfunction checksum(mod, key, ciphertext) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"sha256\") {\n return yield (0, sha256_1.sha256)(checksumData(key, ciphertext));\n }\n else {\n throw new Error(\"Invalid checksum type\");\n }\n });\n}\nexports.checksum = checksum;\nfunction verifyChecksum(mod, key, ciphertext) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"sha256\") {\n return (0, utils_1.equalsBytes)((0, utils_1.hexToBytes)(mod.message), yield (0, sha256_1.sha256)(checksumData(key, ciphertext)));\n }\n else {\n throw new Error(\"Invalid checksum type\");\n }\n });\n}\nexports.verifyChecksum = verifyChecksum;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/checksum/index.js?"); /***/ }), -/***/ "./node_modules/@chainsafe/bls-keystore/lib/cipher.js": -/*!************************************************************!*\ - !*** ./node_modules/@chainsafe/bls-keystore/lib/cipher.js ***! - \************************************************************/ +/***/ "./node_modules/@chainsafe/bls-keystore/lib/checksum/sha256.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/checksum/sha256.js ***! + \*********************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.cipherDecrypt = exports.cipherEncrypt = exports.defaultAes128CtrModule = void 0;\nconst random_1 = __webpack_require__(/*! ethereum-cryptography/random */ \"./node_modules/ethereum-cryptography/random.js\");\nconst aes_1 = __webpack_require__(/*! ethereum-cryptography/aes */ \"./node_modules/ethereum-cryptography/aes.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\nfunction defaultAes128CtrModule() {\n return {\n function: \"aes-128-ctr\",\n params: {\n iv: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(16)),\n },\n };\n}\nexports.defaultAes128CtrModule = defaultAes128CtrModule;\nfunction cipherEncrypt(mod, key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"aes-128-ctr\") {\n try {\n return yield (0, aes_1.encrypt)(data, key, (0, utils_1.hexToBytes)(mod.params.iv), mod.function, false);\n }\n catch (e) {\n throw new Error(\"Unable to encrypt\");\n }\n }\n else {\n throw new Error(\"Invalid cipher type\");\n }\n });\n}\nexports.cipherEncrypt = cipherEncrypt;\nfunction cipherDecrypt(mod, key) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"aes-128-ctr\") {\n try {\n return yield (0, aes_1.decrypt)((0, utils_1.hexToBytes)(mod.message), key, (0, utils_1.hexToBytes)(mod.params.iv), mod.function, false);\n }\n catch (e) {\n throw new Error(\"Unable to decrypt\");\n }\n }\n else {\n throw new Error(\"Invalid cipher type\");\n }\n });\n}\nexports.cipherDecrypt = cipherDecrypt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/cipher.js?"); +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.sha256 = void 0;\nconst sha256_1 = __webpack_require__(/*! ethereum-cryptography/sha256 */ \"./node_modules/ethereum-cryptography/sha256.js\");\nconst env_1 = __webpack_require__(/*! ../env */ \"./node_modules/@chainsafe/bls-keystore/lib/env.js\");\nexports.sha256 = env_1.hasWebCrypto ? sha256WebCrypto : sha256Js;\nfunction sha256WebCrypto(data) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Uint8Array(yield crypto.subtle.digest(\"SHA-256\", data));\n });\n}\nfunction sha256Js(data) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, sha256_1.sha256)(data);\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/checksum/sha256.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/bls-keystore/lib/cipher/aes128Ctr.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/cipher/aes128Ctr.js ***! + \**********************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.aes128CtrDecryptJs = exports.aes128CtrEncryptJs = exports.aes128CtrDecrypt = exports.aes128CtrEncrypt = void 0;\nconst aes_1 = __webpack_require__(/*! ethereum-cryptography/aes */ \"./node_modules/ethereum-cryptography/aes.js\");\nconst env_1 = __webpack_require__(/*! ../env */ \"./node_modules/@chainsafe/bls-keystore/lib/env.js\");\nexports.aes128CtrEncrypt = env_1.hasWebCrypto ? aes128CtrEncryptWebCrypto : aes128CtrEncryptJs;\nexports.aes128CtrDecrypt = env_1.hasWebCrypto ? aes128CtrDecryptWebCrypto : aes128CtrDecryptJs;\nfunction aes128CtrEncryptJs(key, iv, data) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield (0, aes_1.encrypt)(data, key, iv, \"aes-128-ctr\", false);\n });\n}\nexports.aes128CtrEncryptJs = aes128CtrEncryptJs;\nfunction aes128CtrEncryptWebCrypto(key, iv, data) {\n return __awaiter(this, void 0, void 0, function* () {\n const cryptoKey = yield crypto.subtle.importKey(\"raw\", key, { name: \"AES-CTR\" }, false, [\"encrypt\"]);\n return new Uint8Array(yield crypto.subtle.encrypt({ name: \"AES-CTR\", counter: iv, length: 128 }, cryptoKey, data));\n });\n}\nfunction aes128CtrDecryptJs(key, iv, ciphertext) {\n return __awaiter(this, void 0, void 0, function* () {\n return yield (0, aes_1.decrypt)(ciphertext, key, iv, \"aes-128-ctr\", false);\n });\n}\nexports.aes128CtrDecryptJs = aes128CtrDecryptJs;\nfunction aes128CtrDecryptWebCrypto(key, iv, ciphertext) {\n return __awaiter(this, void 0, void 0, function* () {\n const cryptoKey = yield crypto.subtle.importKey(\"raw\", key, { name: \"AES-CTR\" }, false, [\"decrypt\"]);\n return new Uint8Array(yield crypto.subtle.decrypt({ name: \"AES-CTR\", counter: iv, length: 128 }, cryptoKey, ciphertext));\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/cipher/aes128Ctr.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js": +/*!******************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js ***! + \******************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.cipherDecrypt = exports.cipherEncrypt = exports.defaultAes128CtrModule = void 0;\nconst random_1 = __webpack_require__(/*! ethereum-cryptography/random */ \"./node_modules/ethereum-cryptography/random.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\nconst aes128Ctr_1 = __webpack_require__(/*! ./aes128Ctr */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher/aes128Ctr.js\");\nfunction defaultAes128CtrModule() {\n return {\n function: \"aes-128-ctr\",\n params: {\n iv: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(16)),\n },\n };\n}\nexports.defaultAes128CtrModule = defaultAes128CtrModule;\nfunction cipherEncrypt(mod, key, data) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"aes-128-ctr\") {\n try {\n return yield (0, aes128Ctr_1.aes128CtrEncrypt)(key, (0, utils_1.hexToBytes)(mod.params.iv), data);\n }\n catch (e) {\n throw new Error(\"Unable to encrypt\");\n }\n }\n else {\n throw new Error(\"Invalid cipher type\");\n }\n });\n}\nexports.cipherEncrypt = cipherEncrypt;\nfunction cipherDecrypt(mod, key) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"aes-128-ctr\") {\n try {\n return yield (0, aes128Ctr_1.aes128CtrDecrypt)(key, (0, utils_1.hexToBytes)(mod.params.iv), (0, utils_1.hexToBytes)(mod.message));\n }\n catch (e) {\n throw new Error(\"Unable to decrypt\");\n }\n }\n else {\n throw new Error(\"Invalid cipher type\");\n }\n });\n}\nexports.cipherDecrypt = cipherDecrypt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js?"); /***/ }), @@ -38,7 +60,18 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Keystore = void 0;\nconst kdf_1 = __webpack_require__(/*! ./kdf */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf.js\");\nconst checksum_1 = __webpack_require__(/*! ./checksum */ \"./node_modules/@chainsafe/bls-keystore/lib/checksum.js\");\nconst cipher_1 = __webpack_require__(/*! ./cipher */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher.js\");\nconst functional_1 = __webpack_require__(/*! ./functional */ \"./node_modules/@chainsafe/bls-keystore/lib/functional.js\");\nconst schema_validation_1 = __webpack_require__(/*! ./schema-validation */ \"./node_modules/@chainsafe/bls-keystore/lib/schema-validation.js\");\n/**\n * Class-based BLS Keystore\n */\nclass Keystore {\n constructor(obj) {\n this.version = obj.version;\n this.uuid = obj.uuid;\n this.description = obj.description;\n this.path = obj.path;\n this.pubkey = obj.pubkey;\n this.crypto = {\n kdf: Object.assign({}, obj.crypto.kdf),\n checksum: Object.assign({}, obj.crypto.checksum),\n cipher: Object.assign({}, obj.crypto.cipher),\n };\n }\n /**\n * Create a new Keystore object\n */\n static create(password, secret, pubkey, path, description = null, kdfMod = (0, kdf_1.defaultPbkdfModule)(), checksumMod = (0, checksum_1.defaultSha256Module)(), cipherMod = (0, cipher_1.defaultAes128CtrModule)()) {\n return __awaiter(this, void 0, void 0, function* () {\n const obj = yield (0, functional_1.create)(password, secret, pubkey, path, description, kdfMod, checksumMod, cipherMod);\n return new Keystore(obj);\n });\n }\n /**\n * Create a keystore from an unknown object\n */\n static fromObject(obj) {\n (0, schema_validation_1.validateKeystore)(obj);\n return new Keystore(obj);\n }\n /**\n * Parse a keystore from a JSON string\n */\n static parse(str) {\n return Keystore.fromObject(JSON.parse(str));\n }\n /**\n * Decrypt a keystore, returns the secret key or throws on invalid password\n */\n decrypt(password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, functional_1.decrypt)(this, password);\n });\n }\n /**\n * Verify the password as correct or not\n */\n verifyPassword(password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, functional_1.verifyPassword)(this, password);\n });\n }\n /**\n * Return the keystore as a plain object\n */\n toObject() {\n return Object.assign({}, this);\n }\n /**\n * Return the keystore as stringified JSON\n */\n stringify() {\n return JSON.stringify(this.toObject(), null, 2);\n }\n}\nexports.Keystore = Keystore;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/class.js?"); +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Keystore = void 0;\nconst kdf_1 = __webpack_require__(/*! ./kdf */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js\");\nconst checksum_1 = __webpack_require__(/*! ./checksum */ \"./node_modules/@chainsafe/bls-keystore/lib/checksum/index.js\");\nconst cipher_1 = __webpack_require__(/*! ./cipher */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js\");\nconst functional_1 = __webpack_require__(/*! ./functional */ \"./node_modules/@chainsafe/bls-keystore/lib/functional.js\");\nconst schema_validation_1 = __webpack_require__(/*! ./schema-validation */ \"./node_modules/@chainsafe/bls-keystore/lib/schema-validation.js\");\n/**\n * Class-based BLS Keystore\n */\nclass Keystore {\n constructor(obj) {\n this.version = obj.version;\n this.uuid = obj.uuid;\n this.description = obj.description;\n this.path = obj.path;\n this.pubkey = obj.pubkey;\n this.crypto = {\n kdf: Object.assign({}, obj.crypto.kdf),\n checksum: Object.assign({}, obj.crypto.checksum),\n cipher: Object.assign({}, obj.crypto.cipher),\n };\n }\n /**\n * Create a new Keystore object\n */\n static create(password, secret, pubkey, path, description = null, kdfMod = (0, kdf_1.defaultPbkdfModule)(), checksumMod = (0, checksum_1.defaultSha256Module)(), cipherMod = (0, cipher_1.defaultAes128CtrModule)()) {\n return __awaiter(this, void 0, void 0, function* () {\n const obj = yield (0, functional_1.create)(password, secret, pubkey, path, description, kdfMod, checksumMod, cipherMod);\n return new Keystore(obj);\n });\n }\n /**\n * Create a keystore from an unknown object\n */\n static fromObject(obj) {\n (0, schema_validation_1.validateKeystore)(obj);\n return new Keystore(obj);\n }\n /**\n * Parse a keystore from a JSON string\n */\n static parse(str) {\n return Keystore.fromObject(JSON.parse(str));\n }\n /**\n * Decrypt a keystore, returns the secret key or throws on invalid password\n */\n decrypt(password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, functional_1.decrypt)(this, password);\n });\n }\n /**\n * Verify the password as correct or not\n */\n verifyPassword(password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, functional_1.verifyPassword)(this, password);\n });\n }\n /**\n * Return the keystore as a plain object\n */\n toObject() {\n return Object.assign({}, this);\n }\n /**\n * Return the keystore as stringified JSON\n */\n stringify() {\n return JSON.stringify(this.toObject(), null, 2);\n }\n}\nexports.Keystore = Keystore;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/class.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/bls-keystore/lib/env.js": +/*!*********************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/env.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\nvar _a;\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.hasWebCrypto = exports.isNode = void 0;\n/** Is in nodejs environment */\nexports.isNode = typeof process !== \"undefined\" &&\n process.versions != null &&\n process.versions.node != null;\n/** Is in environment with web crypto */\nexports.hasWebCrypto = ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.subtle) != null;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/env.js?"); /***/ }), @@ -49,7 +82,7 @@ eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _argument /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.decrypt = exports.verifyPassword = exports.create = exports.defaultAes128CtrModule = exports.defaultSha256Module = exports.defaultScryptModule = exports.defaultPbkdfModule = void 0;\nconst uuid_1 = __webpack_require__(/*! uuid */ \"./node_modules/uuid/dist/commonjs-browser/index.js\");\nconst kdf_1 = __webpack_require__(/*! ./kdf */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf.js\");\nObject.defineProperty(exports, \"defaultPbkdfModule\", ({ enumerable: true, get: function () { return kdf_1.defaultPbkdfModule; } }));\nObject.defineProperty(exports, \"defaultScryptModule\", ({ enumerable: true, get: function () { return kdf_1.defaultScryptModule; } }));\nconst checksum_1 = __webpack_require__(/*! ./checksum */ \"./node_modules/@chainsafe/bls-keystore/lib/checksum.js\");\nObject.defineProperty(exports, \"defaultSha256Module\", ({ enumerable: true, get: function () { return checksum_1.defaultSha256Module; } }));\nconst cipher_1 = __webpack_require__(/*! ./cipher */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher.js\");\nObject.defineProperty(exports, \"defaultAes128CtrModule\", ({ enumerable: true, get: function () { return cipher_1.defaultAes128CtrModule; } }));\nconst password_1 = __webpack_require__(/*! ./password */ \"./node_modules/@chainsafe/bls-keystore/lib/password.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\n/**\n * Create a new keystore object\n *\n * @param password password used to encrypt the keystore\n * @param secret secret key material to be encrypted\n * @param pubkey public key, not checked for validity\n * @param path HD path used to generate the secret\n * @param kdfMod key derivation function (kdf) configuration module\n * @param checksumMod checksum configuration module\n * @param cipherMod cipher configuration module\n */\nfunction create(password, secret, pubkey, path, description = null, kdfMod = (0, kdf_1.defaultPbkdfModule)(), checksumMod = (0, checksum_1.defaultSha256Module)(), cipherMod = (0, cipher_1.defaultAes128CtrModule)()) {\n return __awaiter(this, void 0, void 0, function* () {\n const encryptionKey = yield (0, kdf_1.kdf)(kdfMod, (0, password_1.normalizePassword)(password));\n const ciphertext = yield (0, cipher_1.cipherEncrypt)(cipherMod, encryptionKey.slice(0, 16), secret);\n return {\n version: 4,\n uuid: (0, uuid_1.v4)(),\n description: description || undefined,\n path: path,\n pubkey: (0, utils_1.bytesToHex)(pubkey),\n crypto: {\n kdf: {\n function: kdfMod.function,\n params: Object.assign({}, kdfMod.params),\n message: \"\",\n },\n checksum: {\n function: checksumMod.function,\n params: {},\n message: (0, utils_1.bytesToHex)(yield (0, checksum_1.checksum)(checksumMod, encryptionKey, ciphertext)),\n },\n cipher: {\n function: cipherMod.function,\n params: Object.assign({}, cipherMod.params),\n message: (0, utils_1.bytesToHex)(ciphertext),\n },\n },\n };\n });\n}\nexports.create = create;\n/**\n * Verify the password of a keystore object\n */\nfunction verifyPassword(keystore, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const decryptionKey = yield (0, kdf_1.kdf)(keystore.crypto.kdf, (0, password_1.normalizePassword)(password));\n const ciphertext = (0, utils_1.hexToBytes)(keystore.crypto.cipher.message);\n return (0, checksum_1.verifyChecksum)(keystore.crypto.checksum, decryptionKey, ciphertext);\n });\n}\nexports.verifyPassword = verifyPassword;\n/**\n * Decrypt a keystore, returns the secret key or throws on invalid password\n */\nfunction decrypt(keystore, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const decryptionKey = yield (0, kdf_1.kdf)(keystore.crypto.kdf, (0, password_1.normalizePassword)(password));\n const ciphertext = (0, utils_1.hexToBytes)(keystore.crypto.cipher.message);\n if (!(yield (0, checksum_1.verifyChecksum)(keystore.crypto.checksum, decryptionKey, ciphertext))) {\n throw new Error(\"Invalid password\");\n }\n return (0, cipher_1.cipherDecrypt)(keystore.crypto.cipher, decryptionKey.slice(0, 16));\n });\n}\nexports.decrypt = decrypt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/functional.js?"); +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.decrypt = exports.verifyPassword = exports.create = exports.defaultAes128CtrModule = exports.defaultSha256Module = exports.defaultScryptModule = exports.defaultPbkdfModule = void 0;\nconst uuid_1 = __webpack_require__(/*! uuid */ \"./node_modules/uuid/dist/commonjs-browser/index.js\");\nconst kdf_1 = __webpack_require__(/*! ./kdf */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js\");\nObject.defineProperty(exports, \"defaultPbkdfModule\", ({ enumerable: true, get: function () { return kdf_1.defaultPbkdfModule; } }));\nObject.defineProperty(exports, \"defaultScryptModule\", ({ enumerable: true, get: function () { return kdf_1.defaultScryptModule; } }));\nconst checksum_1 = __webpack_require__(/*! ./checksum */ \"./node_modules/@chainsafe/bls-keystore/lib/checksum/index.js\");\nObject.defineProperty(exports, \"defaultSha256Module\", ({ enumerable: true, get: function () { return checksum_1.defaultSha256Module; } }));\nconst cipher_1 = __webpack_require__(/*! ./cipher */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js\");\nObject.defineProperty(exports, \"defaultAes128CtrModule\", ({ enumerable: true, get: function () { return cipher_1.defaultAes128CtrModule; } }));\nconst password_1 = __webpack_require__(/*! ./password */ \"./node_modules/@chainsafe/bls-keystore/lib/password.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\n/**\n * Create a new keystore object\n *\n * @param password password used to encrypt the keystore\n * @param secret secret key material to be encrypted\n * @param pubkey public key, not checked for validity\n * @param path HD path used to generate the secret\n * @param kdfMod key derivation function (kdf) configuration module\n * @param checksumMod checksum configuration module\n * @param cipherMod cipher configuration module\n */\nfunction create(password, secret, pubkey, path, description = null, kdfMod = (0, kdf_1.defaultPbkdfModule)(), checksumMod = (0, checksum_1.defaultSha256Module)(), cipherMod = (0, cipher_1.defaultAes128CtrModule)()) {\n return __awaiter(this, void 0, void 0, function* () {\n const encryptionKey = yield (0, kdf_1.kdf)(kdfMod, (0, password_1.normalizePassword)(password));\n const ciphertext = yield (0, cipher_1.cipherEncrypt)(cipherMod, encryptionKey.slice(0, 16), secret);\n return {\n version: 4,\n uuid: (0, uuid_1.v4)(),\n description: description || undefined,\n path: path,\n pubkey: (0, utils_1.bytesToHex)(pubkey),\n crypto: {\n kdf: {\n function: kdfMod.function,\n params: Object.assign({}, kdfMod.params),\n message: \"\",\n },\n checksum: {\n function: checksumMod.function,\n params: {},\n message: (0, utils_1.bytesToHex)(yield (0, checksum_1.checksum)(checksumMod, encryptionKey, ciphertext)),\n },\n cipher: {\n function: cipherMod.function,\n params: Object.assign({}, cipherMod.params),\n message: (0, utils_1.bytesToHex)(ciphertext),\n },\n },\n };\n });\n}\nexports.create = create;\n/**\n * Verify the password of a keystore object\n */\nfunction verifyPassword(keystore, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const decryptionKey = yield (0, kdf_1.kdf)(keystore.crypto.kdf, (0, password_1.normalizePassword)(password));\n const ciphertext = (0, utils_1.hexToBytes)(keystore.crypto.cipher.message);\n return (0, checksum_1.verifyChecksum)(keystore.crypto.checksum, decryptionKey, ciphertext);\n });\n}\nexports.verifyPassword = verifyPassword;\n/**\n * Decrypt a keystore, returns the secret key or throws on invalid password\n */\nfunction decrypt(keystore, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const decryptionKey = yield (0, kdf_1.kdf)(keystore.crypto.kdf, (0, password_1.normalizePassword)(password));\n const ciphertext = (0, utils_1.hexToBytes)(keystore.crypto.cipher.message);\n if (!(yield (0, checksum_1.verifyChecksum)(keystore.crypto.checksum, decryptionKey, ciphertext))) {\n throw new Error(\"Invalid password\");\n }\n return (0, cipher_1.cipherDecrypt)(keystore.crypto.cipher, decryptionKey.slice(0, 16));\n });\n}\nexports.decrypt = decrypt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/functional.js?"); /***/ }), @@ -64,14 +97,36 @@ eval("\nvar __createBinding = (this && this.__createBinding) || (Object.create ? /***/ }), -/***/ "./node_modules/@chainsafe/bls-keystore/lib/kdf.js": -/*!*********************************************************!*\ - !*** ./node_modules/@chainsafe/bls-keystore/lib/kdf.js ***! - \*********************************************************/ +/***/ "./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js": +/*!***************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js ***! + \***************************************************************/ /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; -eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.kdf = exports.defaultScryptModule = exports.defaultPbkdfModule = void 0;\nconst random_1 = __webpack_require__(/*! ethereum-cryptography/random */ \"./node_modules/ethereum-cryptography/random.js\");\nconst pbkdf2_1 = __webpack_require__(/*! ethereum-cryptography/pbkdf2 */ \"./node_modules/ethereum-cryptography/pbkdf2.js\");\nconst scrypt_1 = __webpack_require__(/*! ethereum-cryptography/scrypt */ \"./node_modules/ethereum-cryptography/scrypt.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\n// default kdf configurations\nfunction defaultPbkdfModule() {\n return {\n function: \"pbkdf2\",\n params: {\n dklen: 32,\n c: 262144,\n prf: \"hmac-sha256\",\n salt: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(32)),\n },\n };\n}\nexports.defaultPbkdfModule = defaultPbkdfModule;\nfunction defaultScryptModule() {\n return {\n function: \"scrypt\",\n params: {\n dklen: 32,\n n: 262144,\n r: 8,\n p: 1,\n salt: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(32)),\n },\n };\n}\nexports.defaultScryptModule = defaultScryptModule;\n// kdf operations\nfunction kdf(mod, password) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"pbkdf2\") {\n return yield doPbkdf2(mod.params, password);\n }\n else if (mod.function === \"scrypt\") {\n return yield doScrypt(mod.params, password);\n }\n else {\n throw new Error(\"Invalid kdf type\");\n }\n });\n}\nexports.kdf = kdf;\nfunction doPbkdf2(params, password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, pbkdf2_1.pbkdf2)(password, (0, utils_1.hexToBytes)(params.salt), params.c, params.dklen, params.prf.slice(5));\n });\n}\nfunction doScrypt(params, password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, scrypt_1.scrypt)(password, (0, utils_1.hexToBytes)(params.salt), params.n, params.p, params.r, params.dklen);\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/kdf.js?"); +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.kdf = exports.defaultScryptModule = exports.defaultPbkdfModule = void 0;\nconst random_1 = __webpack_require__(/*! ethereum-cryptography/random */ \"./node_modules/ethereum-cryptography/random.js\");\nconst utils_1 = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/utils.js\");\nconst pbkdf2_1 = __webpack_require__(/*! ./pbkdf2 */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf/pbkdf2.js\");\nconst scrypt_1 = __webpack_require__(/*! ./scrypt */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf/scrypt.js\");\n// default kdf configurations\nfunction defaultPbkdfModule() {\n return {\n function: \"pbkdf2\",\n params: {\n dklen: 32,\n c: 262144,\n prf: \"hmac-sha256\",\n salt: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(32)),\n },\n };\n}\nexports.defaultPbkdfModule = defaultPbkdfModule;\nfunction defaultScryptModule() {\n return {\n function: \"scrypt\",\n params: {\n dklen: 32,\n n: 262144,\n r: 8,\n p: 1,\n salt: (0, utils_1.bytesToHex)((0, random_1.getRandomBytesSync)(32)),\n },\n };\n}\nexports.defaultScryptModule = defaultScryptModule;\n// kdf operations\nfunction kdf(mod, password) {\n return __awaiter(this, void 0, void 0, function* () {\n if (mod.function === \"pbkdf2\") {\n const { salt, c, dklen } = mod.params;\n return yield (0, pbkdf2_1.doPbkdf2)((0, utils_1.hexToBytes)(salt), c, dklen, password);\n }\n else if (mod.function === \"scrypt\") {\n const { salt, n, p, r, dklen } = mod.params;\n return yield (0, scrypt_1.doScrypt)((0, utils_1.hexToBytes)(salt), n, p, r, dklen, password);\n }\n else {\n throw new Error(\"Invalid kdf type\");\n }\n });\n}\nexports.kdf = kdf;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/bls-keystore/lib/kdf/pbkdf2.js": +/*!****************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/kdf/pbkdf2.js ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.doPbkdf2 = void 0;\nconst pbkdf2_1 = __webpack_require__(/*! ethereum-cryptography/pbkdf2 */ \"./node_modules/ethereum-cryptography/pbkdf2.js\");\nconst env_1 = __webpack_require__(/*! ../env */ \"./node_modules/@chainsafe/bls-keystore/lib/env.js\");\nexports.doPbkdf2 = env_1.isNode ? doPbkdf2Node : env_1.hasWebCrypto ? doPbkdf2WebCrypto : doPbkdf2Js;\nfunction doPbkdf2Js(salt, c, dklen, password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, pbkdf2_1.pbkdf2)(password, salt, c, dklen, \"sha256\");\n });\n}\nfunction doPbkdf2Node(salt, c, dklen, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const crypto = yield Promise.resolve().then(() => __webpack_require__(/*! crypto */ \"./node_modules/crypto-browserify/index.js\"));\n return crypto.pbkdf2Sync(password, salt, c, dklen, \"sha256\");\n });\n}\nfunction doPbkdf2WebCrypto(salt, c, dklen, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const passwordKey = yield crypto.subtle.importKey(\"raw\", password, { name: \"PBKDF2\" }, false, [\"deriveBits\"]);\n return new Uint8Array(yield crypto.subtle.deriveBits({\n name: \"PBKDF2\",\n salt,\n iterations: c,\n hash: \"SHA-256\",\n }, passwordKey, dklen * 8));\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/kdf/pbkdf2.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/bls-keystore/lib/kdf/scrypt.js": +/*!****************************************************************!*\ + !*** ./node_modules/@chainsafe/bls-keystore/lib/kdf/scrypt.js ***! + \****************************************************************/ +/***/ (function(__unused_webpack_module, exports, __webpack_require__) { + +"use strict"; +eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.doScrypt = void 0;\nconst scrypt_1 = __webpack_require__(/*! ethereum-cryptography/scrypt */ \"./node_modules/ethereum-cryptography/scrypt.js\");\nconst env_1 = __webpack_require__(/*! ../env */ \"./node_modules/@chainsafe/bls-keystore/lib/env.js\");\nexports.doScrypt = env_1.isNode ? doScryptNode : doScryptJs;\nfunction doScryptJs(salt, n, p, r, dklen, password) {\n return __awaiter(this, void 0, void 0, function* () {\n return (0, scrypt_1.scrypt)(password, salt, n, p, r, dklen);\n });\n}\nfunction doScryptNode(salt, n, p, r, dklen, password) {\n return __awaiter(this, void 0, void 0, function* () {\n const crypto = yield Promise.resolve().then(() => __webpack_require__(/*! crypto */ \"./node_modules/crypto-browserify/index.js\"));\n return crypto.scryptSync(password, salt, dklen, {\n N: n,\n r,\n p,\n maxmem: n * r * 256,\n });\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/bls-keystore/lib/kdf/scrypt.js?"); /***/ }), @@ -565,7 +620,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac \********************************************************************************/ /***/ ((module, exports, __webpack_require__) => { -eval("var __WEBPACK_AMD_DEFINE_RESULT__;/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.8.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {\n Array.isArray = function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n };\n }\n\n if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n ArrayBuffer.isView = function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n };\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (!n && !s) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var notString, type = typeof message;\n if (type !== 'string') {\n if (type === 'object') {\n if (message === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n message = new Uint8Array(message);\n } else if (!Array.isArray(message)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (notString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var notString, type = typeof str;\n if (type !== 'string') {\n if (type === 'object') {\n if (str === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {\n str = new Uint8Array(str);\n } else if (!Array.isArray(str)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var bytes = 0, length = str.length;\n if (notString) {\n bytes = length;\n } else {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = w - bytes % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n array[i] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return methods;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@ethersproject/keccak256/node_modules/js-sha3/src/sha3.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\nvar __WEBPACK_AMD_DEFINE_RESULT__;/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.8.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) {\n Array.isArray = function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n };\n }\n\n if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n ArrayBuffer.isView = function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n };\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (!n && !s) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var notString, type = typeof message;\n if (type !== 'string') {\n if (type === 'object') {\n if (message === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n message = new Uint8Array(message);\n } else if (!Array.isArray(message)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (notString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var notString, type = typeof str;\n if (type !== 'string') {\n if (type === 'object') {\n if (str === null) {\n throw new Error(INPUT_ERROR);\n } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) {\n str = new Uint8Array(str);\n } else if (!Array.isArray(str)) {\n if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) {\n throw new Error(INPUT_ERROR);\n }\n }\n } else {\n throw new Error(INPUT_ERROR);\n }\n notString = true;\n }\n var bytes = 0, length = str.length;\n if (notString) {\n bytes = length;\n } else {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = w - bytes % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n array[i] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return methods;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@ethersproject/keccak256/node_modules/js-sha3/src/sha3.js?"); /***/ }), @@ -976,6 +1031,156 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/asn1.js/lib/asn1.js": +/*!******************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1.js ***! + \******************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var asn1 = exports;\n\nasn1.bignum = __webpack_require__(/*! bn.js */ \"./node_modules/asn1.js/node_modules/bn.js/lib/bn.js\");\n\nasn1.define = (__webpack_require__(/*! ./asn1/api */ \"./node_modules/asn1.js/lib/asn1/api.js\").define);\nasn1.base = __webpack_require__(/*! ./asn1/base */ \"./node_modules/asn1.js/lib/asn1/base/index.js\");\nasn1.constants = __webpack_require__(/*! ./asn1/constants */ \"./node_modules/asn1.js/lib/asn1/constants/index.js\");\nasn1.decoders = __webpack_require__(/*! ./asn1/decoders */ \"./node_modules/asn1.js/lib/asn1/decoders/index.js\");\nasn1.encoders = __webpack_require__(/*! ./asn1/encoders */ \"./node_modules/asn1.js/lib/asn1/encoders/index.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/api.js": +/*!**********************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/api.js ***! + \**********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var asn1 = __webpack_require__(/*! ../asn1 */ \"./node_modules/asn1.js/lib/asn1.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar api = exports;\n\napi.define = function define(name, body) {\n return new Entity(name, body);\n};\n\nfunction Entity(name, body) {\n this.name = name;\n this.body = body;\n\n this.decoders = {};\n this.encoders = {};\n};\n\nEntity.prototype._createNamed = function createNamed(base) {\n var named;\n try {\n named = (__webpack_require__(/*! vm */ \"./node_modules/vm-browserify/index.js\").runInThisContext)(\n '(function ' + this.name + '(entity) {\\n' +\n ' this._initNamed(entity);\\n' +\n '})'\n );\n } catch (e) {\n named = function (entity) {\n this._initNamed(entity);\n };\n }\n inherits(named, base);\n named.prototype._initNamed = function initnamed(entity) {\n base.call(this, entity);\n };\n\n return new named(this);\n};\n\nEntity.prototype._getDecoder = function _getDecoder(enc) {\n enc = enc || 'der';\n // Lazily create decoder\n if (!this.decoders.hasOwnProperty(enc))\n this.decoders[enc] = this._createNamed(asn1.decoders[enc]);\n return this.decoders[enc];\n};\n\nEntity.prototype.decode = function decode(data, enc, options) {\n return this._getDecoder(enc).decode(data, options);\n};\n\nEntity.prototype._getEncoder = function _getEncoder(enc) {\n enc = enc || 'der';\n // Lazily create encoder\n if (!this.encoders.hasOwnProperty(enc))\n this.encoders[enc] = this._createNamed(asn1.encoders[enc]);\n return this.encoders[enc];\n};\n\nEntity.prototype.encode = function encode(data, enc, /* internal */ reporter) {\n return this._getEncoder(enc).encode(data, reporter);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/api.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/base/buffer.js": +/*!******************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/base/buffer.js ***! + \******************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Reporter = (__webpack_require__(/*! ../base */ \"./node_modules/asn1.js/lib/asn1/base/index.js\").Reporter);\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer);\n\nfunction DecoderBuffer(base, options) {\n Reporter.call(this, options);\n if (!Buffer.isBuffer(base)) {\n this.error('Input not Buffer');\n return;\n }\n\n this.base = base;\n this.offset = 0;\n this.length = base.length;\n}\ninherits(DecoderBuffer, Reporter);\nexports.DecoderBuffer = DecoderBuffer;\n\nDecoderBuffer.prototype.save = function save() {\n return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };\n};\n\nDecoderBuffer.prototype.restore = function restore(save) {\n // Return skipped data\n var res = new DecoderBuffer(this.base);\n res.offset = save.offset;\n res.length = this.offset;\n\n this.offset = save.offset;\n Reporter.prototype.restore.call(this, save.reporter);\n\n return res;\n};\n\nDecoderBuffer.prototype.isEmpty = function isEmpty() {\n return this.offset === this.length;\n};\n\nDecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {\n if (this.offset + 1 <= this.length)\n return this.base.readUInt8(this.offset++, true);\n else\n return this.error(fail || 'DecoderBuffer overrun');\n}\n\nDecoderBuffer.prototype.skip = function skip(bytes, fail) {\n if (!(this.offset + bytes <= this.length))\n return this.error(fail || 'DecoderBuffer overrun');\n\n var res = new DecoderBuffer(this.base);\n\n // Share reporter state\n res._reporterState = this._reporterState;\n\n res.offset = this.offset;\n res.length = this.offset + bytes;\n this.offset += bytes;\n return res;\n}\n\nDecoderBuffer.prototype.raw = function raw(save) {\n return this.base.slice(save ? save.offset : this.offset, this.length);\n}\n\nfunction EncoderBuffer(value, reporter) {\n if (Array.isArray(value)) {\n this.length = 0;\n this.value = value.map(function(item) {\n if (!(item instanceof EncoderBuffer))\n item = new EncoderBuffer(item, reporter);\n this.length += item.length;\n return item;\n }, this);\n } else if (typeof value === 'number') {\n if (!(0 <= value && value <= 0xff))\n return reporter.error('non-byte EncoderBuffer value');\n this.value = value;\n this.length = 1;\n } else if (typeof value === 'string') {\n this.value = value;\n this.length = Buffer.byteLength(value);\n } else if (Buffer.isBuffer(value)) {\n this.value = value;\n this.length = value.length;\n } else {\n return reporter.error('Unsupported type: ' + typeof value);\n }\n}\nexports.EncoderBuffer = EncoderBuffer;\n\nEncoderBuffer.prototype.join = function join(out, offset) {\n if (!out)\n out = new Buffer(this.length);\n if (!offset)\n offset = 0;\n\n if (this.length === 0)\n return out;\n\n if (Array.isArray(this.value)) {\n this.value.forEach(function(item) {\n item.join(out, offset);\n offset += item.length;\n });\n } else {\n if (typeof this.value === 'number')\n out[offset] = this.value;\n else if (typeof this.value === 'string')\n out.write(this.value, offset);\n else if (Buffer.isBuffer(this.value))\n this.value.copy(out, offset);\n offset += this.length;\n }\n\n return out;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/base/buffer.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/base/index.js": +/*!*****************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/base/index.js ***! + \*****************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var base = exports;\n\nbase.Reporter = (__webpack_require__(/*! ./reporter */ \"./node_modules/asn1.js/lib/asn1/base/reporter.js\").Reporter);\nbase.DecoderBuffer = (__webpack_require__(/*! ./buffer */ \"./node_modules/asn1.js/lib/asn1/base/buffer.js\").DecoderBuffer);\nbase.EncoderBuffer = (__webpack_require__(/*! ./buffer */ \"./node_modules/asn1.js/lib/asn1/base/buffer.js\").EncoderBuffer);\nbase.Node = __webpack_require__(/*! ./node */ \"./node_modules/asn1.js/lib/asn1/base/node.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/base/index.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/base/node.js": +/*!****************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/base/node.js ***! + \****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Reporter = (__webpack_require__(/*! ../base */ \"./node_modules/asn1.js/lib/asn1/base/index.js\").Reporter);\nvar EncoderBuffer = (__webpack_require__(/*! ../base */ \"./node_modules/asn1.js/lib/asn1/base/index.js\").EncoderBuffer);\nvar DecoderBuffer = (__webpack_require__(/*! ../base */ \"./node_modules/asn1.js/lib/asn1/base/index.js\").DecoderBuffer);\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\n\n// Supported tags\nvar tags = [\n 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',\n 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',\n 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',\n 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'\n];\n\n// Public methods list\nvar methods = [\n 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',\n 'any', 'contains'\n].concat(tags);\n\n// Overrided methods list\nvar overrided = [\n '_peekTag', '_decodeTag', '_use',\n '_decodeStr', '_decodeObjid', '_decodeTime',\n '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',\n\n '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',\n '_encodeNull', '_encodeInt', '_encodeBool'\n];\n\nfunction Node(enc, parent) {\n var state = {};\n this._baseState = state;\n\n state.enc = enc;\n\n state.parent = parent || null;\n state.children = null;\n\n // State\n state.tag = null;\n state.args = null;\n state.reverseArgs = null;\n state.choice = null;\n state.optional = false;\n state.any = false;\n state.obj = false;\n state.use = null;\n state.useDecoder = null;\n state.key = null;\n state['default'] = null;\n state.explicit = null;\n state.implicit = null;\n state.contains = null;\n\n // Should create new instance on each method\n if (!state.parent) {\n state.children = [];\n this._wrap();\n }\n}\nmodule.exports = Node;\n\nvar stateProps = [\n 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',\n 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',\n 'implicit', 'contains'\n];\n\nNode.prototype.clone = function clone() {\n var state = this._baseState;\n var cstate = {};\n stateProps.forEach(function(prop) {\n cstate[prop] = state[prop];\n });\n var res = new this.constructor(cstate.parent);\n res._baseState = cstate;\n return res;\n};\n\nNode.prototype._wrap = function wrap() {\n var state = this._baseState;\n methods.forEach(function(method) {\n this[method] = function _wrappedMethod() {\n var clone = new this.constructor(this);\n state.children.push(clone);\n return clone[method].apply(clone, arguments);\n };\n }, this);\n};\n\nNode.prototype._init = function init(body) {\n var state = this._baseState;\n\n assert(state.parent === null);\n body.call(this);\n\n // Filter children\n state.children = state.children.filter(function(child) {\n return child._baseState.parent === this;\n }, this);\n assert.equal(state.children.length, 1, 'Root node can have only one child');\n};\n\nNode.prototype._useArgs = function useArgs(args) {\n var state = this._baseState;\n\n // Filter children and args\n var children = args.filter(function(arg) {\n return arg instanceof this.constructor;\n }, this);\n args = args.filter(function(arg) {\n return !(arg instanceof this.constructor);\n }, this);\n\n if (children.length !== 0) {\n assert(state.children === null);\n state.children = children;\n\n // Replace parent to maintain backward link\n children.forEach(function(child) {\n child._baseState.parent = this;\n }, this);\n }\n if (args.length !== 0) {\n assert(state.args === null);\n state.args = args;\n state.reverseArgs = args.map(function(arg) {\n if (typeof arg !== 'object' || arg.constructor !== Object)\n return arg;\n\n var res = {};\n Object.keys(arg).forEach(function(key) {\n if (key == (key | 0))\n key |= 0;\n var value = arg[key];\n res[value] = key;\n });\n return res;\n });\n }\n};\n\n//\n// Overrided methods\n//\n\noverrided.forEach(function(method) {\n Node.prototype[method] = function _overrided() {\n var state = this._baseState;\n throw new Error(method + ' not implemented for encoding: ' + state.enc);\n };\n});\n\n//\n// Public methods\n//\n\ntags.forEach(function(tag) {\n Node.prototype[tag] = function _tagMethod() {\n var state = this._baseState;\n var args = Array.prototype.slice.call(arguments);\n\n assert(state.tag === null);\n state.tag = tag;\n\n this._useArgs(args);\n\n return this;\n };\n});\n\nNode.prototype.use = function use(item) {\n assert(item);\n var state = this._baseState;\n\n assert(state.use === null);\n state.use = item;\n\n return this;\n};\n\nNode.prototype.optional = function optional() {\n var state = this._baseState;\n\n state.optional = true;\n\n return this;\n};\n\nNode.prototype.def = function def(val) {\n var state = this._baseState;\n\n assert(state['default'] === null);\n state['default'] = val;\n state.optional = true;\n\n return this;\n};\n\nNode.prototype.explicit = function explicit(num) {\n var state = this._baseState;\n\n assert(state.explicit === null && state.implicit === null);\n state.explicit = num;\n\n return this;\n};\n\nNode.prototype.implicit = function implicit(num) {\n var state = this._baseState;\n\n assert(state.explicit === null && state.implicit === null);\n state.implicit = num;\n\n return this;\n};\n\nNode.prototype.obj = function obj() {\n var state = this._baseState;\n var args = Array.prototype.slice.call(arguments);\n\n state.obj = true;\n\n if (args.length !== 0)\n this._useArgs(args);\n\n return this;\n};\n\nNode.prototype.key = function key(newKey) {\n var state = this._baseState;\n\n assert(state.key === null);\n state.key = newKey;\n\n return this;\n};\n\nNode.prototype.any = function any() {\n var state = this._baseState;\n\n state.any = true;\n\n return this;\n};\n\nNode.prototype.choice = function choice(obj) {\n var state = this._baseState;\n\n assert(state.choice === null);\n state.choice = obj;\n this._useArgs(Object.keys(obj).map(function(key) {\n return obj[key];\n }));\n\n return this;\n};\n\nNode.prototype.contains = function contains(item) {\n var state = this._baseState;\n\n assert(state.use === null);\n state.contains = item;\n\n return this;\n};\n\n//\n// Decoding\n//\n\nNode.prototype._decode = function decode(input, options) {\n var state = this._baseState;\n\n // Decode root node\n if (state.parent === null)\n return input.wrapResult(state.children[0]._decode(input, options));\n\n var result = state['default'];\n var present = true;\n\n var prevKey = null;\n if (state.key !== null)\n prevKey = input.enterKey(state.key);\n\n // Check if tag is there\n if (state.optional) {\n var tag = null;\n if (state.explicit !== null)\n tag = state.explicit;\n else if (state.implicit !== null)\n tag = state.implicit;\n else if (state.tag !== null)\n tag = state.tag;\n\n if (tag === null && !state.any) {\n // Trial and Error\n var save = input.save();\n try {\n if (state.choice === null)\n this._decodeGeneric(state.tag, input, options);\n else\n this._decodeChoice(input, options);\n present = true;\n } catch (e) {\n present = false;\n }\n input.restore(save);\n } else {\n present = this._peekTag(input, tag, state.any);\n\n if (input.isError(present))\n return present;\n }\n }\n\n // Push object on stack\n var prevObj;\n if (state.obj && present)\n prevObj = input.enterObject();\n\n if (present) {\n // Unwrap explicit values\n if (state.explicit !== null) {\n var explicit = this._decodeTag(input, state.explicit);\n if (input.isError(explicit))\n return explicit;\n input = explicit;\n }\n\n var start = input.offset;\n\n // Unwrap implicit and normal values\n if (state.use === null && state.choice === null) {\n if (state.any)\n var save = input.save();\n var body = this._decodeTag(\n input,\n state.implicit !== null ? state.implicit : state.tag,\n state.any\n );\n if (input.isError(body))\n return body;\n\n if (state.any)\n result = input.raw(save);\n else\n input = body;\n }\n\n if (options && options.track && state.tag !== null)\n options.track(input.path(), start, input.length, 'tagged');\n\n if (options && options.track && state.tag !== null)\n options.track(input.path(), input.offset, input.length, 'content');\n\n // Select proper method for tag\n if (state.any)\n result = result;\n else if (state.choice === null)\n result = this._decodeGeneric(state.tag, input, options);\n else\n result = this._decodeChoice(input, options);\n\n if (input.isError(result))\n return result;\n\n // Decode children\n if (!state.any && state.choice === null && state.children !== null) {\n state.children.forEach(function decodeChildren(child) {\n // NOTE: We are ignoring errors here, to let parser continue with other\n // parts of encoded data\n child._decode(input, options);\n });\n }\n\n // Decode contained/encoded by schema, only in bit or octet strings\n if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {\n var data = new DecoderBuffer(result);\n result = this._getUse(state.contains, input._reporterState.obj)\n ._decode(data, options);\n }\n }\n\n // Pop object\n if (state.obj && present)\n result = input.leaveObject(prevObj);\n\n // Set key\n if (state.key !== null && (result !== null || present === true))\n input.leaveKey(prevKey, state.key, result);\n else if (prevKey !== null)\n input.exitKey(prevKey);\n\n return result;\n};\n\nNode.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {\n var state = this._baseState;\n\n if (tag === 'seq' || tag === 'set')\n return null;\n if (tag === 'seqof' || tag === 'setof')\n return this._decodeList(input, tag, state.args[0], options);\n else if (/str$/.test(tag))\n return this._decodeStr(input, tag, options);\n else if (tag === 'objid' && state.args)\n return this._decodeObjid(input, state.args[0], state.args[1], options);\n else if (tag === 'objid')\n return this._decodeObjid(input, null, null, options);\n else if (tag === 'gentime' || tag === 'utctime')\n return this._decodeTime(input, tag, options);\n else if (tag === 'null_')\n return this._decodeNull(input, options);\n else if (tag === 'bool')\n return this._decodeBool(input, options);\n else if (tag === 'objDesc')\n return this._decodeStr(input, tag, options);\n else if (tag === 'int' || tag === 'enum')\n return this._decodeInt(input, state.args && state.args[0], options);\n\n if (state.use !== null) {\n return this._getUse(state.use, input._reporterState.obj)\n ._decode(input, options);\n } else {\n return input.error('unknown tag: ' + tag);\n }\n};\n\nNode.prototype._getUse = function _getUse(entity, obj) {\n\n var state = this._baseState;\n // Create altered use decoder if implicit is set\n state.useDecoder = this._use(entity, obj);\n assert(state.useDecoder._baseState.parent === null);\n state.useDecoder = state.useDecoder._baseState.children[0];\n if (state.implicit !== state.useDecoder._baseState.implicit) {\n state.useDecoder = state.useDecoder.clone();\n state.useDecoder._baseState.implicit = state.implicit;\n }\n return state.useDecoder;\n};\n\nNode.prototype._decodeChoice = function decodeChoice(input, options) {\n var state = this._baseState;\n var result = null;\n var match = false;\n\n Object.keys(state.choice).some(function(key) {\n var save = input.save();\n var node = state.choice[key];\n try {\n var value = node._decode(input, options);\n if (input.isError(value))\n return false;\n\n result = { type: key, value: value };\n match = true;\n } catch (e) {\n input.restore(save);\n return false;\n }\n return true;\n }, this);\n\n if (!match)\n return input.error('Choice not matched');\n\n return result;\n};\n\n//\n// Encoding\n//\n\nNode.prototype._createEncoderBuffer = function createEncoderBuffer(data) {\n return new EncoderBuffer(data, this.reporter);\n};\n\nNode.prototype._encode = function encode(data, reporter, parent) {\n var state = this._baseState;\n if (state['default'] !== null && state['default'] === data)\n return;\n\n var result = this._encodeValue(data, reporter, parent);\n if (result === undefined)\n return;\n\n if (this._skipDefault(result, reporter, parent))\n return;\n\n return result;\n};\n\nNode.prototype._encodeValue = function encode(data, reporter, parent) {\n var state = this._baseState;\n\n // Decode root node\n if (state.parent === null)\n return state.children[0]._encode(data, reporter || new Reporter());\n\n var result = null;\n\n // Set reporter to share it with a child class\n this.reporter = reporter;\n\n // Check if data is there\n if (state.optional && data === undefined) {\n if (state['default'] !== null)\n data = state['default']\n else\n return;\n }\n\n // Encode children first\n var content = null;\n var primitive = false;\n if (state.any) {\n // Anything that was given is translated to buffer\n result = this._createEncoderBuffer(data);\n } else if (state.choice) {\n result = this._encodeChoice(data, reporter);\n } else if (state.contains) {\n content = this._getUse(state.contains, parent)._encode(data, reporter);\n primitive = true;\n } else if (state.children) {\n content = state.children.map(function(child) {\n if (child._baseState.tag === 'null_')\n return child._encode(null, reporter, data);\n\n if (child._baseState.key === null)\n return reporter.error('Child should have a key');\n var prevKey = reporter.enterKey(child._baseState.key);\n\n if (typeof data !== 'object')\n return reporter.error('Child expected, but input is not object');\n\n var res = child._encode(data[child._baseState.key], reporter, data);\n reporter.leaveKey(prevKey);\n\n return res;\n }, this).filter(function(child) {\n return child;\n });\n content = this._createEncoderBuffer(content);\n } else {\n if (state.tag === 'seqof' || state.tag === 'setof') {\n // TODO(indutny): this should be thrown on DSL level\n if (!(state.args && state.args.length === 1))\n return reporter.error('Too many args for : ' + state.tag);\n\n if (!Array.isArray(data))\n return reporter.error('seqof/setof, but data is not Array');\n\n var child = this.clone();\n child._baseState.implicit = null;\n content = this._createEncoderBuffer(data.map(function(item) {\n var state = this._baseState;\n\n return this._getUse(state.args[0], data)._encode(item, reporter);\n }, child));\n } else if (state.use !== null) {\n result = this._getUse(state.use, parent)._encode(data, reporter);\n } else {\n content = this._encodePrimitive(state.tag, data);\n primitive = true;\n }\n }\n\n // Encode data itself\n var result;\n if (!state.any && state.choice === null) {\n var tag = state.implicit !== null ? state.implicit : state.tag;\n var cls = state.implicit === null ? 'universal' : 'context';\n\n if (tag === null) {\n if (state.use === null)\n reporter.error('Tag could be omitted only for .use()');\n } else {\n if (state.use === null)\n result = this._encodeComposite(tag, primitive, cls, content);\n }\n }\n\n // Wrap in explicit\n if (state.explicit !== null)\n result = this._encodeComposite(state.explicit, false, 'context', result);\n\n return result;\n};\n\nNode.prototype._encodeChoice = function encodeChoice(data, reporter) {\n var state = this._baseState;\n\n var node = state.choice[data.type];\n if (!node) {\n assert(\n false,\n data.type + ' not found in ' +\n JSON.stringify(Object.keys(state.choice)));\n }\n return node._encode(data.value, reporter);\n};\n\nNode.prototype._encodePrimitive = function encodePrimitive(tag, data) {\n var state = this._baseState;\n\n if (/str$/.test(tag))\n return this._encodeStr(data, tag);\n else if (tag === 'objid' && state.args)\n return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);\n else if (tag === 'objid')\n return this._encodeObjid(data, null, null);\n else if (tag === 'gentime' || tag === 'utctime')\n return this._encodeTime(data, tag);\n else if (tag === 'null_')\n return this._encodeNull();\n else if (tag === 'int' || tag === 'enum')\n return this._encodeInt(data, state.args && state.reverseArgs[0]);\n else if (tag === 'bool')\n return this._encodeBool(data);\n else if (tag === 'objDesc')\n return this._encodeStr(data, tag);\n else\n throw new Error('Unsupported tag: ' + tag);\n};\n\nNode.prototype._isNumstr = function isNumstr(str) {\n return /^[0-9 ]*$/.test(str);\n};\n\nNode.prototype._isPrintstr = function isPrintstr(str) {\n return /^[A-Za-z0-9 '\\(\\)\\+,\\-\\.\\/:=\\?]*$/.test(str);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/base/node.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/base/reporter.js": +/*!********************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/base/reporter.js ***! + \********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nfunction Reporter(options) {\n this._reporterState = {\n obj: null,\n path: [],\n options: options || {},\n errors: []\n };\n}\nexports.Reporter = Reporter;\n\nReporter.prototype.isError = function isError(obj) {\n return obj instanceof ReporterError;\n};\n\nReporter.prototype.save = function save() {\n var state = this._reporterState;\n\n return { obj: state.obj, pathLen: state.path.length };\n};\n\nReporter.prototype.restore = function restore(data) {\n var state = this._reporterState;\n\n state.obj = data.obj;\n state.path = state.path.slice(0, data.pathLen);\n};\n\nReporter.prototype.enterKey = function enterKey(key) {\n return this._reporterState.path.push(key);\n};\n\nReporter.prototype.exitKey = function exitKey(index) {\n var state = this._reporterState;\n\n state.path = state.path.slice(0, index - 1);\n};\n\nReporter.prototype.leaveKey = function leaveKey(index, key, value) {\n var state = this._reporterState;\n\n this.exitKey(index);\n if (state.obj !== null)\n state.obj[key] = value;\n};\n\nReporter.prototype.path = function path() {\n return this._reporterState.path.join('/');\n};\n\nReporter.prototype.enterObject = function enterObject() {\n var state = this._reporterState;\n\n var prev = state.obj;\n state.obj = {};\n return prev;\n};\n\nReporter.prototype.leaveObject = function leaveObject(prev) {\n var state = this._reporterState;\n\n var now = state.obj;\n state.obj = prev;\n return now;\n};\n\nReporter.prototype.error = function error(msg) {\n var err;\n var state = this._reporterState;\n\n var inherited = msg instanceof ReporterError;\n if (inherited) {\n err = msg;\n } else {\n err = new ReporterError(state.path.map(function(elem) {\n return '[' + JSON.stringify(elem) + ']';\n }).join(''), msg.message || msg, msg.stack);\n }\n\n if (!state.options.partial)\n throw err;\n\n if (!inherited)\n state.errors.push(err);\n\n return err;\n};\n\nReporter.prototype.wrapResult = function wrapResult(result) {\n var state = this._reporterState;\n if (!state.options.partial)\n return result;\n\n return {\n result: this.isError(result) ? null : result,\n errors: state.errors\n };\n};\n\nfunction ReporterError(path, msg) {\n this.path = path;\n this.rethrow(msg);\n};\ninherits(ReporterError, Error);\n\nReporterError.prototype.rethrow = function rethrow(msg) {\n this.message = msg + ' at: ' + (this.path || '(shallow)');\n if (Error.captureStackTrace)\n Error.captureStackTrace(this, ReporterError);\n\n if (!this.stack) {\n try {\n // IE only adds stack when thrown\n throw new Error(this.message);\n } catch (e) {\n this.stack = e.stack;\n }\n }\n return this;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/base/reporter.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/constants/der.js": +/*!********************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/constants/der.js ***! + \********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var constants = __webpack_require__(/*! ../constants */ \"./node_modules/asn1.js/lib/asn1/constants/index.js\");\n\nexports.tagClass = {\n 0: 'universal',\n 1: 'application',\n 2: 'context',\n 3: 'private'\n};\nexports.tagClassByName = constants._reverse(exports.tagClass);\n\nexports.tag = {\n 0x00: 'end',\n 0x01: 'bool',\n 0x02: 'int',\n 0x03: 'bitstr',\n 0x04: 'octstr',\n 0x05: 'null_',\n 0x06: 'objid',\n 0x07: 'objDesc',\n 0x08: 'external',\n 0x09: 'real',\n 0x0a: 'enum',\n 0x0b: 'embed',\n 0x0c: 'utf8str',\n 0x0d: 'relativeOid',\n 0x10: 'seq',\n 0x11: 'set',\n 0x12: 'numstr',\n 0x13: 'printstr',\n 0x14: 't61str',\n 0x15: 'videostr',\n 0x16: 'ia5str',\n 0x17: 'utctime',\n 0x18: 'gentime',\n 0x19: 'graphstr',\n 0x1a: 'iso646str',\n 0x1b: 'genstr',\n 0x1c: 'unistr',\n 0x1d: 'charstr',\n 0x1e: 'bmpstr'\n};\nexports.tagByName = constants._reverse(exports.tag);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/constants/der.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/constants/index.js": +/*!**********************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/constants/index.js ***! + \**********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var constants = exports;\n\n// Helper\nconstants._reverse = function reverse(map) {\n var res = {};\n\n Object.keys(map).forEach(function(key) {\n // Convert key to integer if it is stringified\n if ((key | 0) == key)\n key = key | 0;\n\n var value = map[key];\n res[value] = key;\n });\n\n return res;\n};\n\nconstants.der = __webpack_require__(/*! ./der */ \"./node_modules/asn1.js/lib/asn1/constants/der.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/constants/index.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/decoders/der.js": +/*!*******************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/decoders/der.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar asn1 = __webpack_require__(/*! ../../asn1 */ \"./node_modules/asn1.js/lib/asn1.js\");\nvar base = asn1.base;\nvar bignum = asn1.bignum;\n\n// Import DER constants\nvar der = asn1.constants.der;\n\nfunction DERDecoder(entity) {\n this.enc = 'der';\n this.name = entity.name;\n this.entity = entity;\n\n // Construct base tree\n this.tree = new DERNode();\n this.tree._init(entity.body);\n};\nmodule.exports = DERDecoder;\n\nDERDecoder.prototype.decode = function decode(data, options) {\n if (!(data instanceof base.DecoderBuffer))\n data = new base.DecoderBuffer(data, options);\n\n return this.tree._decode(data, options);\n};\n\n// Tree methods\n\nfunction DERNode(parent) {\n base.Node.call(this, 'der', parent);\n}\ninherits(DERNode, base.Node);\n\nDERNode.prototype._peekTag = function peekTag(buffer, tag, any) {\n if (buffer.isEmpty())\n return false;\n\n var state = buffer.save();\n var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: \"' + tag + '\"');\n if (buffer.isError(decodedTag))\n return decodedTag;\n\n buffer.restore(state);\n\n return decodedTag.tag === tag || decodedTag.tagStr === tag ||\n (decodedTag.tagStr + 'of') === tag || any;\n};\n\nDERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {\n var decodedTag = derDecodeTag(buffer,\n 'Failed to decode tag of \"' + tag + '\"');\n if (buffer.isError(decodedTag))\n return decodedTag;\n\n var len = derDecodeLen(buffer,\n decodedTag.primitive,\n 'Failed to get length of \"' + tag + '\"');\n\n // Failure\n if (buffer.isError(len))\n return len;\n\n if (!any &&\n decodedTag.tag !== tag &&\n decodedTag.tagStr !== tag &&\n decodedTag.tagStr + 'of' !== tag) {\n return buffer.error('Failed to match tag: \"' + tag + '\"');\n }\n\n if (decodedTag.primitive || len !== null)\n return buffer.skip(len, 'Failed to match body of: \"' + tag + '\"');\n\n // Indefinite length... find END tag\n var state = buffer.save();\n var res = this._skipUntilEnd(\n buffer,\n 'Failed to skip indefinite length body: \"' + this.tag + '\"');\n if (buffer.isError(res))\n return res;\n\n len = buffer.offset - state.offset;\n buffer.restore(state);\n return buffer.skip(len, 'Failed to match body of: \"' + tag + '\"');\n};\n\nDERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {\n while (true) {\n var tag = derDecodeTag(buffer, fail);\n if (buffer.isError(tag))\n return tag;\n var len = derDecodeLen(buffer, tag.primitive, fail);\n if (buffer.isError(len))\n return len;\n\n var res;\n if (tag.primitive || len !== null)\n res = buffer.skip(len)\n else\n res = this._skipUntilEnd(buffer, fail);\n\n // Failure\n if (buffer.isError(res))\n return res;\n\n if (tag.tagStr === 'end')\n break;\n }\n};\n\nDERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,\n options) {\n var result = [];\n while (!buffer.isEmpty()) {\n var possibleEnd = this._peekTag(buffer, 'end');\n if (buffer.isError(possibleEnd))\n return possibleEnd;\n\n var res = decoder.decode(buffer, 'der', options);\n if (buffer.isError(res) && possibleEnd)\n break;\n result.push(res);\n }\n return result;\n};\n\nDERNode.prototype._decodeStr = function decodeStr(buffer, tag) {\n if (tag === 'bitstr') {\n var unused = buffer.readUInt8();\n if (buffer.isError(unused))\n return unused;\n return { unused: unused, data: buffer.raw() };\n } else if (tag === 'bmpstr') {\n var raw = buffer.raw();\n if (raw.length % 2 === 1)\n return buffer.error('Decoding of string type: bmpstr length mismatch');\n\n var str = '';\n for (var i = 0; i < raw.length / 2; i++) {\n str += String.fromCharCode(raw.readUInt16BE(i * 2));\n }\n return str;\n } else if (tag === 'numstr') {\n var numstr = buffer.raw().toString('ascii');\n if (!this._isNumstr(numstr)) {\n return buffer.error('Decoding of string type: ' +\n 'numstr unsupported characters');\n }\n return numstr;\n } else if (tag === 'octstr') {\n return buffer.raw();\n } else if (tag === 'objDesc') {\n return buffer.raw();\n } else if (tag === 'printstr') {\n var printstr = buffer.raw().toString('ascii');\n if (!this._isPrintstr(printstr)) {\n return buffer.error('Decoding of string type: ' +\n 'printstr unsupported characters');\n }\n return printstr;\n } else if (/str$/.test(tag)) {\n return buffer.raw().toString();\n } else {\n return buffer.error('Decoding of string type: ' + tag + ' unsupported');\n }\n};\n\nDERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {\n var result;\n var identifiers = [];\n var ident = 0;\n while (!buffer.isEmpty()) {\n var subident = buffer.readUInt8();\n ident <<= 7;\n ident |= subident & 0x7f;\n if ((subident & 0x80) === 0) {\n identifiers.push(ident);\n ident = 0;\n }\n }\n if (subident & 0x80)\n identifiers.push(ident);\n\n var first = (identifiers[0] / 40) | 0;\n var second = identifiers[0] % 40;\n\n if (relative)\n result = identifiers;\n else\n result = [first, second].concat(identifiers.slice(1));\n\n if (values) {\n var tmp = values[result.join(' ')];\n if (tmp === undefined)\n tmp = values[result.join('.')];\n if (tmp !== undefined)\n result = tmp;\n }\n\n return result;\n};\n\nDERNode.prototype._decodeTime = function decodeTime(buffer, tag) {\n var str = buffer.raw().toString();\n if (tag === 'gentime') {\n var year = str.slice(0, 4) | 0;\n var mon = str.slice(4, 6) | 0;\n var day = str.slice(6, 8) | 0;\n var hour = str.slice(8, 10) | 0;\n var min = str.slice(10, 12) | 0;\n var sec = str.slice(12, 14) | 0;\n } else if (tag === 'utctime') {\n var year = str.slice(0, 2) | 0;\n var mon = str.slice(2, 4) | 0;\n var day = str.slice(4, 6) | 0;\n var hour = str.slice(6, 8) | 0;\n var min = str.slice(8, 10) | 0;\n var sec = str.slice(10, 12) | 0;\n if (year < 70)\n year = 2000 + year;\n else\n year = 1900 + year;\n } else {\n return buffer.error('Decoding ' + tag + ' time is not supported yet');\n }\n\n return Date.UTC(year, mon - 1, day, hour, min, sec, 0);\n};\n\nDERNode.prototype._decodeNull = function decodeNull(buffer) {\n return null;\n};\n\nDERNode.prototype._decodeBool = function decodeBool(buffer) {\n var res = buffer.readUInt8();\n if (buffer.isError(res))\n return res;\n else\n return res !== 0;\n};\n\nDERNode.prototype._decodeInt = function decodeInt(buffer, values) {\n // Bigint, return as it is (assume big endian)\n var raw = buffer.raw();\n var res = new bignum(raw);\n\n if (values)\n res = values[res.toString(10)] || res;\n\n return res;\n};\n\nDERNode.prototype._use = function use(entity, obj) {\n if (typeof entity === 'function')\n entity = entity(obj);\n return entity._getDecoder('der').tree;\n};\n\n// Utility methods\n\nfunction derDecodeTag(buf, fail) {\n var tag = buf.readUInt8(fail);\n if (buf.isError(tag))\n return tag;\n\n var cls = der.tagClass[tag >> 6];\n var primitive = (tag & 0x20) === 0;\n\n // Multi-octet tag - load\n if ((tag & 0x1f) === 0x1f) {\n var oct = tag;\n tag = 0;\n while ((oct & 0x80) === 0x80) {\n oct = buf.readUInt8(fail);\n if (buf.isError(oct))\n return oct;\n\n tag <<= 7;\n tag |= oct & 0x7f;\n }\n } else {\n tag &= 0x1f;\n }\n var tagStr = der.tag[tag];\n\n return {\n cls: cls,\n primitive: primitive,\n tag: tag,\n tagStr: tagStr\n };\n}\n\nfunction derDecodeLen(buf, primitive, fail) {\n var len = buf.readUInt8(fail);\n if (buf.isError(len))\n return len;\n\n // Indefinite form\n if (!primitive && len === 0x80)\n return null;\n\n // Definite form\n if ((len & 0x80) === 0) {\n // Short form\n return len;\n }\n\n // Long form\n var num = len & 0x7f;\n if (num > 4)\n return buf.error('length octect is too long');\n\n len = 0;\n for (var i = 0; i < num; i++) {\n len <<= 8;\n var j = buf.readUInt8(fail);\n if (buf.isError(j))\n return j;\n len |= j;\n }\n\n return len;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/decoders/der.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/decoders/index.js": +/*!*********************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/decoders/index.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var decoders = exports;\n\ndecoders.der = __webpack_require__(/*! ./der */ \"./node_modules/asn1.js/lib/asn1/decoders/der.js\");\ndecoders.pem = __webpack_require__(/*! ./pem */ \"./node_modules/asn1.js/lib/asn1/decoders/pem.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/decoders/index.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/decoders/pem.js": +/*!*******************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/decoders/pem.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer);\n\nvar DERDecoder = __webpack_require__(/*! ./der */ \"./node_modules/asn1.js/lib/asn1/decoders/der.js\");\n\nfunction PEMDecoder(entity) {\n DERDecoder.call(this, entity);\n this.enc = 'pem';\n};\ninherits(PEMDecoder, DERDecoder);\nmodule.exports = PEMDecoder;\n\nPEMDecoder.prototype.decode = function decode(data, options) {\n var lines = data.toString().split(/[\\r\\n]+/g);\n\n var label = options.label.toUpperCase();\n\n var re = /^-----(BEGIN|END) ([^-]+)-----$/;\n var start = -1;\n var end = -1;\n for (var i = 0; i < lines.length; i++) {\n var match = lines[i].match(re);\n if (match === null)\n continue;\n\n if (match[2] !== label)\n continue;\n\n if (start === -1) {\n if (match[1] !== 'BEGIN')\n break;\n start = i;\n } else {\n if (match[1] !== 'END')\n break;\n end = i;\n break;\n }\n }\n if (start === -1 || end === -1)\n throw new Error('PEM section not found for: ' + label);\n\n var base64 = lines.slice(start + 1, end).join('');\n // Remove excessive symbols\n base64.replace(/[^a-z0-9\\+\\/=]+/gi, '');\n\n var input = new Buffer(base64, 'base64');\n return DERDecoder.prototype.decode.call(this, input, options);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/decoders/pem.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/encoders/der.js": +/*!*******************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/encoders/der.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer);\n\nvar asn1 = __webpack_require__(/*! ../../asn1 */ \"./node_modules/asn1.js/lib/asn1.js\");\nvar base = asn1.base;\n\n// Import DER constants\nvar der = asn1.constants.der;\n\nfunction DEREncoder(entity) {\n this.enc = 'der';\n this.name = entity.name;\n this.entity = entity;\n\n // Construct base tree\n this.tree = new DERNode();\n this.tree._init(entity.body);\n};\nmodule.exports = DEREncoder;\n\nDEREncoder.prototype.encode = function encode(data, reporter) {\n return this.tree._encode(data, reporter).join();\n};\n\n// Tree methods\n\nfunction DERNode(parent) {\n base.Node.call(this, 'der', parent);\n}\ninherits(DERNode, base.Node);\n\nDERNode.prototype._encodeComposite = function encodeComposite(tag,\n primitive,\n cls,\n content) {\n var encodedTag = encodeTag(tag, primitive, cls, this.reporter);\n\n // Short form\n if (content.length < 0x80) {\n var header = new Buffer(2);\n header[0] = encodedTag;\n header[1] = content.length;\n return this._createEncoderBuffer([ header, content ]);\n }\n\n // Long form\n // Count octets required to store length\n var lenOctets = 1;\n for (var i = content.length; i >= 0x100; i >>= 8)\n lenOctets++;\n\n var header = new Buffer(1 + 1 + lenOctets);\n header[0] = encodedTag;\n header[1] = 0x80 | lenOctets;\n\n for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)\n header[i] = j & 0xff;\n\n return this._createEncoderBuffer([ header, content ]);\n};\n\nDERNode.prototype._encodeStr = function encodeStr(str, tag) {\n if (tag === 'bitstr') {\n return this._createEncoderBuffer([ str.unused | 0, str.data ]);\n } else if (tag === 'bmpstr') {\n var buf = new Buffer(str.length * 2);\n for (var i = 0; i < str.length; i++) {\n buf.writeUInt16BE(str.charCodeAt(i), i * 2);\n }\n return this._createEncoderBuffer(buf);\n } else if (tag === 'numstr') {\n if (!this._isNumstr(str)) {\n return this.reporter.error('Encoding of string type: numstr supports ' +\n 'only digits and space');\n }\n return this._createEncoderBuffer(str);\n } else if (tag === 'printstr') {\n if (!this._isPrintstr(str)) {\n return this.reporter.error('Encoding of string type: printstr supports ' +\n 'only latin upper and lower case letters, ' +\n 'digits, space, apostrophe, left and rigth ' +\n 'parenthesis, plus sign, comma, hyphen, ' +\n 'dot, slash, colon, equal sign, ' +\n 'question mark');\n }\n return this._createEncoderBuffer(str);\n } else if (/str$/.test(tag)) {\n return this._createEncoderBuffer(str);\n } else if (tag === 'objDesc') {\n return this._createEncoderBuffer(str);\n } else {\n return this.reporter.error('Encoding of string type: ' + tag +\n ' unsupported');\n }\n};\n\nDERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {\n if (typeof id === 'string') {\n if (!values)\n return this.reporter.error('string objid given, but no values map found');\n if (!values.hasOwnProperty(id))\n return this.reporter.error('objid not found in values map');\n id = values[id].split(/[\\s\\.]+/g);\n for (var i = 0; i < id.length; i++)\n id[i] |= 0;\n } else if (Array.isArray(id)) {\n id = id.slice();\n for (var i = 0; i < id.length; i++)\n id[i] |= 0;\n }\n\n if (!Array.isArray(id)) {\n return this.reporter.error('objid() should be either array or string, ' +\n 'got: ' + JSON.stringify(id));\n }\n\n if (!relative) {\n if (id[1] >= 40)\n return this.reporter.error('Second objid identifier OOB');\n id.splice(0, 2, id[0] * 40 + id[1]);\n }\n\n // Count number of octets\n var size = 0;\n for (var i = 0; i < id.length; i++) {\n var ident = id[i];\n for (size++; ident >= 0x80; ident >>= 7)\n size++;\n }\n\n var objid = new Buffer(size);\n var offset = objid.length - 1;\n for (var i = id.length - 1; i >= 0; i--) {\n var ident = id[i];\n objid[offset--] = ident & 0x7f;\n while ((ident >>= 7) > 0)\n objid[offset--] = 0x80 | (ident & 0x7f);\n }\n\n return this._createEncoderBuffer(objid);\n};\n\nfunction two(num) {\n if (num < 10)\n return '0' + num;\n else\n return num;\n}\n\nDERNode.prototype._encodeTime = function encodeTime(time, tag) {\n var str;\n var date = new Date(time);\n\n if (tag === 'gentime') {\n str = [\n two(date.getFullYear()),\n two(date.getUTCMonth() + 1),\n two(date.getUTCDate()),\n two(date.getUTCHours()),\n two(date.getUTCMinutes()),\n two(date.getUTCSeconds()),\n 'Z'\n ].join('');\n } else if (tag === 'utctime') {\n str = [\n two(date.getFullYear() % 100),\n two(date.getUTCMonth() + 1),\n two(date.getUTCDate()),\n two(date.getUTCHours()),\n two(date.getUTCMinutes()),\n two(date.getUTCSeconds()),\n 'Z'\n ].join('');\n } else {\n this.reporter.error('Encoding ' + tag + ' time is not supported yet');\n }\n\n return this._encodeStr(str, 'octstr');\n};\n\nDERNode.prototype._encodeNull = function encodeNull() {\n return this._createEncoderBuffer('');\n};\n\nDERNode.prototype._encodeInt = function encodeInt(num, values) {\n if (typeof num === 'string') {\n if (!values)\n return this.reporter.error('String int or enum given, but no values map');\n if (!values.hasOwnProperty(num)) {\n return this.reporter.error('Values map doesn\\'t contain: ' +\n JSON.stringify(num));\n }\n num = values[num];\n }\n\n // Bignum, assume big endian\n if (typeof num !== 'number' && !Buffer.isBuffer(num)) {\n var numArray = num.toArray();\n if (!num.sign && numArray[0] & 0x80) {\n numArray.unshift(0);\n }\n num = new Buffer(numArray);\n }\n\n if (Buffer.isBuffer(num)) {\n var size = num.length;\n if (num.length === 0)\n size++;\n\n var out = new Buffer(size);\n num.copy(out);\n if (num.length === 0)\n out[0] = 0\n return this._createEncoderBuffer(out);\n }\n\n if (num < 0x80)\n return this._createEncoderBuffer(num);\n\n if (num < 0x100)\n return this._createEncoderBuffer([0, num]);\n\n var size = 1;\n for (var i = num; i >= 0x100; i >>= 8)\n size++;\n\n var out = new Array(size);\n for (var i = out.length - 1; i >= 0; i--) {\n out[i] = num & 0xff;\n num >>= 8;\n }\n if(out[0] & 0x80) {\n out.unshift(0);\n }\n\n return this._createEncoderBuffer(new Buffer(out));\n};\n\nDERNode.prototype._encodeBool = function encodeBool(value) {\n return this._createEncoderBuffer(value ? 0xff : 0);\n};\n\nDERNode.prototype._use = function use(entity, obj) {\n if (typeof entity === 'function')\n entity = entity(obj);\n return entity._getEncoder('der').tree;\n};\n\nDERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {\n var state = this._baseState;\n var i;\n if (state['default'] === null)\n return false;\n\n var data = dataBuffer.join();\n if (state.defaultBuffer === undefined)\n state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();\n\n if (data.length !== state.defaultBuffer.length)\n return false;\n\n for (i=0; i < data.length; i++)\n if (data[i] !== state.defaultBuffer[i])\n return false;\n\n return true;\n};\n\n// Utility methods\n\nfunction encodeTag(tag, primitive, cls, reporter) {\n var res;\n\n if (tag === 'seqof')\n tag = 'seq';\n else if (tag === 'setof')\n tag = 'set';\n\n if (der.tagByName.hasOwnProperty(tag))\n res = der.tagByName[tag];\n else if (typeof tag === 'number' && (tag | 0) === tag)\n res = tag;\n else\n return reporter.error('Unknown tag: ' + tag);\n\n if (res >= 0x1f)\n return reporter.error('Multi-octet tag encoding unsupported');\n\n if (!primitive)\n res |= 0x20;\n\n res |= (der.tagClassByName[cls || 'universal'] << 6);\n\n return res;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/encoders/der.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/encoders/index.js": +/*!*********************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/encoders/index.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var encoders = exports;\n\nencoders.der = __webpack_require__(/*! ./der */ \"./node_modules/asn1.js/lib/asn1/encoders/der.js\");\nencoders.pem = __webpack_require__(/*! ./pem */ \"./node_modules/asn1.js/lib/asn1/encoders/pem.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/encoders/index.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/lib/asn1/encoders/pem.js": +/*!*******************************************************!*\ + !*** ./node_modules/asn1.js/lib/asn1/encoders/pem.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar DEREncoder = __webpack_require__(/*! ./der */ \"./node_modules/asn1.js/lib/asn1/encoders/der.js\");\n\nfunction PEMEncoder(entity) {\n DEREncoder.call(this, entity);\n this.enc = 'pem';\n};\ninherits(PEMEncoder, DEREncoder);\nmodule.exports = PEMEncoder;\n\nPEMEncoder.prototype.encode = function encode(data, options) {\n var buf = DEREncoder.prototype.encode.call(this, data);\n\n var p = buf.toString('base64');\n var out = [ '-----BEGIN ' + options.label + '-----' ];\n for (var i = 0; i < p.length; i += 64)\n out.push(p.slice(i, i + 64));\n out.push('-----END ' + options.label + '-----');\n return out.join('\\n');\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/lib/asn1/encoders/pem.js?"); + +/***/ }), + +/***/ "./node_modules/asn1.js/node_modules/bn.js/lib/bn.js": +/*!***********************************************************!*\ + !*** ./node_modules/asn1.js/node_modules/bn.js/lib/bn.js ***! + \***********************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?d546\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/asn1.js/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + /***/ "./node_modules/asn1js/build/index.es.js": /*!***********************************************!*\ !*** ./node_modules/asn1js/build/index.es.js ***! @@ -987,6 +1192,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/base64-js/index.js": +/*!*****************************************!*\ + !*** ./node_modules/base64-js/index.js ***! + \*****************************************/ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +eval("\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/base64-js/index.js?"); + +/***/ }), + /***/ "./node_modules/bech32/index.js": /*!**************************************!*\ !*** ./node_modules/bech32/index.js ***! @@ -1008,13 +1224,696 @@ eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(functio /***/ }), +/***/ "./node_modules/brorand/index.js": +/*!***************************************!*\ + !*** ./node_modules/brorand/index.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = __webpack_require__(/*! crypto */ \"?3fc0\");\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/brorand/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/aes.js": +/*!********************************************!*\ + !*** ./node_modules/browserify-aes/aes.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("// based on the aes implimentation in triple sec\n// https://github.com/keybase/triplesec\n// which is in turn based on the one from crypto-js\n// https://code.google.com/p/crypto-js/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nfunction asUInt32Array (buf) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n\n var len = (buf.length / 4) | 0\n var out = new Array(len)\n\n for (var i = 0; i < len; i++) {\n out[i] = buf.readUInt32BE(i * 4)\n }\n\n return out\n}\n\nfunction scrubVec (v) {\n for (var i = 0; i < v.length; v++) {\n v[i] = 0\n }\n}\n\nfunction cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {\n var SUB_MIX0 = SUB_MIX[0]\n var SUB_MIX1 = SUB_MIX[1]\n var SUB_MIX2 = SUB_MIX[2]\n var SUB_MIX3 = SUB_MIX[3]\n\n var s0 = M[0] ^ keySchedule[0]\n var s1 = M[1] ^ keySchedule[1]\n var s2 = M[2] ^ keySchedule[2]\n var s3 = M[3] ^ keySchedule[3]\n var t0, t1, t2, t3\n var ksRow = 4\n\n for (var round = 1; round < nRounds; round++) {\n t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]\n t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]\n t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]\n t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]\n s0 = t0\n s1 = t1\n s2 = t2\n s3 = t3\n }\n\n t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]\n t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]\n t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]\n t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]\n t0 = t0 >>> 0\n t1 = t1 >>> 0\n t2 = t2 >>> 0\n t3 = t3 >>> 0\n\n return [t0, t1, t2, t3]\n}\n\n// AES constants\nvar RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]\nvar G = (function () {\n // Compute double table\n var d = new Array(256)\n for (var j = 0; j < 256; j++) {\n if (j < 128) {\n d[j] = j << 1\n } else {\n d[j] = (j << 1) ^ 0x11b\n }\n }\n\n var SBOX = []\n var INV_SBOX = []\n var SUB_MIX = [[], [], [], []]\n var INV_SUB_MIX = [[], [], [], []]\n\n // Walk GF(2^8)\n var x = 0\n var xi = 0\n for (var i = 0; i < 256; ++i) {\n // Compute sbox\n var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63\n SBOX[x] = sx\n INV_SBOX[sx] = x\n\n // Compute multiplication\n var x2 = d[x]\n var x4 = d[x2]\n var x8 = d[x4]\n\n // Compute sub bytes, mix columns tables\n var t = (d[sx] * 0x101) ^ (sx * 0x1010100)\n SUB_MIX[0][x] = (t << 24) | (t >>> 8)\n SUB_MIX[1][x] = (t << 16) | (t >>> 16)\n SUB_MIX[2][x] = (t << 8) | (t >>> 24)\n SUB_MIX[3][x] = t\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)\n INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)\n INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)\n INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)\n INV_SUB_MIX[3][sx] = t\n\n if (x === 0) {\n x = xi = 1\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]]\n xi ^= d[d[xi]]\n }\n }\n\n return {\n SBOX: SBOX,\n INV_SBOX: INV_SBOX,\n SUB_MIX: SUB_MIX,\n INV_SUB_MIX: INV_SUB_MIX\n }\n})()\n\nfunction AES (key) {\n this._key = asUInt32Array(key)\n this._reset()\n}\n\nAES.blockSize = 4 * 4\nAES.keySize = 256 / 8\nAES.prototype.blockSize = AES.blockSize\nAES.prototype.keySize = AES.keySize\nAES.prototype._reset = function () {\n var keyWords = this._key\n var keySize = keyWords.length\n var nRounds = keySize + 6\n var ksRows = (nRounds + 1) * 4\n\n var keySchedule = []\n for (var k = 0; k < keySize; k++) {\n keySchedule[k] = keyWords[k]\n }\n\n for (k = keySize; k < ksRows; k++) {\n var t = keySchedule[k - 1]\n\n if (k % keySize === 0) {\n t = (t << 8) | (t >>> 24)\n t =\n (G.SBOX[t >>> 24] << 24) |\n (G.SBOX[(t >>> 16) & 0xff] << 16) |\n (G.SBOX[(t >>> 8) & 0xff] << 8) |\n (G.SBOX[t & 0xff])\n\n t ^= RCON[(k / keySize) | 0] << 24\n } else if (keySize > 6 && k % keySize === 4) {\n t =\n (G.SBOX[t >>> 24] << 24) |\n (G.SBOX[(t >>> 16) & 0xff] << 16) |\n (G.SBOX[(t >>> 8) & 0xff] << 8) |\n (G.SBOX[t & 0xff])\n }\n\n keySchedule[k] = keySchedule[k - keySize] ^ t\n }\n\n var invKeySchedule = []\n for (var ik = 0; ik < ksRows; ik++) {\n var ksR = ksRows - ik\n var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]\n\n if (ik < 4 || ksR <= 4) {\n invKeySchedule[ik] = tt\n } else {\n invKeySchedule[ik] =\n G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^\n G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^\n G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^\n G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]\n }\n }\n\n this._nRounds = nRounds\n this._keySchedule = keySchedule\n this._invKeySchedule = invKeySchedule\n}\n\nAES.prototype.encryptBlockRaw = function (M) {\n M = asUInt32Array(M)\n return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)\n}\n\nAES.prototype.encryptBlock = function (M) {\n var out = this.encryptBlockRaw(M)\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0], 0)\n buf.writeUInt32BE(out[1], 4)\n buf.writeUInt32BE(out[2], 8)\n buf.writeUInt32BE(out[3], 12)\n return buf\n}\n\nAES.prototype.decryptBlock = function (M) {\n M = asUInt32Array(M)\n\n // swap\n var m1 = M[1]\n M[1] = M[3]\n M[3] = m1\n\n var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0], 0)\n buf.writeUInt32BE(out[3], 4)\n buf.writeUInt32BE(out[2], 8)\n buf.writeUInt32BE(out[1], 12)\n return buf\n}\n\nAES.prototype.scrub = function () {\n scrubVec(this._keySchedule)\n scrubVec(this._invKeySchedule)\n scrubVec(this._key)\n}\n\nmodule.exports.AES = AES\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/aes.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/authCipher.js": +/*!***************************************************!*\ + !*** ./node_modules/browserify-aes/authCipher.js ***! + \***************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var aes = __webpack_require__(/*! ./aes */ \"./node_modules/browserify-aes/aes.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar Transform = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar GHASH = __webpack_require__(/*! ./ghash */ \"./node_modules/browserify-aes/ghash.js\")\nvar xor = __webpack_require__(/*! buffer-xor */ \"./node_modules/buffer-xor/index.js\")\nvar incr32 = __webpack_require__(/*! ./incr32 */ \"./node_modules/browserify-aes/incr32.js\")\n\nfunction xorTest (a, b) {\n var out = 0\n if (a.length !== b.length) out++\n\n var len = Math.min(a.length, b.length)\n for (var i = 0; i < len; ++i) {\n out += (a[i] ^ b[i])\n }\n\n return out\n}\n\nfunction calcIv (self, iv, ck) {\n if (iv.length === 12) {\n self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])\n return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])\n }\n var ghash = new GHASH(ck)\n var len = iv.length\n var toPad = len % 16\n ghash.update(iv)\n if (toPad) {\n toPad = 16 - toPad\n ghash.update(Buffer.alloc(toPad, 0))\n }\n ghash.update(Buffer.alloc(8, 0))\n var ivBits = len * 8\n var tail = Buffer.alloc(8)\n tail.writeUIntBE(ivBits, 0, 8)\n ghash.update(tail)\n self._finID = ghash.state\n var out = Buffer.from(self._finID)\n incr32(out)\n return out\n}\nfunction StreamCipher (mode, key, iv, decrypt) {\n Transform.call(this)\n\n var h = Buffer.alloc(4, 0)\n\n this._cipher = new aes.AES(key)\n var ck = this._cipher.encryptBlock(h)\n this._ghash = new GHASH(ck)\n iv = calcIv(this, iv, ck)\n\n this._prev = Buffer.from(iv)\n this._cache = Buffer.allocUnsafe(0)\n this._secCache = Buffer.allocUnsafe(0)\n this._decrypt = decrypt\n this._alen = 0\n this._len = 0\n this._mode = mode\n\n this._authTag = null\n this._called = false\n}\n\ninherits(StreamCipher, Transform)\n\nStreamCipher.prototype._update = function (chunk) {\n if (!this._called && this._alen) {\n var rump = 16 - (this._alen % 16)\n if (rump < 16) {\n rump = Buffer.alloc(rump, 0)\n this._ghash.update(rump)\n }\n }\n\n this._called = true\n var out = this._mode.encrypt(this, chunk)\n if (this._decrypt) {\n this._ghash.update(chunk)\n } else {\n this._ghash.update(out)\n }\n this._len += chunk.length\n return out\n}\n\nStreamCipher.prototype._final = function () {\n if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')\n\n var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))\n if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')\n\n this._authTag = tag\n this._cipher.scrub()\n}\n\nStreamCipher.prototype.getAuthTag = function getAuthTag () {\n if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')\n\n return this._authTag\n}\n\nStreamCipher.prototype.setAuthTag = function setAuthTag (tag) {\n if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')\n\n this._authTag = tag\n}\n\nStreamCipher.prototype.setAAD = function setAAD (buf) {\n if (this._called) throw new Error('Attempting to set AAD in unsupported state')\n\n this._ghash.update(buf)\n this._alen += buf.length\n}\n\nmodule.exports = StreamCipher\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/authCipher.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/browser.js": +/*!************************************************!*\ + !*** ./node_modules/browserify-aes/browser.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var ciphers = __webpack_require__(/*! ./encrypter */ \"./node_modules/browserify-aes/encrypter.js\")\nvar deciphers = __webpack_require__(/*! ./decrypter */ \"./node_modules/browserify-aes/decrypter.js\")\nvar modes = __webpack_require__(/*! ./modes/list.json */ \"./node_modules/browserify-aes/modes/list.json\")\n\nfunction getCiphers () {\n return Object.keys(modes)\n}\n\nexports.createCipher = exports.Cipher = ciphers.createCipher\nexports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv\nexports.createDecipher = exports.Decipher = deciphers.createDecipher\nexports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv\nexports.listCiphers = exports.getCiphers = getCiphers\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/browser.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/decrypter.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/decrypter.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var AuthCipher = __webpack_require__(/*! ./authCipher */ \"./node_modules/browserify-aes/authCipher.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar MODES = __webpack_require__(/*! ./modes */ \"./node_modules/browserify-aes/modes/index.js\")\nvar StreamCipher = __webpack_require__(/*! ./streamCipher */ \"./node_modules/browserify-aes/streamCipher.js\")\nvar Transform = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar aes = __webpack_require__(/*! ./aes */ \"./node_modules/browserify-aes/aes.js\")\nvar ebtk = __webpack_require__(/*! evp_bytestokey */ \"./node_modules/evp_bytestokey/index.js\")\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\n\nfunction Decipher (mode, key, iv) {\n Transform.call(this)\n\n this._cache = new Splitter()\n this._last = void 0\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._mode = mode\n this._autopadding = true\n}\n\ninherits(Decipher, Transform)\n\nDecipher.prototype._update = function (data) {\n this._cache.add(data)\n var chunk\n var thing\n var out = []\n while ((chunk = this._cache.get(this._autopadding))) {\n thing = this._mode.decrypt(this, chunk)\n out.push(thing)\n }\n return Buffer.concat(out)\n}\n\nDecipher.prototype._final = function () {\n var chunk = this._cache.flush()\n if (this._autopadding) {\n return unpad(this._mode.decrypt(this, chunk))\n } else if (chunk) {\n throw new Error('data not multiple of block length')\n }\n}\n\nDecipher.prototype.setAutoPadding = function (setTo) {\n this._autopadding = !!setTo\n return this\n}\n\nfunction Splitter () {\n this.cache = Buffer.allocUnsafe(0)\n}\n\nSplitter.prototype.add = function (data) {\n this.cache = Buffer.concat([this.cache, data])\n}\n\nSplitter.prototype.get = function (autoPadding) {\n var out\n if (autoPadding) {\n if (this.cache.length > 16) {\n out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n } else {\n if (this.cache.length >= 16) {\n out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n }\n\n return null\n}\n\nSplitter.prototype.flush = function () {\n if (this.cache.length) return this.cache\n}\n\nfunction unpad (last) {\n var padded = last[15]\n if (padded < 1 || padded > 16) {\n throw new Error('unable to decrypt data')\n }\n var i = -1\n while (++i < padded) {\n if (last[(i + (16 - padded))] !== padded) {\n throw new Error('unable to decrypt data')\n }\n }\n if (padded === 16) return\n\n return last.slice(0, 16 - padded)\n}\n\nfunction createDecipheriv (suite, password, iv) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n if (typeof iv === 'string') iv = Buffer.from(iv)\n if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)\n\n if (typeof password === 'string') password = Buffer.from(password)\n if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)\n\n if (config.type === 'stream') {\n return new StreamCipher(config.module, password, iv, true)\n } else if (config.type === 'auth') {\n return new AuthCipher(config.module, password, iv, true)\n }\n\n return new Decipher(config.module, password, iv)\n}\n\nfunction createDecipher (suite, password) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n var keys = ebtk(password, false, config.key, config.iv)\n return createDecipheriv(suite, keys.key, keys.iv)\n}\n\nexports.createDecipher = createDecipher\nexports.createDecipheriv = createDecipheriv\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/decrypter.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/encrypter.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/encrypter.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var MODES = __webpack_require__(/*! ./modes */ \"./node_modules/browserify-aes/modes/index.js\")\nvar AuthCipher = __webpack_require__(/*! ./authCipher */ \"./node_modules/browserify-aes/authCipher.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar StreamCipher = __webpack_require__(/*! ./streamCipher */ \"./node_modules/browserify-aes/streamCipher.js\")\nvar Transform = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar aes = __webpack_require__(/*! ./aes */ \"./node_modules/browserify-aes/aes.js\")\nvar ebtk = __webpack_require__(/*! evp_bytestokey */ \"./node_modules/evp_bytestokey/index.js\")\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\n\nfunction Cipher (mode, key, iv) {\n Transform.call(this)\n\n this._cache = new Splitter()\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._mode = mode\n this._autopadding = true\n}\n\ninherits(Cipher, Transform)\n\nCipher.prototype._update = function (data) {\n this._cache.add(data)\n var chunk\n var thing\n var out = []\n\n while ((chunk = this._cache.get())) {\n thing = this._mode.encrypt(this, chunk)\n out.push(thing)\n }\n\n return Buffer.concat(out)\n}\n\nvar PADDING = Buffer.alloc(16, 0x10)\n\nCipher.prototype._final = function () {\n var chunk = this._cache.flush()\n if (this._autopadding) {\n chunk = this._mode.encrypt(this, chunk)\n this._cipher.scrub()\n return chunk\n }\n\n if (!chunk.equals(PADDING)) {\n this._cipher.scrub()\n throw new Error('data not multiple of block length')\n }\n}\n\nCipher.prototype.setAutoPadding = function (setTo) {\n this._autopadding = !!setTo\n return this\n}\n\nfunction Splitter () {\n this.cache = Buffer.allocUnsafe(0)\n}\n\nSplitter.prototype.add = function (data) {\n this.cache = Buffer.concat([this.cache, data])\n}\n\nSplitter.prototype.get = function () {\n if (this.cache.length > 15) {\n var out = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n return out\n }\n return null\n}\n\nSplitter.prototype.flush = function () {\n var len = 16 - this.cache.length\n var padBuff = Buffer.allocUnsafe(len)\n\n var i = -1\n while (++i < len) {\n padBuff.writeUInt8(len, i)\n }\n\n return Buffer.concat([this.cache, padBuff])\n}\n\nfunction createCipheriv (suite, password, iv) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n if (typeof password === 'string') password = Buffer.from(password)\n if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)\n\n if (typeof iv === 'string') iv = Buffer.from(iv)\n if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)\n\n if (config.type === 'stream') {\n return new StreamCipher(config.module, password, iv)\n } else if (config.type === 'auth') {\n return new AuthCipher(config.module, password, iv)\n }\n\n return new Cipher(config.module, password, iv)\n}\n\nfunction createCipher (suite, password) {\n var config = MODES[suite.toLowerCase()]\n if (!config) throw new TypeError('invalid suite type')\n\n var keys = ebtk(password, false, config.key, config.iv)\n return createCipheriv(suite, keys.key, keys.iv)\n}\n\nexports.createCipheriv = createCipheriv\nexports.createCipher = createCipher\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/encrypter.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/ghash.js": +/*!**********************************************!*\ + !*** ./node_modules/browserify-aes/ghash.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar ZEROES = Buffer.alloc(16, 0)\n\nfunction toArray (buf) {\n return [\n buf.readUInt32BE(0),\n buf.readUInt32BE(4),\n buf.readUInt32BE(8),\n buf.readUInt32BE(12)\n ]\n}\n\nfunction fromArray (out) {\n var buf = Buffer.allocUnsafe(16)\n buf.writeUInt32BE(out[0] >>> 0, 0)\n buf.writeUInt32BE(out[1] >>> 0, 4)\n buf.writeUInt32BE(out[2] >>> 0, 8)\n buf.writeUInt32BE(out[3] >>> 0, 12)\n return buf\n}\n\nfunction GHASH (key) {\n this.h = key\n this.state = Buffer.alloc(16, 0)\n this.cache = Buffer.allocUnsafe(0)\n}\n\n// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html\n// by Juho Vähä-Herttua\nGHASH.prototype.ghash = function (block) {\n var i = -1\n while (++i < block.length) {\n this.state[i] ^= block[i]\n }\n this._multiply()\n}\n\nGHASH.prototype._multiply = function () {\n var Vi = toArray(this.h)\n var Zi = [0, 0, 0, 0]\n var j, xi, lsbVi\n var i = -1\n while (++i < 128) {\n xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0\n if (xi) {\n // Z_i+1 = Z_i ^ V_i\n Zi[0] ^= Vi[0]\n Zi[1] ^= Vi[1]\n Zi[2] ^= Vi[2]\n Zi[3] ^= Vi[3]\n }\n\n // Store the value of LSB(V_i)\n lsbVi = (Vi[3] & 1) !== 0\n\n // V_i+1 = V_i >> 1\n for (j = 3; j > 0; j--) {\n Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)\n }\n Vi[0] = Vi[0] >>> 1\n\n // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R\n if (lsbVi) {\n Vi[0] = Vi[0] ^ (0xe1 << 24)\n }\n }\n this.state = fromArray(Zi)\n}\n\nGHASH.prototype.update = function (buf) {\n this.cache = Buffer.concat([this.cache, buf])\n var chunk\n while (this.cache.length >= 16) {\n chunk = this.cache.slice(0, 16)\n this.cache = this.cache.slice(16)\n this.ghash(chunk)\n }\n}\n\nGHASH.prototype.final = function (abl, bl) {\n if (this.cache.length) {\n this.ghash(Buffer.concat([this.cache, ZEROES], 16))\n }\n\n this.ghash(fromArray([0, abl, 0, bl]))\n return this.state\n}\n\nmodule.exports = GHASH\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/ghash.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/incr32.js": +/*!***********************************************!*\ + !*** ./node_modules/browserify-aes/incr32.js ***! + \***********************************************/ +/***/ ((module) => { + +eval("function incr32 (iv) {\n var len = iv.length\n var item\n while (len--) {\n item = iv.readUInt8(len)\n if (item === 255) {\n iv.writeUInt8(0, len)\n } else {\n item++\n iv.writeUInt8(item, len)\n break\n }\n }\n}\nmodule.exports = incr32\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/incr32.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/cbc.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/modes/cbc.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var xor = __webpack_require__(/*! buffer-xor */ \"./node_modules/buffer-xor/index.js\")\n\nexports.encrypt = function (self, block) {\n var data = xor(block, self._prev)\n\n self._prev = self._cipher.encryptBlock(data)\n return self._prev\n}\n\nexports.decrypt = function (self, block) {\n var pad = self._prev\n\n self._prev = block\n var out = self._cipher.decryptBlock(block)\n\n return xor(out, pad)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/cbc.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/cfb.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/modes/cfb.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar xor = __webpack_require__(/*! buffer-xor */ \"./node_modules/buffer-xor/index.js\")\n\nfunction encryptStart (self, data, decrypt) {\n var len = data.length\n var out = xor(data, self._cache)\n self._cache = self._cache.slice(len)\n self._prev = Buffer.concat([self._prev, decrypt ? data : out])\n return out\n}\n\nexports.encrypt = function (self, data, decrypt) {\n var out = Buffer.allocUnsafe(0)\n var len\n\n while (data.length) {\n if (self._cache.length === 0) {\n self._cache = self._cipher.encryptBlock(self._prev)\n self._prev = Buffer.allocUnsafe(0)\n }\n\n if (self._cache.length <= data.length) {\n len = self._cache.length\n out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])\n data = data.slice(len)\n } else {\n out = Buffer.concat([out, encryptStart(self, data, decrypt)])\n break\n }\n }\n\n return out\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/cfb.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/cfb1.js": +/*!***************************************************!*\ + !*** ./node_modules/browserify-aes/modes/cfb1.js ***! + \***************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nfunction encryptByte (self, byteParam, decrypt) {\n var pad\n var i = -1\n var len = 8\n var out = 0\n var bit, value\n while (++i < len) {\n pad = self._cipher.encryptBlock(self._prev)\n bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0\n value = pad[0] ^ bit\n out += ((value & 0x80) >> (i % 8))\n self._prev = shiftIn(self._prev, decrypt ? bit : value)\n }\n return out\n}\n\nfunction shiftIn (buffer, value) {\n var len = buffer.length\n var i = -1\n var out = Buffer.allocUnsafe(buffer.length)\n buffer = Buffer.concat([buffer, Buffer.from([value])])\n\n while (++i < len) {\n out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)\n }\n\n return out\n}\n\nexports.encrypt = function (self, chunk, decrypt) {\n var len = chunk.length\n var out = Buffer.allocUnsafe(len)\n var i = -1\n\n while (++i < len) {\n out[i] = encryptByte(self, chunk[i], decrypt)\n }\n\n return out\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/cfb1.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/cfb8.js": +/*!***************************************************!*\ + !*** ./node_modules/browserify-aes/modes/cfb8.js ***! + \***************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nfunction encryptByte (self, byteParam, decrypt) {\n var pad = self._cipher.encryptBlock(self._prev)\n var out = pad[0] ^ byteParam\n\n self._prev = Buffer.concat([\n self._prev.slice(1),\n Buffer.from([decrypt ? byteParam : out])\n ])\n\n return out\n}\n\nexports.encrypt = function (self, chunk, decrypt) {\n var len = chunk.length\n var out = Buffer.allocUnsafe(len)\n var i = -1\n\n while (++i < len) {\n out[i] = encryptByte(self, chunk[i], decrypt)\n }\n\n return out\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/cfb8.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/ctr.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/modes/ctr.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var xor = __webpack_require__(/*! buffer-xor */ \"./node_modules/buffer-xor/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar incr32 = __webpack_require__(/*! ../incr32 */ \"./node_modules/browserify-aes/incr32.js\")\n\nfunction getBlock (self) {\n var out = self._cipher.encryptBlockRaw(self._prev)\n incr32(self._prev)\n return out\n}\n\nvar blockSize = 16\nexports.encrypt = function (self, chunk) {\n var chunkNum = Math.ceil(chunk.length / blockSize)\n var start = self._cache.length\n self._cache = Buffer.concat([\n self._cache,\n Buffer.allocUnsafe(chunkNum * blockSize)\n ])\n for (var i = 0; i < chunkNum; i++) {\n var out = getBlock(self)\n var offset = start + i * blockSize\n self._cache.writeUInt32BE(out[0], offset + 0)\n self._cache.writeUInt32BE(out[1], offset + 4)\n self._cache.writeUInt32BE(out[2], offset + 8)\n self._cache.writeUInt32BE(out[3], offset + 12)\n }\n var pad = self._cache.slice(0, chunk.length)\n self._cache = self._cache.slice(chunk.length)\n return xor(chunk, pad)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/ctr.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/ecb.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/modes/ecb.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("exports.encrypt = function (self, block) {\n return self._cipher.encryptBlock(block)\n}\n\nexports.decrypt = function (self, block) {\n return self._cipher.decryptBlock(block)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/ecb.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/index.js": +/*!****************************************************!*\ + !*** ./node_modules/browserify-aes/modes/index.js ***! + \****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var modeModules = {\n ECB: __webpack_require__(/*! ./ecb */ \"./node_modules/browserify-aes/modes/ecb.js\"),\n CBC: __webpack_require__(/*! ./cbc */ \"./node_modules/browserify-aes/modes/cbc.js\"),\n CFB: __webpack_require__(/*! ./cfb */ \"./node_modules/browserify-aes/modes/cfb.js\"),\n CFB8: __webpack_require__(/*! ./cfb8 */ \"./node_modules/browserify-aes/modes/cfb8.js\"),\n CFB1: __webpack_require__(/*! ./cfb1 */ \"./node_modules/browserify-aes/modes/cfb1.js\"),\n OFB: __webpack_require__(/*! ./ofb */ \"./node_modules/browserify-aes/modes/ofb.js\"),\n CTR: __webpack_require__(/*! ./ctr */ \"./node_modules/browserify-aes/modes/ctr.js\"),\n GCM: __webpack_require__(/*! ./ctr */ \"./node_modules/browserify-aes/modes/ctr.js\")\n}\n\nvar modes = __webpack_require__(/*! ./list.json */ \"./node_modules/browserify-aes/modes/list.json\")\n\nfor (var key in modes) {\n modes[key].module = modeModules[modes[key].mode]\n}\n\nmodule.exports = modes\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/ofb.js": +/*!**************************************************!*\ + !*** ./node_modules/browserify-aes/modes/ofb.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\nvar xor = __webpack_require__(/*! buffer-xor */ \"./node_modules/buffer-xor/index.js\")\n\nfunction getBlock (self) {\n self._prev = self._cipher.encryptBlock(self._prev)\n return self._prev\n}\n\nexports.encrypt = function (self, chunk) {\n while (self._cache.length < chunk.length) {\n self._cache = Buffer.concat([self._cache, getBlock(self)])\n }\n\n var pad = self._cache.slice(0, chunk.length)\n self._cache = self._cache.slice(chunk.length)\n return xor(chunk, pad)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/ofb.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-aes/streamCipher.js": +/*!*****************************************************!*\ + !*** ./node_modules/browserify-aes/streamCipher.js ***! + \*****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var aes = __webpack_require__(/*! ./aes */ \"./node_modules/browserify-aes/aes.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar Transform = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\n\nfunction StreamCipher (mode, key, iv, decrypt) {\n Transform.call(this)\n\n this._cipher = new aes.AES(key)\n this._prev = Buffer.from(iv)\n this._cache = Buffer.allocUnsafe(0)\n this._secCache = Buffer.allocUnsafe(0)\n this._decrypt = decrypt\n this._mode = mode\n}\n\ninherits(StreamCipher, Transform)\n\nStreamCipher.prototype._update = function (chunk) {\n return this._mode.encrypt(this, chunk, this._decrypt)\n}\n\nStreamCipher.prototype._final = function () {\n this._cipher.scrub()\n}\n\nmodule.exports = StreamCipher\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/streamCipher.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-cipher/browser.js": +/*!***************************************************!*\ + !*** ./node_modules/browserify-cipher/browser.js ***! + \***************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("var DES = __webpack_require__(/*! browserify-des */ \"./node_modules/browserify-des/index.js\")\nvar aes = __webpack_require__(/*! browserify-aes/browser */ \"./node_modules/browserify-aes/browser.js\")\nvar aesModes = __webpack_require__(/*! browserify-aes/modes */ \"./node_modules/browserify-aes/modes/index.js\")\nvar desModes = __webpack_require__(/*! browserify-des/modes */ \"./node_modules/browserify-des/modes.js\")\nvar ebtk = __webpack_require__(/*! evp_bytestokey */ \"./node_modules/evp_bytestokey/index.js\")\n\nfunction createCipher (suite, password) {\n suite = suite.toLowerCase()\n\n var keyLen, ivLen\n if (aesModes[suite]) {\n keyLen = aesModes[suite].key\n ivLen = aesModes[suite].iv\n } else if (desModes[suite]) {\n keyLen = desModes[suite].key * 8\n ivLen = desModes[suite].iv\n } else {\n throw new TypeError('invalid suite type')\n }\n\n var keys = ebtk(password, false, keyLen, ivLen)\n return createCipheriv(suite, keys.key, keys.iv)\n}\n\nfunction createDecipher (suite, password) {\n suite = suite.toLowerCase()\n\n var keyLen, ivLen\n if (aesModes[suite]) {\n keyLen = aesModes[suite].key\n ivLen = aesModes[suite].iv\n } else if (desModes[suite]) {\n keyLen = desModes[suite].key * 8\n ivLen = desModes[suite].iv\n } else {\n throw new TypeError('invalid suite type')\n }\n\n var keys = ebtk(password, false, keyLen, ivLen)\n return createDecipheriv(suite, keys.key, keys.iv)\n}\n\nfunction createCipheriv (suite, key, iv) {\n suite = suite.toLowerCase()\n if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)\n if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })\n\n throw new TypeError('invalid suite type')\n}\n\nfunction createDecipheriv (suite, key, iv) {\n suite = suite.toLowerCase()\n if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)\n if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })\n\n throw new TypeError('invalid suite type')\n}\n\nfunction getCiphers () {\n return Object.keys(desModes).concat(aes.getCiphers())\n}\n\nexports.createCipher = exports.Cipher = createCipher\nexports.createCipheriv = exports.Cipheriv = createCipheriv\nexports.createDecipher = exports.Decipher = createDecipher\nexports.createDecipheriv = exports.Decipheriv = createDecipheriv\nexports.listCiphers = exports.getCiphers = getCiphers\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-cipher/browser.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-des/index.js": +/*!**********************************************!*\ + !*** ./node_modules/browserify-des/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var CipherBase = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar des = __webpack_require__(/*! des.js */ \"./node_modules/des.js/lib/des.js\")\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar modes = {\n 'des-ede3-cbc': des.CBC.instantiate(des.EDE),\n 'des-ede3': des.EDE,\n 'des-ede-cbc': des.CBC.instantiate(des.EDE),\n 'des-ede': des.EDE,\n 'des-cbc': des.CBC.instantiate(des.DES),\n 'des-ecb': des.DES\n}\nmodes.des = modes['des-cbc']\nmodes.des3 = modes['des-ede3-cbc']\nmodule.exports = DES\ninherits(DES, CipherBase)\nfunction DES (opts) {\n CipherBase.call(this)\n var modeName = opts.mode.toLowerCase()\n var mode = modes[modeName]\n var type\n if (opts.decrypt) {\n type = 'decrypt'\n } else {\n type = 'encrypt'\n }\n var key = opts.key\n if (!Buffer.isBuffer(key)) {\n key = Buffer.from(key)\n }\n if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {\n key = Buffer.concat([key, key.slice(0, 8)])\n }\n var iv = opts.iv\n if (!Buffer.isBuffer(iv)) {\n iv = Buffer.from(iv)\n }\n this._des = mode.create({\n key: key,\n iv: iv,\n type: type\n })\n}\nDES.prototype._update = function (data) {\n return Buffer.from(this._des.update(data))\n}\nDES.prototype._final = function () {\n return Buffer.from(this._des.final())\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-des/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-des/modes.js": +/*!**********************************************!*\ + !*** ./node_modules/browserify-des/modes.js ***! + \**********************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("exports[\"des-ecb\"] = {\n key: 8,\n iv: 0\n}\nexports[\"des-cbc\"] = exports.des = {\n key: 8,\n iv: 8\n}\nexports[\"des-ede3-cbc\"] = exports.des3 = {\n key: 24,\n iv: 8\n}\nexports[\"des-ede3\"] = {\n key: 24,\n iv: 0\n}\nexports[\"des-ede-cbc\"] = {\n key: 16,\n iv: 8\n}\nexports[\"des-ede\"] = {\n key: 16,\n iv: 0\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-des/modes.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-rsa/index.js": +/*!**********************************************!*\ + !*** ./node_modules/browserify-rsa/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/bn.js/lib/bn.js\");\nvar randomBytes = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\");\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\n\nfunction getr(priv) {\n\tvar len = priv.modulus.byteLength();\n\tvar r;\n\tdo {\n\t\tr = new BN(randomBytes(len));\n\t} while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2));\n\treturn r;\n}\n\nfunction blind(priv) {\n\tvar r = getr(priv);\n\tvar blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed();\n\treturn { blinder: blinder, unblinder: r.invm(priv.modulus) };\n}\n\nfunction crt(msg, priv) {\n\tvar blinds = blind(priv);\n\tvar len = priv.modulus.byteLength();\n\tvar blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus);\n\tvar c1 = blinded.toRed(BN.mont(priv.prime1));\n\tvar c2 = blinded.toRed(BN.mont(priv.prime2));\n\tvar qinv = priv.coefficient;\n\tvar p = priv.prime1;\n\tvar q = priv.prime2;\n\tvar m1 = c1.redPow(priv.exponent1).fromRed();\n\tvar m2 = c2.redPow(priv.exponent2).fromRed();\n\tvar h = m1.isub(m2).imul(qinv).umod(p).imul(q);\n\treturn m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len);\n}\ncrt.getr = getr;\n\nmodule.exports = crt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-rsa/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/algos.js": +/*!***********************************************!*\ + !*** ./node_modules/browserify-sign/algos.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nmodule.exports = __webpack_require__(/*! ./browser/algorithms.json */ \"./node_modules/browserify-sign/browser/algorithms.json\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/algos.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/browser/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/browserify-sign/browser/index.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\nvar createHash = __webpack_require__(/*! create-hash */ \"./node_modules/create-hash/browser.js\");\nvar stream = __webpack_require__(/*! readable-stream */ \"./node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar sign = __webpack_require__(/*! ./sign */ \"./node_modules/browserify-sign/browser/sign.js\");\nvar verify = __webpack_require__(/*! ./verify */ \"./node_modules/browserify-sign/browser/verify.js\");\n\nvar algorithms = __webpack_require__(/*! ./algorithms.json */ \"./node_modules/browserify-sign/browser/algorithms.json\");\nObject.keys(algorithms).forEach(function (key) {\n algorithms[key].id = Buffer.from(algorithms[key].id, 'hex');\n algorithms[key.toLowerCase()] = algorithms[key];\n});\n\nfunction Sign(algorithm) {\n stream.Writable.call(this);\n\n var data = algorithms[algorithm];\n if (!data) { throw new Error('Unknown message digest'); }\n\n this._hashType = data.hash;\n this._hash = createHash(data.hash);\n this._tag = data.id;\n this._signType = data.sign;\n}\ninherits(Sign, stream.Writable);\n\nSign.prototype._write = function _write(data, _, done) {\n this._hash.update(data);\n done();\n};\n\nSign.prototype.update = function update(data, enc) {\n this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data);\n\n return this;\n};\n\nSign.prototype.sign = function signMethod(key, enc) {\n this.end();\n var hash = this._hash.digest();\n var sig = sign(hash, key, this._hashType, this._signType, this._tag);\n\n return enc ? sig.toString(enc) : sig;\n};\n\nfunction Verify(algorithm) {\n stream.Writable.call(this);\n\n var data = algorithms[algorithm];\n if (!data) { throw new Error('Unknown message digest'); }\n\n this._hash = createHash(data.hash);\n this._tag = data.id;\n this._signType = data.sign;\n}\ninherits(Verify, stream.Writable);\n\nVerify.prototype._write = function _write(data, _, done) {\n this._hash.update(data);\n done();\n};\n\nVerify.prototype.update = function update(data, enc) {\n this._hash.update(typeof data === 'string' ? Buffer.from(data, enc) : data);\n\n return this;\n};\n\nVerify.prototype.verify = function verifyMethod(key, sig, enc) {\n var sigBuffer = typeof sig === 'string' ? Buffer.from(sig, enc) : sig;\n\n this.end();\n var hash = this._hash.digest();\n return verify(sigBuffer, hash, key, this._signType, this._tag);\n};\n\nfunction createSign(algorithm) {\n return new Sign(algorithm);\n}\n\nfunction createVerify(algorithm) {\n return new Verify(algorithm);\n}\n\nmodule.exports = {\n Sign: createSign,\n Verify: createVerify,\n createSign: createSign,\n createVerify: createVerify\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/browser/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/browser/sign.js": +/*!******************************************************!*\ + !*** ./node_modules/browserify-sign/browser/sign.js ***! + \******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\nvar createHmac = __webpack_require__(/*! create-hmac */ \"./node_modules/create-hmac/browser.js\");\nvar crt = __webpack_require__(/*! browserify-rsa */ \"./node_modules/browserify-rsa/index.js\");\nvar EC = (__webpack_require__(/*! elliptic */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js\").ec);\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/bn.js/lib/bn.js\");\nvar parseKeys = __webpack_require__(/*! parse-asn1 */ \"./node_modules/parse-asn1/index.js\");\nvar curves = __webpack_require__(/*! ./curves.json */ \"./node_modules/browserify-sign/browser/curves.json\");\n\nvar RSA_PKCS1_PADDING = 1;\n\nfunction sign(hash, key, hashType, signType, tag) {\n var priv = parseKeys(key);\n if (priv.curve) {\n // rsa keys can be interpreted as ecdsa ones in openssl\n if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); }\n return ecSign(hash, priv);\n } else if (priv.type === 'dsa') {\n if (signType !== 'dsa') { throw new Error('wrong private key type'); }\n return dsaSign(hash, priv, hashType);\n }\n if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong private key type'); }\n if (key.padding !== undefined && key.padding !== RSA_PKCS1_PADDING) { throw new Error('illegal or unsupported padding mode'); }\n\n hash = Buffer.concat([tag, hash]);\n var len = priv.modulus.byteLength();\n var pad = [0, 1];\n while (hash.length + pad.length + 1 < len) { pad.push(0xff); }\n pad.push(0x00);\n var i = -1;\n while (++i < hash.length) { pad.push(hash[i]); }\n\n var out = crt(pad, priv);\n return out;\n}\n\nfunction ecSign(hash, priv) {\n var curveId = curves[priv.curve.join('.')];\n if (!curveId) { throw new Error('unknown curve ' + priv.curve.join('.')); }\n\n var curve = new EC(curveId);\n var key = curve.keyFromPrivate(priv.privateKey);\n var out = key.sign(hash);\n\n return Buffer.from(out.toDER());\n}\n\nfunction dsaSign(hash, priv, algo) {\n var x = priv.params.priv_key;\n var p = priv.params.p;\n var q = priv.params.q;\n var g = priv.params.g;\n var r = new BN(0);\n var k;\n var H = bits2int(hash, q).mod(q);\n var s = false;\n var kv = getKey(x, q, hash, algo);\n while (s === false) {\n k = makeKey(q, kv, algo);\n r = makeR(g, k, p, q);\n s = k.invm(q).imul(H.add(x.mul(r))).mod(q);\n if (s.cmpn(0) === 0) {\n s = false;\n r = new BN(0);\n }\n }\n return toDER(r, s);\n}\n\nfunction toDER(r, s) {\n r = r.toArray();\n s = s.toArray();\n\n // Pad values\n if (r[0] & 0x80) { r = [0].concat(r); }\n if (s[0] & 0x80) { s = [0].concat(s); }\n\n var total = r.length + s.length + 4;\n var res = [\n 0x30, total, 0x02, r.length\n ];\n res = res.concat(r, [0x02, s.length], s);\n return Buffer.from(res);\n}\n\nfunction getKey(x, q, hash, algo) {\n x = Buffer.from(x.toArray());\n if (x.length < q.byteLength()) {\n var zeros = Buffer.alloc(q.byteLength() - x.length);\n x = Buffer.concat([zeros, x]);\n }\n var hlen = hash.length;\n var hbits = bits2octets(hash, q);\n var v = Buffer.alloc(hlen);\n v.fill(1);\n var k = Buffer.alloc(hlen);\n k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest();\n v = createHmac(algo, k).update(v).digest();\n k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest();\n v = createHmac(algo, k).update(v).digest();\n return { k: k, v: v };\n}\n\nfunction bits2int(obits, q) {\n var bits = new BN(obits);\n var shift = (obits.length << 3) - q.bitLength();\n if (shift > 0) { bits.ishrn(shift); }\n return bits;\n}\n\nfunction bits2octets(bits, q) {\n bits = bits2int(bits, q);\n bits = bits.mod(q);\n var out = Buffer.from(bits.toArray());\n if (out.length < q.byteLength()) {\n var zeros = Buffer.alloc(q.byteLength() - out.length);\n out = Buffer.concat([zeros, out]);\n }\n return out;\n}\n\nfunction makeKey(q, kv, algo) {\n var t;\n var k;\n\n do {\n t = Buffer.alloc(0);\n\n while (t.length * 8 < q.bitLength()) {\n kv.v = createHmac(algo, kv.k).update(kv.v).digest();\n t = Buffer.concat([t, kv.v]);\n }\n\n k = bits2int(t, q);\n kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest();\n kv.v = createHmac(algo, kv.k).update(kv.v).digest();\n } while (k.cmp(q) !== -1);\n\n return k;\n}\n\nfunction makeR(g, k, p, q) {\n return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q);\n}\n\nmodule.exports = sign;\nmodule.exports.getKey = getKey;\nmodule.exports.makeKey = makeKey;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/browser/sign.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/browser/verify.js": +/*!********************************************************!*\ + !*** ./node_modules/browserify-sign/browser/verify.js ***! + \********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/bn.js/lib/bn.js\");\nvar EC = (__webpack_require__(/*! elliptic */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js\").ec);\nvar parseKeys = __webpack_require__(/*! parse-asn1 */ \"./node_modules/parse-asn1/index.js\");\nvar curves = __webpack_require__(/*! ./curves.json */ \"./node_modules/browserify-sign/browser/curves.json\");\n\nfunction verify(sig, hash, key, signType, tag) {\n var pub = parseKeys(key);\n if (pub.type === 'ec') {\n // rsa keys can be interpreted as ecdsa ones in openssl\n if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); }\n return ecVerify(sig, hash, pub);\n } else if (pub.type === 'dsa') {\n if (signType !== 'dsa') { throw new Error('wrong public key type'); }\n return dsaVerify(sig, hash, pub);\n }\n if (signType !== 'rsa' && signType !== 'ecdsa/rsa') { throw new Error('wrong public key type'); }\n\n hash = Buffer.concat([tag, hash]);\n var len = pub.modulus.byteLength();\n var pad = [1];\n var padNum = 0;\n while (hash.length + pad.length + 2 < len) {\n pad.push(0xff);\n padNum += 1;\n }\n pad.push(0x00);\n var i = -1;\n while (++i < hash.length) {\n pad.push(hash[i]);\n }\n pad = Buffer.from(pad);\n var red = BN.mont(pub.modulus);\n sig = new BN(sig).toRed(red);\n\n sig = sig.redPow(new BN(pub.publicExponent));\n sig = Buffer.from(sig.fromRed().toArray());\n var out = padNum < 8 ? 1 : 0;\n len = Math.min(sig.length, pad.length);\n if (sig.length !== pad.length) { out = 1; }\n\n i = -1;\n while (++i < len) { out |= sig[i] ^ pad[i]; }\n return out === 0;\n}\n\nfunction ecVerify(sig, hash, pub) {\n var curveId = curves[pub.data.algorithm.curve.join('.')];\n if (!curveId) { throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')); }\n\n var curve = new EC(curveId);\n var pubkey = pub.data.subjectPrivateKey.data;\n\n return curve.verify(hash, sig, pubkey);\n}\n\nfunction dsaVerify(sig, hash, pub) {\n var p = pub.data.p;\n var q = pub.data.q;\n var g = pub.data.g;\n var y = pub.data.pub_key;\n var unpacked = parseKeys.signature.decode(sig, 'der');\n var s = unpacked.s;\n var r = unpacked.r;\n checkValue(s, q);\n checkValue(r, q);\n var montp = BN.mont(p);\n var w = s.invm(q);\n var v = g.toRed(montp)\n .redPow(new BN(hash).mul(w).mod(q))\n .fromRed()\n .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())\n .mod(p)\n .mod(q);\n return v.cmp(r) === 0;\n}\n\nfunction checkValue(b, q) {\n if (b.cmpn(0) <= 0) { throw new Error('invalid sig'); }\n if (b.cmp(q) >= 0) { throw new Error('invalid sig'); }\n}\n\nmodule.exports = verify;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/browser/verify.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js": +/*!****************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js ***! + \****************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar elliptic = exports;\n\nelliptic.version = (__webpack_require__(/*! ../package.json */ \"./node_modules/browserify-sign/node_modules/elliptic/package.json\").version);\nelliptic.utils = __webpack_require__(/*! ./elliptic/utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nelliptic.rand = __webpack_require__(/*! brorand */ \"./node_modules/brorand/index.js\");\nelliptic.curve = __webpack_require__(/*! ./elliptic/curve */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js\");\nelliptic.curves = __webpack_require__(/*! ./elliptic/curves */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js\");\n\n// Protocols\nelliptic.ec = __webpack_require__(/*! ./elliptic/ec */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js\");\nelliptic.eddsa = __webpack_require__(/*! ./elliptic/eddsa */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js ***! + \***************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n this._bitLength = this.n ? this.n.bitLength() : 0;\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1, this._bitLength);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n var j;\n var nafW;\n for (j = 0; j < naf.length; j += doubles.step) {\n nafW = 0;\n for (var l = j + doubles.step - 1; l >= j; l--)\n nafW = (nafW << 1) + naf[l];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (j = 0; j < repr.length; j++) {\n nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w, this._bitLength);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var l = 0; i >= 0 && naf[i] === 0; i--)\n l++;\n if (i >= 0)\n l++;\n acc = acc.dblp(l);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n var i;\n var j;\n var p;\n for (i = 0; i < len; i++) {\n p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);\n naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b], /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3, /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (j = 0; j < len; j++) {\n var z = tmp[j];\n p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len));\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null,\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles,\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res,\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js ***! + \******************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n var e;\n var h;\n var j;\n if (this.curve.twisted) {\n // E = a * C\n e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n h = this.z.redSqr();\n // J = F - 2 * H\n j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n e = c.redAdd(d);\n // H = (c * Z1)^2\n h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar curve = exports;\n\ncurve.base = __webpack_require__(/*! ./base */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js\");\ncurve.short = __webpack_require__(/*! ./short */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js\");\ncurve.mont = __webpack_require__(/*! ./mont */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js\");\ncurve.edwards = __webpack_require__(/*! ./edwards */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/edwards.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js ***! + \***************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n return this.point(utils.toArray(bytes, enc), 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode() {\n return this.getX().toArray('be', this.curve.p.byteLength());\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/mont.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js ***! + \****************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16),\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis,\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 },\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n };\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul),\n },\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1),\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1),\n },\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point)),\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point)),\n },\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate),\n },\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n var i;\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/short.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js ***! + \***********************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar curves = exports;\n\nvar hash = __webpack_require__(/*! hash.js */ \"./node_modules/hash.js/lib/hash.js\");\nvar curve = __webpack_require__(/*! ./curve */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curve/index.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else\n this.curve = new curve.mont(options);\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve,\n });\n return curve;\n },\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',\n ],\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',\n ],\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',\n ],\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',\n ],\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650',\n ],\n});\n\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9',\n ],\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658',\n ],\n});\n\nvar pre;\ntry {\n pre = __webpack_require__(/*! ./precomputed/secp256k1 */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js\");\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3',\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15',\n },\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre,\n ],\n});\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js ***! + \*************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar HmacDRBG = __webpack_require__(/*! hmac-drbg */ \"./node_modules/hmac-drbg/lib/hmac-drbg.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar curves = __webpack_require__(/*! ../curves */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js\");\nvar rand = __webpack_require__(/*! brorand */ \"./node_modules/brorand/index.js\");\nvar assert = utils.assert;\n\nvar KeyPair = __webpack_require__(/*! ./key */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js\");\nvar Signature = __webpack_require__(/*! ./signature */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js\");\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(Object.prototype.hasOwnProperty.call(curves, options),\n 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash for function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray(),\n });\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n for (;;) {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n }\n};\n\nEC.prototype._truncateToN = function _truncateToN(msg, truncOnly, bitLength) {\n var byteLength;\n if (BN.isBN(msg) || typeof msg === 'number') {\n msg = new BN(msg, 16);\n byteLength = msg.byteLength();\n } else if (typeof msg === 'object') {\n // BN assumes an array-like input and asserts length\n byteLength = msg.length;\n msg = new BN(msg, 16);\n } else {\n // BN converts the value to string\n var str = msg.toString();\n // HEX encoding\n byteLength = (str.length + 1) >>> 1;\n msg = new BN(str, 16);\n }\n // Allow overriding\n if (typeof bitLength !== 'number') {\n bitLength = byteLength * 8;\n }\n var delta = bitLength - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n if (typeof msg !== 'string' && typeof msg !== 'number' && !BN.isBN(msg)) {\n assert(typeof msg === 'object' && msg && typeof msg.length === 'number',\n 'Expected message to be an array-like, a hex string, or a BN instance');\n assert((msg.length >>> 0) === msg.length); // non-negative 32-bit integer\n for (var i = 0; i < msg.length; i++) assert((msg[i] & 255) === msg[i]);\n }\n\n key = this.keyFromPrivate(key, enc);\n msg = this._truncateToN(msg, false, options.msgBitLength);\n\n // Would fail further checks, but let's make the error message clear\n assert(!msg.isNeg(), 'Can not sign a negative message');\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Recheck nonce to be bijective to msg\n assert((new BN(nonce)).eq(msg), 'Can not sign message');\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; ; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc, options) {\n if (!options)\n options = {};\n\n msg = this._truncateToN(msg, false, options.msgBitLength);\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n var p;\n\n if (!this.curve._maxwellTrick) {\n p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js ***! + \***********************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc,\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc,\n });\n};\n\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(compact, enc) {\n // compact is optional argument\n if (typeof compact === 'string') {\n enc = compact;\n compact = null;\n }\n\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n if(!pub.validate()) {\n assert(pub.validate(), 'public point not validated');\n }\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature, options) {\n return this.ec.verify(msg, signature, this, undefined, options);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/key.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js ***! + \*****************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n\n // Indefinite length or overflow\n if (octetLen === 0 || octetLen > 4) {\n return false;\n }\n\n if(buf[p.place] === 0x00) {\n return false;\n }\n\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n val >>>= 0;\n }\n\n // Leading zeroes\n if (val <= 0x7f) {\n return false;\n }\n\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if (len === false) {\n return false;\n }\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n if (rlen === false) {\n return false;\n }\n if ((data[p.place] & 128) !== 0) {\n return false;\n }\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (slen === false) {\n return false;\n }\n if (data.length !== slen + p.place) {\n return false;\n }\n if ((data[p.place] & 128) !== 0) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if (r[1] & 0x80) {\n r = r.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n if (s[0] === 0) {\n if (s[1] & 0x80) {\n s = s.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/ec/signature.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js ***! + \****************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar hash = __webpack_require__(/*! hash.js */ \"./node_modules/hash.js/lib/hash.js\");\nvar curves = __webpack_require__(/*! ../curves */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/curves.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = __webpack_require__(/*! ./key */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js\");\nvar Signature = __webpack_require__(/*! ./signature */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js\");\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) {\n return false;\n }\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js ***! + \**************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else\n this._pubBytes = parseBytes(params.pub);\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc) {\n return utils.encode(this.pubBytes(), enc);\n};\n\nmodule.exports = KeyPair;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/key.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js ***! + \********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size');\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength),\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/eddsa/signature.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js ***! + \**************************************************************************************************/ +/***/ ((module) => { + +eval("module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',\n ],\n ],\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',\n ],\n ],\n },\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js ***! + \**********************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = exports;\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar minAssert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\nvar minUtils = __webpack_require__(/*! minimalistic-crypto-utils */ \"./node_modules/minimalistic-crypto-utils/lib/utils.js\");\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w, bits) {\n var naf = new Array(Math.max(num.bitLength(), bits) + 1);\n var i;\n for (i = 0; i < naf.length; i += 1) {\n naf[i] = 0;\n }\n\n var ws = 1 << (w + 1);\n var k = num.clone();\n\n for (i = 0; i < naf.length; i++) {\n var z;\n var mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n\n naf[i] = z;\n k.iushrn(1);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n [],\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n var m8;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/lib/elliptic/utils.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js ***! + \*****************************************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?8bcc\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/isarray/index.js": +/*!********************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/isarray/index.js ***! + \********************************************************************/ +/***/ ((module) => { + +eval("var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/isarray/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js ***! + \*****************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/**/\n\nvar Readable = __webpack_require__(/*! ./_stream_readable */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js\");\nvar Writable = __webpack_require__(/*! ./_stream_writable */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js\");\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js ***! + \**********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n\n\nmodule.exports = PassThrough;\n\nvar Transform = __webpack_require__(/*! ./_stream_transform */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js\");\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js ***! + \*******************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = __webpack_require__(/*! isarray */ \"./node_modules/browserify-sign/node_modules/isarray/index.js\");\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/**/\n\n/**/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js\").Buffer);\nvar OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/**/\n\n/**/\nvar debugUtil = __webpack_require__(/*! util */ \"?593c\");\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/BufferList */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/BufferList.js\");\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = (__webpack_require__(/*! string_decoder/ */ \"./node_modules/browserify-sign/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = (__webpack_require__(/*! string_decoder/ */ \"./node_modules/browserify-sign/node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, { hasUnpiped: false });\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js ***! + \********************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\n\nmodule.exports = Transform;\n\nvar Duplex = __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js ***! + \*******************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(__webpack_require__(/*! core-util-is */ \"./node_modules/core-util-is/lib/util.js\"));\nutil.inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: __webpack_require__(/*! util-deprecate */ \"./node_modules/util-deprecate/browser.js\")\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/**/\n\n/**/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js\").Buffer);\nvar OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js\");\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/BufferList.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/BufferList.js ***! + \******************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js\").Buffer);\nvar util = __webpack_require__(/*! util */ \"?cad2\");\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/BufferList.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js ***! + \***************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n/**/\n\nvar pna = __webpack_require__(/*! process-nextick-args */ \"./node_modules/process-nextick-args/index.js\");\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/destroy.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js ***! + \**********************************************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/lib/internal/streams/stream-browser.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js ***! + \*****************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/node_modules/safe-buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js ***! + \***************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("exports = module.exports = __webpack_require__(/*! ./lib/_stream_readable.js */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_readable.js\");\nexports.Stream = exports;\nexports.Readable = exports;\nexports.Writable = __webpack_require__(/*! ./lib/_stream_writable.js */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_writable.js\");\nexports.Duplex = __webpack_require__(/*! ./lib/_stream_duplex.js */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_duplex.js\");\nexports.Transform = __webpack_require__(/*! ./lib/_stream_transform.js */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_transform.js\");\nexports.PassThrough = __webpack_require__(/*! ./lib/_stream_passthrough.js */ \"./node_modules/browserify-sign/node_modules/readable-stream/lib/_stream_passthrough.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/readable-stream/readable-browser.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/string_decoder/lib/string_decoder.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/string_decoder/lib/string_decoder.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/**/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer/index.js\").Buffer);\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/string_decoder/lib/string_decoder.js?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer/index.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer/index.js ***! + \****************************************************************************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/string_decoder/node_modules/safe-buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/buffer-xor/index.js": +/*!******************************************!*\ + !*** ./node_modules/buffer-xor/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\nmodule.exports = function xor (a, b) {\n var length = Math.min(a.length, b.length)\n var buffer = new Buffer(length)\n\n for (var i = 0; i < length; ++i) {\n buffer[i] = a[i] ^ b[i]\n }\n\n return buffer\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/buffer-xor/index.js?"); + +/***/ }), + +/***/ "./node_modules/buffer/index.js": +/*!**************************************!*\ + !*** ./node_modules/buffer/index.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n\n\nconst base64 = __webpack_require__(/*! base64-js */ \"./node_modules/base64-js/index.js\")\nconst ieee754 = __webpack_require__(/*! ieee754 */ \"./node_modules/ieee754/index.js\")\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/cipher-base/index.js": +/*!*******************************************!*\ + !*** ./node_modules/cipher-base/index.js ***! + \*******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\nvar Transform = (__webpack_require__(/*! stream */ \"./node_modules/stream-browserify/index.js\").Transform);\nvar StringDecoder = (__webpack_require__(/*! string_decoder */ \"./node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nfunction CipherBase(hashMode) {\n\tTransform.call(this);\n\tthis.hashMode = typeof hashMode === 'string';\n\tif (this.hashMode) {\n\t\tthis[hashMode] = this._finalOrDigest;\n\t} else {\n\t\tthis['final'] = this._finalOrDigest;\n\t}\n\tif (this._final) {\n\t\tthis.__final = this._final;\n\t\tthis._final = null;\n\t}\n\tthis._decoder = null;\n\tthis._encoding = null;\n}\ninherits(CipherBase, Transform);\n\nvar useUint8Array = typeof Uint8Array !== 'undefined';\nvar useArrayBuffer = typeof ArrayBuffer !== 'undefined'\n\t&& typeof Uint8Array !== 'undefined'\n\t&& ArrayBuffer.isView\n\t&& (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT);\n\nfunction toBuffer(data, encoding) {\n\t/*\n\t * No need to do anything for exact instance\n\t * This is only valid when safe-buffer.Buffer === buffer.Buffer, i.e. when Buffer.from/Buffer.alloc existed\n\t */\n\tif (data instanceof Buffer) {\n\t\treturn data;\n\t}\n\n\t// Convert strings to Buffer\n\tif (typeof data === 'string') {\n\t\treturn Buffer.from(data, encoding);\n\t}\n\n\t/*\n\t * Wrap any TypedArray instances and DataViews\n\t * Makes sense only on engines with full TypedArray support -- let Buffer detect that\n\t */\n\tif (useArrayBuffer && ArrayBuffer.isView(data)) {\n\t\t// Bug in Node.js <6.3.1, which treats this as out-of-bounds\n\t\tif (data.byteLength === 0) {\n\t\t\treturn Buffer.alloc(0);\n\t\t}\n\n\t\tvar res = Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n\t\t/*\n\t\t * Recheck result size, as offset/length doesn't work on Node.js <5.10\n\t\t * We just go to Uint8Array case if this fails\n\t\t */\n\t\tif (res.byteLength === data.byteLength) {\n\t\t\treturn res;\n\t\t}\n\t}\n\n\t/*\n\t * Uint8Array in engines where Buffer.from might not work with ArrayBuffer, just copy over\n\t * Doesn't make sense with other TypedArray instances\n\t */\n\tif (useUint8Array && data instanceof Uint8Array) {\n\t\treturn Buffer.from(data);\n\t}\n\n\t/*\n\t * Old Buffer polyfill on an engine that doesn't have TypedArray support\n\t * Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed\n\t * Convert to our current Buffer implementation\n\t */\n\tif (\n\t\tBuffer.isBuffer(data)\n\t\t\t&& data.constructor\n\t\t\t&& typeof data.constructor.isBuffer === 'function'\n\t\t\t&& data.constructor.isBuffer(data)\n\t) {\n\t\treturn Buffer.from(data);\n\t}\n\n\tthrow new TypeError('The \"data\" argument must be of type string or an instance of Buffer, TypedArray, or DataView.');\n}\n\nCipherBase.prototype.update = function (data, inputEnc, outputEnc) {\n\tvar bufferData = toBuffer(data, inputEnc); // asserts correct input type\n\tvar outData = this._update(bufferData);\n\tif (this.hashMode) {\n\t\treturn this;\n\t}\n\n\tif (outputEnc) {\n\t\toutData = this._toString(outData, outputEnc);\n\t}\n\n\treturn outData;\n};\n\nCipherBase.prototype.setAutoPadding = function () {};\nCipherBase.prototype.getAuthTag = function () {\n\tthrow new Error('trying to get auth tag in unsupported state');\n};\n\nCipherBase.prototype.setAuthTag = function () {\n\tthrow new Error('trying to set auth tag in unsupported state');\n};\n\nCipherBase.prototype.setAAD = function () {\n\tthrow new Error('trying to set aad in unsupported state');\n};\n\nCipherBase.prototype._transform = function (data, _, next) {\n\tvar err;\n\ttry {\n\t\tif (this.hashMode) {\n\t\t\tthis._update(data);\n\t\t} else {\n\t\t\tthis.push(this._update(data));\n\t\t}\n\t} catch (e) {\n\t\terr = e;\n\t} finally {\n\t\tnext(err);\n\t}\n};\nCipherBase.prototype._flush = function (done) {\n\tvar err;\n\ttry {\n\t\tthis.push(this.__final());\n\t} catch (e) {\n\t\terr = e;\n\t}\n\n\tdone(err);\n};\nCipherBase.prototype._finalOrDigest = function (outputEnc) {\n\tvar outData = this.__final() || Buffer.alloc(0);\n\tif (outputEnc) {\n\t\toutData = this._toString(outData, outputEnc, true);\n\t}\n\treturn outData;\n};\n\nCipherBase.prototype._toString = function (value, enc, fin) {\n\tif (!this._decoder) {\n\t\tthis._decoder = new StringDecoder(enc);\n\t\tthis._encoding = enc;\n\t}\n\n\tif (this._encoding !== enc) {\n\t\tthrow new Error('can’t switch encodings');\n\t}\n\n\tvar out = this._decoder.write(value);\n\tif (fin) {\n\t\tout += this._decoder.end();\n\t}\n\n\treturn out;\n};\n\nmodule.exports = CipherBase;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/cipher-base/index.js?"); + +/***/ }), + +/***/ "./node_modules/core-util-is/lib/util.js": +/*!***********************************************!*\ + !*** ./node_modules/core-util-is/lib/util.js ***! + \***********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/core-util-is/lib/util.js?"); + +/***/ }), + +/***/ "./node_modules/create-ecdh/browser.js": +/*!*********************************************!*\ + !*** ./node_modules/create-ecdh/browser.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\nvar elliptic = __webpack_require__(/*! elliptic */ \"./node_modules/elliptic/lib/elliptic.js\")\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/create-ecdh/node_modules/bn.js/lib/bn.js\")\n\nmodule.exports = function createECDH (curve) {\n return new ECDH(curve)\n}\n\nvar aliases = {\n secp256k1: {\n name: 'secp256k1',\n byteLength: 32\n },\n secp224r1: {\n name: 'p224',\n byteLength: 28\n },\n prime256v1: {\n name: 'p256',\n byteLength: 32\n },\n prime192v1: {\n name: 'p192',\n byteLength: 24\n },\n ed25519: {\n name: 'ed25519',\n byteLength: 32\n },\n secp384r1: {\n name: 'p384',\n byteLength: 48\n },\n secp521r1: {\n name: 'p521',\n byteLength: 66\n }\n}\n\naliases.p224 = aliases.secp224r1\naliases.p256 = aliases.secp256r1 = aliases.prime256v1\naliases.p192 = aliases.secp192r1 = aliases.prime192v1\naliases.p384 = aliases.secp384r1\naliases.p521 = aliases.secp521r1\n\nfunction ECDH (curve) {\n this.curveType = aliases[curve]\n if (!this.curveType) {\n this.curveType = {\n name: curve\n }\n }\n this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap\n this.keys = void 0\n}\n\nECDH.prototype.generateKeys = function (enc, format) {\n this.keys = this.curve.genKeyPair()\n return this.getPublicKey(enc, format)\n}\n\nECDH.prototype.computeSecret = function (other, inenc, enc) {\n inenc = inenc || 'utf8'\n if (!Buffer.isBuffer(other)) {\n other = new Buffer(other, inenc)\n }\n var otherPub = this.curve.keyFromPublic(other).getPublic()\n var out = otherPub.mul(this.keys.getPrivate()).getX()\n return formatReturnValue(out, enc, this.curveType.byteLength)\n}\n\nECDH.prototype.getPublicKey = function (enc, format) {\n var key = this.keys.getPublic(format === 'compressed', true)\n if (format === 'hybrid') {\n if (key[key.length - 1] % 2) {\n key[0] = 7\n } else {\n key[0] = 6\n }\n }\n return formatReturnValue(key, enc)\n}\n\nECDH.prototype.getPrivateKey = function (enc) {\n return formatReturnValue(this.keys.getPrivate(), enc)\n}\n\nECDH.prototype.setPublicKey = function (pub, enc) {\n enc = enc || 'utf8'\n if (!Buffer.isBuffer(pub)) {\n pub = new Buffer(pub, enc)\n }\n this.keys._importPublic(pub)\n return this\n}\n\nECDH.prototype.setPrivateKey = function (priv, enc) {\n enc = enc || 'utf8'\n if (!Buffer.isBuffer(priv)) {\n priv = new Buffer(priv, enc)\n }\n\n var _priv = new BN(priv)\n _priv = _priv.toString(16)\n this.keys = this.curve.genKeyPair()\n this.keys._importPrivate(_priv)\n return this\n}\n\nfunction formatReturnValue (bn, enc, len) {\n if (!Array.isArray(bn)) {\n bn = bn.toArray()\n }\n var buf = new Buffer(bn)\n if (len && buf.length < len) {\n var zeros = new Buffer(len - buf.length)\n zeros.fill(0)\n buf = Buffer.concat([zeros, buf])\n }\n if (!enc) {\n return buf\n } else {\n return buf.toString(enc)\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-ecdh/browser.js?"); + +/***/ }), + +/***/ "./node_modules/create-ecdh/node_modules/bn.js/lib/bn.js": +/*!***************************************************************!*\ + !*** ./node_modules/create-ecdh/node_modules/bn.js/lib/bn.js ***! + \***************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?4068\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-ecdh/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + +/***/ "./node_modules/create-hash/browser.js": +/*!*********************************************!*\ + !*** ./node_modules/create-hash/browser.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar MD5 = __webpack_require__(/*! md5.js */ \"./node_modules/md5.js/index.js\")\nvar RIPEMD160 = __webpack_require__(/*! ripemd160 */ \"./node_modules/ripemd160/index.js\")\nvar sha = __webpack_require__(/*! sha.js */ \"./node_modules/sha.js/index.js\")\nvar Base = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\n\nfunction Hash (hash) {\n Base.call(this, 'digest')\n\n this._hash = hash\n}\n\ninherits(Hash, Base)\n\nHash.prototype._update = function (data) {\n this._hash.update(data)\n}\n\nHash.prototype._final = function () {\n return this._hash.digest()\n}\n\nmodule.exports = function createHash (alg) {\n alg = alg.toLowerCase()\n if (alg === 'md5') return new MD5()\n if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()\n\n return new Hash(sha(alg))\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-hash/browser.js?"); + +/***/ }), + +/***/ "./node_modules/create-hash/md5.js": +/*!*****************************************!*\ + !*** ./node_modules/create-hash/md5.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var MD5 = __webpack_require__(/*! md5.js */ \"./node_modules/md5.js/index.js\")\n\nmodule.exports = function (buffer) {\n return new MD5().update(buffer).digest()\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-hash/md5.js?"); + +/***/ }), + +/***/ "./node_modules/create-hmac/browser.js": +/*!*********************************************!*\ + !*** ./node_modules/create-hmac/browser.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Legacy = __webpack_require__(/*! ./legacy */ \"./node_modules/create-hmac/legacy.js\")\nvar Base = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar md5 = __webpack_require__(/*! create-hash/md5 */ \"./node_modules/create-hash/md5.js\")\nvar RIPEMD160 = __webpack_require__(/*! ripemd160 */ \"./node_modules/ripemd160/index.js\")\n\nvar sha = __webpack_require__(/*! sha.js */ \"./node_modules/sha.js/index.js\")\n\nvar ZEROS = Buffer.alloc(128)\n\nfunction Hmac (alg, key) {\n Base.call(this, 'digest')\n if (typeof key === 'string') {\n key = Buffer.from(key)\n }\n\n var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64\n\n this._alg = alg\n this._key = key\n if (key.length > blocksize) {\n var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)\n key = hash.update(key).digest()\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = this._ipad = Buffer.allocUnsafe(blocksize)\n var opad = this._opad = Buffer.allocUnsafe(blocksize)\n\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)\n this._hash.update(ipad)\n}\n\ninherits(Hmac, Base)\n\nHmac.prototype._update = function (data) {\n this._hash.update(data)\n}\n\nHmac.prototype._final = function () {\n var h = this._hash.digest()\n var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)\n return hash.update(this._opad).update(h).digest()\n}\n\nmodule.exports = function createHmac (alg, key) {\n alg = alg.toLowerCase()\n if (alg === 'rmd160' || alg === 'ripemd160') {\n return new Hmac('rmd160', key)\n }\n if (alg === 'md5') {\n return new Legacy(md5, key)\n }\n return new Hmac(alg, key)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-hmac/browser.js?"); + +/***/ }), + +/***/ "./node_modules/create-hmac/legacy.js": +/*!********************************************!*\ + !*** ./node_modules/create-hmac/legacy.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar Base = __webpack_require__(/*! cipher-base */ \"./node_modules/cipher-base/index.js\")\n\nvar ZEROS = Buffer.alloc(128)\nvar blocksize = 64\n\nfunction Hmac (alg, key) {\n Base.call(this, 'digest')\n if (typeof key === 'string') {\n key = Buffer.from(key)\n }\n\n this._alg = alg\n this._key = key\n\n if (key.length > blocksize) {\n key = alg(key)\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = this._ipad = Buffer.allocUnsafe(blocksize)\n var opad = this._opad = Buffer.allocUnsafe(blocksize)\n\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n\n this._hash = [ipad]\n}\n\ninherits(Hmac, Base)\n\nHmac.prototype._update = function (data) {\n this._hash.push(data)\n}\n\nHmac.prototype._final = function () {\n var h = this._alg(Buffer.concat(this._hash))\n return this._alg(Buffer.concat([this._opad, h]))\n}\nmodule.exports = Hmac\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/create-hmac/legacy.js?"); + +/***/ }), + +/***/ "./node_modules/crypto-browserify/index.js": +/*!*************************************************!*\ + !*** ./node_modules/crypto-browserify/index.js ***! + \*************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\n// eslint-disable-next-line no-multi-assign\nexports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\");\n\n// eslint-disable-next-line no-multi-assign\nexports.createHash = exports.Hash = __webpack_require__(/*! create-hash */ \"./node_modules/create-hash/browser.js\");\n\n// eslint-disable-next-line no-multi-assign\nexports.createHmac = exports.Hmac = __webpack_require__(/*! create-hmac */ \"./node_modules/create-hmac/browser.js\");\n\nvar algos = __webpack_require__(/*! browserify-sign/algos */ \"./node_modules/browserify-sign/algos.js\");\nvar algoKeys = Object.keys(algos);\nvar hashes = [\n\t'sha1',\n\t'sha224',\n\t'sha256',\n\t'sha384',\n\t'sha512',\n\t'md5',\n\t'rmd160'\n].concat(algoKeys);\n\nexports.getHashes = function () {\n\treturn hashes;\n};\n\nvar p = __webpack_require__(/*! pbkdf2 */ \"./node_modules/pbkdf2/browser.js\");\nexports.pbkdf2 = p.pbkdf2;\nexports.pbkdf2Sync = p.pbkdf2Sync;\n\nvar aes = __webpack_require__(/*! browserify-cipher */ \"./node_modules/browserify-cipher/browser.js\");\n\nexports.Cipher = aes.Cipher;\nexports.createCipher = aes.createCipher;\nexports.Cipheriv = aes.Cipheriv;\nexports.createCipheriv = aes.createCipheriv;\nexports.Decipher = aes.Decipher;\nexports.createDecipher = aes.createDecipher;\nexports.Decipheriv = aes.Decipheriv;\nexports.createDecipheriv = aes.createDecipheriv;\nexports.getCiphers = aes.getCiphers;\nexports.listCiphers = aes.listCiphers;\n\nvar dh = __webpack_require__(/*! diffie-hellman */ \"./node_modules/diffie-hellman/browser.js\");\n\nexports.DiffieHellmanGroup = dh.DiffieHellmanGroup;\nexports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup;\nexports.getDiffieHellman = dh.getDiffieHellman;\nexports.createDiffieHellman = dh.createDiffieHellman;\nexports.DiffieHellman = dh.DiffieHellman;\n\nvar sign = __webpack_require__(/*! browserify-sign */ \"./node_modules/browserify-sign/browser/index.js\");\n\nexports.createSign = sign.createSign;\nexports.Sign = sign.Sign;\nexports.createVerify = sign.createVerify;\nexports.Verify = sign.Verify;\n\nexports.createECDH = __webpack_require__(/*! create-ecdh */ \"./node_modules/create-ecdh/browser.js\");\n\nvar publicEncrypt = __webpack_require__(/*! public-encrypt */ \"./node_modules/public-encrypt/browser.js\");\n\nexports.publicEncrypt = publicEncrypt.publicEncrypt;\nexports.privateEncrypt = publicEncrypt.privateEncrypt;\nexports.publicDecrypt = publicEncrypt.publicDecrypt;\nexports.privateDecrypt = publicEncrypt.privateDecrypt;\n\n// the least I can do is make error messages for the rest of the node.js/crypto api.\n// [\n// 'createCredentials'\n// ].forEach(function (name) {\n// exports[name] = function () {\n// throw new Error('sorry, ' + name + ' is not implemented yet\\nwe accept pull requests\\nhttps://github.com/browserify/crypto-browserify');\n// };\n// });\n\nvar rf = __webpack_require__(/*! randomfill */ \"./node_modules/randomfill/browser.js\");\n\nexports.randomFill = rf.randomFill;\nexports.randomFillSync = rf.randomFillSync;\n\nexports.createCredentials = function () {\n\tthrow new Error('sorry, createCredentials is not implemented yet\\nwe accept pull requests\\nhttps://github.com/browserify/crypto-browserify');\n};\n\nexports.constants = {\n\tDH_CHECK_P_NOT_SAFE_PRIME: 2,\n\tDH_CHECK_P_NOT_PRIME: 1,\n\tDH_UNABLE_TO_CHECK_GENERATOR: 4,\n\tDH_NOT_SUITABLE_GENERATOR: 8,\n\tNPN_ENABLED: 1,\n\tALPN_ENABLED: 1,\n\tRSA_PKCS1_PADDING: 1,\n\tRSA_SSLV23_PADDING: 2,\n\tRSA_NO_PADDING: 3,\n\tRSA_PKCS1_OAEP_PADDING: 4,\n\tRSA_X931_PADDING: 5,\n\tRSA_PKCS1_PSS_PADDING: 6,\n\tPOINT_CONVERSION_COMPRESSED: 2,\n\tPOINT_CONVERSION_UNCOMPRESSED: 4,\n\tPOINT_CONVERSION_HYBRID: 6\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/crypto-browserify/index.js?"); + +/***/ }), + /***/ "./node_modules/debug/src/browser.js": /*!*******************************************!*\ !*** ./node_modules/debug/src/browser.js ***! \*******************************************/ /***/ ((module, exports, __webpack_require__) => { -eval("/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = __webpack_require__(/*! ./common */ \"./node_modules/debug/src/common.js\")(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/debug/src/browser.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = __webpack_require__(/*! ./common */ \"./node_modules/debug/src/common.js\")(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/debug/src/browser.js?"); /***/ }), @@ -1024,7 +1923,7 @@ eval("/* eslint-env browser */\n\n/**\n * This is the web browser implementation \******************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = __webpack_require__(/*! ms */ \"./node_modules/ms/index.js\");\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/debug/src/common.js?"); +eval("\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = __webpack_require__(/*! ms */ \"./node_modules/ms/index.js\");\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(' ', ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/debug/src/common.js?"); /***/ }), @@ -1039,6 +1938,286 @@ eval("\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction /***/ }), +/***/ "./node_modules/des.js/lib/des.js": +/*!****************************************!*\ + !*** ./node_modules/des.js/lib/des.js ***! + \****************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nexports.utils = __webpack_require__(/*! ./des/utils */ \"./node_modules/des.js/lib/des/utils.js\");\nexports.Cipher = __webpack_require__(/*! ./des/cipher */ \"./node_modules/des.js/lib/des/cipher.js\");\nexports.DES = __webpack_require__(/*! ./des/des */ \"./node_modules/des.js/lib/des/des.js\");\nexports.CBC = __webpack_require__(/*! ./des/cbc */ \"./node_modules/des.js/lib/des/cbc.js\");\nexports.EDE = __webpack_require__(/*! ./des/ede */ \"./node_modules/des.js/lib/des/ede.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des.js?"); + +/***/ }), + +/***/ "./node_modules/des.js/lib/des/cbc.js": +/*!********************************************!*\ + !*** ./node_modules/des.js/lib/des/cbc.js ***! + \********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar proto = {};\n\nfunction CBCState(iv) {\n assert.equal(iv.length, 8, 'Invalid IV length');\n\n this.iv = new Array(8);\n for (var i = 0; i < this.iv.length; i++)\n this.iv[i] = iv[i];\n}\n\nfunction instantiate(Base) {\n function CBC(options) {\n Base.call(this, options);\n this._cbcInit();\n }\n inherits(CBC, Base);\n\n var keys = Object.keys(proto);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n CBC.prototype[key] = proto[key];\n }\n\n CBC.create = function create(options) {\n return new CBC(options);\n };\n\n return CBC;\n}\n\nexports.instantiate = instantiate;\n\nproto._cbcInit = function _cbcInit() {\n var state = new CBCState(this.options.iv);\n this._cbcState = state;\n};\n\nproto._update = function _update(inp, inOff, out, outOff) {\n var state = this._cbcState;\n var superProto = this.constructor.super_.prototype;\n\n var iv = state.iv;\n if (this.type === 'encrypt') {\n for (var i = 0; i < this.blockSize; i++)\n iv[i] ^= inp[inOff + i];\n\n superProto._update.call(this, iv, 0, out, outOff);\n\n for (var i = 0; i < this.blockSize; i++)\n iv[i] = out[outOff + i];\n } else {\n superProto._update.call(this, inp, inOff, out, outOff);\n\n for (var i = 0; i < this.blockSize; i++)\n out[outOff + i] ^= iv[i];\n\n for (var i = 0; i < this.blockSize; i++)\n iv[i] = inp[inOff + i];\n }\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des/cbc.js?"); + +/***/ }), + +/***/ "./node_modules/des.js/lib/des/cipher.js": +/*!***********************************************!*\ + !*** ./node_modules/des.js/lib/des/cipher.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\n\nfunction Cipher(options) {\n this.options = options;\n\n this.type = this.options.type;\n this.blockSize = 8;\n this._init();\n\n this.buffer = new Array(this.blockSize);\n this.bufferOff = 0;\n this.padding = options.padding !== false\n}\nmodule.exports = Cipher;\n\nCipher.prototype._init = function _init() {\n // Might be overrided\n};\n\nCipher.prototype.update = function update(data) {\n if (data.length === 0)\n return [];\n\n if (this.type === 'decrypt')\n return this._updateDecrypt(data);\n else\n return this._updateEncrypt(data);\n};\n\nCipher.prototype._buffer = function _buffer(data, off) {\n // Append data to buffer\n var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);\n for (var i = 0; i < min; i++)\n this.buffer[this.bufferOff + i] = data[off + i];\n this.bufferOff += min;\n\n // Shift next\n return min;\n};\n\nCipher.prototype._flushBuffer = function _flushBuffer(out, off) {\n this._update(this.buffer, 0, out, off);\n this.bufferOff = 0;\n return this.blockSize;\n};\n\nCipher.prototype._updateEncrypt = function _updateEncrypt(data) {\n var inputOff = 0;\n var outputOff = 0;\n\n var count = ((this.bufferOff + data.length) / this.blockSize) | 0;\n var out = new Array(count * this.blockSize);\n\n if (this.bufferOff !== 0) {\n inputOff += this._buffer(data, inputOff);\n\n if (this.bufferOff === this.buffer.length)\n outputOff += this._flushBuffer(out, outputOff);\n }\n\n // Write blocks\n var max = data.length - ((data.length - inputOff) % this.blockSize);\n for (; inputOff < max; inputOff += this.blockSize) {\n this._update(data, inputOff, out, outputOff);\n outputOff += this.blockSize;\n }\n\n // Queue rest\n for (; inputOff < data.length; inputOff++, this.bufferOff++)\n this.buffer[this.bufferOff] = data[inputOff];\n\n return out;\n};\n\nCipher.prototype._updateDecrypt = function _updateDecrypt(data) {\n var inputOff = 0;\n var outputOff = 0;\n\n var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;\n var out = new Array(count * this.blockSize);\n\n // TODO(indutny): optimize it, this is far from optimal\n for (; count > 0; count--) {\n inputOff += this._buffer(data, inputOff);\n outputOff += this._flushBuffer(out, outputOff);\n }\n\n // Buffer rest of the input\n inputOff += this._buffer(data, inputOff);\n\n return out;\n};\n\nCipher.prototype.final = function final(buffer) {\n var first;\n if (buffer)\n first = this.update(buffer);\n\n var last;\n if (this.type === 'encrypt')\n last = this._finalEncrypt();\n else\n last = this._finalDecrypt();\n\n if (first)\n return first.concat(last);\n else\n return last;\n};\n\nCipher.prototype._pad = function _pad(buffer, off) {\n if (off === 0)\n return false;\n\n while (off < buffer.length)\n buffer[off++] = 0;\n\n return true;\n};\n\nCipher.prototype._finalEncrypt = function _finalEncrypt() {\n if (!this._pad(this.buffer, this.bufferOff))\n return [];\n\n var out = new Array(this.blockSize);\n this._update(this.buffer, 0, out, 0);\n return out;\n};\n\nCipher.prototype._unpad = function _unpad(buffer) {\n return buffer;\n};\n\nCipher.prototype._finalDecrypt = function _finalDecrypt() {\n assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');\n var out = new Array(this.blockSize);\n this._flushBuffer(out, 0);\n\n return this._unpad(out);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des/cipher.js?"); + +/***/ }), + +/***/ "./node_modules/des.js/lib/des/des.js": +/*!********************************************!*\ + !*** ./node_modules/des.js/lib/des/des.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/des.js/lib/des/utils.js\");\nvar Cipher = __webpack_require__(/*! ./cipher */ \"./node_modules/des.js/lib/des/cipher.js\");\n\nfunction DESState() {\n this.tmp = new Array(2);\n this.keys = null;\n}\n\nfunction DES(options) {\n Cipher.call(this, options);\n\n var state = new DESState();\n this._desState = state;\n\n this.deriveKeys(state, options.key);\n}\ninherits(DES, Cipher);\nmodule.exports = DES;\n\nDES.create = function create(options) {\n return new DES(options);\n};\n\nvar shiftTable = [\n 1, 1, 2, 2, 2, 2, 2, 2,\n 1, 2, 2, 2, 2, 2, 2, 1\n];\n\nDES.prototype.deriveKeys = function deriveKeys(state, key) {\n state.keys = new Array(16 * 2);\n\n assert.equal(key.length, this.blockSize, 'Invalid key length');\n\n var kL = utils.readUInt32BE(key, 0);\n var kR = utils.readUInt32BE(key, 4);\n\n utils.pc1(kL, kR, state.tmp, 0);\n kL = state.tmp[0];\n kR = state.tmp[1];\n for (var i = 0; i < state.keys.length; i += 2) {\n var shift = shiftTable[i >>> 1];\n kL = utils.r28shl(kL, shift);\n kR = utils.r28shl(kR, shift);\n utils.pc2(kL, kR, state.keys, i);\n }\n};\n\nDES.prototype._update = function _update(inp, inOff, out, outOff) {\n var state = this._desState;\n\n var l = utils.readUInt32BE(inp, inOff);\n var r = utils.readUInt32BE(inp, inOff + 4);\n\n // Initial Permutation\n utils.ip(l, r, state.tmp, 0);\n l = state.tmp[0];\n r = state.tmp[1];\n\n if (this.type === 'encrypt')\n this._encrypt(state, l, r, state.tmp, 0);\n else\n this._decrypt(state, l, r, state.tmp, 0);\n\n l = state.tmp[0];\n r = state.tmp[1];\n\n utils.writeUInt32BE(out, l, outOff);\n utils.writeUInt32BE(out, r, outOff + 4);\n};\n\nDES.prototype._pad = function _pad(buffer, off) {\n if (this.padding === false) {\n return false;\n }\n\n var value = buffer.length - off;\n for (var i = off; i < buffer.length; i++)\n buffer[i] = value;\n\n return true;\n};\n\nDES.prototype._unpad = function _unpad(buffer) {\n if (this.padding === false) {\n return buffer;\n }\n\n var pad = buffer[buffer.length - 1];\n for (var i = buffer.length - pad; i < buffer.length; i++)\n assert.equal(buffer[i], pad);\n\n return buffer.slice(0, buffer.length - pad);\n};\n\nDES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {\n var l = lStart;\n var r = rStart;\n\n // Apply f() x16 times\n for (var i = 0; i < state.keys.length; i += 2) {\n var keyL = state.keys[i];\n var keyR = state.keys[i + 1];\n\n // f(r, k)\n utils.expand(r, state.tmp, 0);\n\n keyL ^= state.tmp[0];\n keyR ^= state.tmp[1];\n var s = utils.substitute(keyL, keyR);\n var f = utils.permute(s);\n\n var t = r;\n r = (l ^ f) >>> 0;\n l = t;\n }\n\n // Reverse Initial Permutation\n utils.rip(r, l, out, off);\n};\n\nDES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {\n var l = rStart;\n var r = lStart;\n\n // Apply f() x16 times\n for (var i = state.keys.length - 2; i >= 0; i -= 2) {\n var keyL = state.keys[i];\n var keyR = state.keys[i + 1];\n\n // f(r, k)\n utils.expand(l, state.tmp, 0);\n\n keyL ^= state.tmp[0];\n keyR ^= state.tmp[1];\n var s = utils.substitute(keyL, keyR);\n var f = utils.permute(s);\n\n var t = l;\n l = (r ^ f) >>> 0;\n r = t;\n }\n\n // Reverse Initial Permutation\n utils.rip(l, r, out, off);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des/des.js?"); + +/***/ }), + +/***/ "./node_modules/des.js/lib/des/ede.js": +/*!********************************************!*\ + !*** ./node_modules/des.js/lib/des/ede.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\nvar Cipher = __webpack_require__(/*! ./cipher */ \"./node_modules/des.js/lib/des/cipher.js\");\nvar DES = __webpack_require__(/*! ./des */ \"./node_modules/des.js/lib/des/des.js\");\n\nfunction EDEState(type, key) {\n assert.equal(key.length, 24, 'Invalid key length');\n\n var k1 = key.slice(0, 8);\n var k2 = key.slice(8, 16);\n var k3 = key.slice(16, 24);\n\n if (type === 'encrypt') {\n this.ciphers = [\n DES.create({ type: 'encrypt', key: k1 }),\n DES.create({ type: 'decrypt', key: k2 }),\n DES.create({ type: 'encrypt', key: k3 })\n ];\n } else {\n this.ciphers = [\n DES.create({ type: 'decrypt', key: k3 }),\n DES.create({ type: 'encrypt', key: k2 }),\n DES.create({ type: 'decrypt', key: k1 })\n ];\n }\n}\n\nfunction EDE(options) {\n Cipher.call(this, options);\n\n var state = new EDEState(this.type, this.options.key);\n this._edeState = state;\n}\ninherits(EDE, Cipher);\n\nmodule.exports = EDE;\n\nEDE.create = function create(options) {\n return new EDE(options);\n};\n\nEDE.prototype._update = function _update(inp, inOff, out, outOff) {\n var state = this._edeState;\n\n state.ciphers[0]._update(inp, inOff, out, outOff);\n state.ciphers[1]._update(out, outOff, out, outOff);\n state.ciphers[2]._update(out, outOff, out, outOff);\n};\n\nEDE.prototype._pad = DES.prototype._pad;\nEDE.prototype._unpad = DES.prototype._unpad;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des/ede.js?"); + +/***/ }), + +/***/ "./node_modules/des.js/lib/des/utils.js": +/*!**********************************************!*\ + !*** ./node_modules/des.js/lib/des/utils.js ***! + \**********************************************/ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +eval("\n\nexports.readUInt32BE = function readUInt32BE(bytes, off) {\n var res = (bytes[0 + off] << 24) |\n (bytes[1 + off] << 16) |\n (bytes[2 + off] << 8) |\n bytes[3 + off];\n return res >>> 0;\n};\n\nexports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {\n bytes[0 + off] = value >>> 24;\n bytes[1 + off] = (value >>> 16) & 0xff;\n bytes[2 + off] = (value >>> 8) & 0xff;\n bytes[3 + off] = value & 0xff;\n};\n\nexports.ip = function ip(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n for (var i = 6; i >= 0; i -= 2) {\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >>> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inL >>> (j + i)) & 1;\n }\n }\n\n for (var i = 6; i >= 0; i -= 2) {\n for (var j = 1; j <= 25; j += 8) {\n outR <<= 1;\n outR |= (inR >>> (j + i)) & 1;\n }\n for (var j = 1; j <= 25; j += 8) {\n outR <<= 1;\n outR |= (inL >>> (j + i)) & 1;\n }\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.rip = function rip(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n for (var i = 0; i < 4; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n outL <<= 1;\n outL |= (inR >>> (j + i)) & 1;\n outL <<= 1;\n outL |= (inL >>> (j + i)) & 1;\n }\n }\n for (var i = 4; i < 8; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n outR <<= 1;\n outR |= (inR >>> (j + i)) & 1;\n outR <<= 1;\n outR |= (inL >>> (j + i)) & 1;\n }\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.pc1 = function pc1(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n // 7, 15, 23, 31, 39, 47, 55, 63\n // 6, 14, 22, 30, 39, 47, 55, 63\n // 5, 13, 21, 29, 39, 47, 55, 63\n // 4, 12, 20, 28\n for (var i = 7; i >= 5; i--) {\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inL >> (j + i)) & 1;\n }\n }\n for (var j = 0; j <= 24; j += 8) {\n outL <<= 1;\n outL |= (inR >> (j + i)) & 1;\n }\n\n // 1, 9, 17, 25, 33, 41, 49, 57\n // 2, 10, 18, 26, 34, 42, 50, 58\n // 3, 11, 19, 27, 35, 43, 51, 59\n // 36, 44, 52, 60\n for (var i = 1; i <= 3; i++) {\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inR >> (j + i)) & 1;\n }\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inL >> (j + i)) & 1;\n }\n }\n for (var j = 0; j <= 24; j += 8) {\n outR <<= 1;\n outR |= (inL >> (j + i)) & 1;\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.r28shl = function r28shl(num, shift) {\n return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));\n};\n\nvar pc2table = [\n // inL => outL\n 14, 11, 17, 4, 27, 23, 25, 0,\n 13, 22, 7, 18, 5, 9, 16, 24,\n 2, 20, 12, 21, 1, 8, 15, 26,\n\n // inR => outR\n 15, 4, 25, 19, 9, 1, 26, 16,\n 5, 11, 23, 8, 12, 7, 17, 0,\n 22, 3, 10, 14, 6, 20, 27, 24\n];\n\nexports.pc2 = function pc2(inL, inR, out, off) {\n var outL = 0;\n var outR = 0;\n\n var len = pc2table.length >>> 1;\n for (var i = 0; i < len; i++) {\n outL <<= 1;\n outL |= (inL >>> pc2table[i]) & 0x1;\n }\n for (var i = len; i < pc2table.length; i++) {\n outR <<= 1;\n outR |= (inR >>> pc2table[i]) & 0x1;\n }\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nexports.expand = function expand(r, out, off) {\n var outL = 0;\n var outR = 0;\n\n outL = ((r & 1) << 5) | (r >>> 27);\n for (var i = 23; i >= 15; i -= 4) {\n outL <<= 6;\n outL |= (r >>> i) & 0x3f;\n }\n for (var i = 11; i >= 3; i -= 4) {\n outR |= (r >>> i) & 0x3f;\n outR <<= 6;\n }\n outR |= ((r & 0x1f) << 1) | (r >>> 31);\n\n out[off + 0] = outL >>> 0;\n out[off + 1] = outR >>> 0;\n};\n\nvar sTable = [\n 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,\n 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,\n 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,\n 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,\n\n 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,\n 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,\n 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,\n 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,\n\n 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,\n 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,\n 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,\n 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,\n\n 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,\n 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,\n 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,\n 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,\n\n 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,\n 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,\n 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,\n 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,\n\n 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,\n 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,\n 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,\n 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,\n\n 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,\n 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,\n 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,\n 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,\n\n 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,\n 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,\n 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,\n 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11\n];\n\nexports.substitute = function substitute(inL, inR) {\n var out = 0;\n for (var i = 0; i < 4; i++) {\n var b = (inL >>> (18 - i * 6)) & 0x3f;\n var sb = sTable[i * 0x40 + b];\n\n out <<= 4;\n out |= sb;\n }\n for (var i = 0; i < 4; i++) {\n var b = (inR >>> (18 - i * 6)) & 0x3f;\n var sb = sTable[4 * 0x40 + i * 0x40 + b];\n\n out <<= 4;\n out |= sb;\n }\n return out >>> 0;\n};\n\nvar permuteTable = [\n 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,\n 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7\n];\n\nexports.permute = function permute(num) {\n var out = 0;\n for (var i = 0; i < permuteTable.length; i++) {\n out <<= 1;\n out |= (num >>> permuteTable[i]) & 0x1;\n }\n return out >>> 0;\n};\n\nexports.padSplit = function padSplit(num, size, group) {\n var str = num.toString(2);\n while (str.length < size)\n str = '0' + str;\n\n var out = [];\n for (var i = 0; i < size; i += group)\n out.push(str.slice(i, i + group));\n return out.join(' ');\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/des.js/lib/des/utils.js?"); + +/***/ }), + +/***/ "./node_modules/diffie-hellman/browser.js": +/*!************************************************!*\ + !*** ./node_modules/diffie-hellman/browser.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\nvar generatePrime = __webpack_require__(/*! ./lib/generatePrime */ \"./node_modules/diffie-hellman/lib/generatePrime.js\")\nvar primes = __webpack_require__(/*! ./lib/primes.json */ \"./node_modules/diffie-hellman/lib/primes.json\")\n\nvar DH = __webpack_require__(/*! ./lib/dh */ \"./node_modules/diffie-hellman/lib/dh.js\")\n\nfunction getDiffieHellman (mod) {\n var prime = new Buffer(primes[mod].prime, 'hex')\n var gen = new Buffer(primes[mod].gen, 'hex')\n\n return new DH(prime, gen)\n}\n\nvar ENCODINGS = {\n 'binary': true, 'hex': true, 'base64': true\n}\n\nfunction createDiffieHellman (prime, enc, generator, genc) {\n if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {\n return createDiffieHellman(prime, 'binary', enc, generator)\n }\n\n enc = enc || 'binary'\n genc = genc || 'binary'\n generator = generator || new Buffer([2])\n\n if (!Buffer.isBuffer(generator)) {\n generator = new Buffer(generator, genc)\n }\n\n if (typeof prime === 'number') {\n return new DH(generatePrime(prime, generator), generator, true)\n }\n\n if (!Buffer.isBuffer(prime)) {\n prime = new Buffer(prime, enc)\n }\n\n return new DH(prime, generator, true)\n}\n\nexports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman\nexports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/diffie-hellman/browser.js?"); + +/***/ }), + +/***/ "./node_modules/diffie-hellman/lib/dh.js": +/*!***********************************************!*\ + !*** ./node_modules/diffie-hellman/lib/dh.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js\");\nvar MillerRabin = __webpack_require__(/*! miller-rabin */ \"./node_modules/miller-rabin/lib/mr.js\");\nvar millerRabin = new MillerRabin();\nvar TWENTYFOUR = new BN(24);\nvar ELEVEN = new BN(11);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar primes = __webpack_require__(/*! ./generatePrime */ \"./node_modules/diffie-hellman/lib/generatePrime.js\");\nvar randomBytes = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\");\nmodule.exports = DH;\n\nfunction setPublicKey(pub, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(pub)) {\n pub = new Buffer(pub, enc);\n }\n this._pub = new BN(pub);\n return this;\n}\n\nfunction setPrivateKey(priv, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(priv)) {\n priv = new Buffer(priv, enc);\n }\n this._priv = new BN(priv);\n return this;\n}\n\nvar primeCache = {};\nfunction checkPrime(prime, generator) {\n var gen = generator.toString('hex');\n var hex = [gen, prime.toString(16)].join('_');\n if (hex in primeCache) {\n return primeCache[hex];\n }\n var error = 0;\n\n if (prime.isEven() ||\n !primes.simpleSieve ||\n !primes.fermatTest(prime) ||\n !millerRabin.test(prime)) {\n //not a prime so +1\n error += 1;\n\n if (gen === '02' || gen === '05') {\n // we'd be able to check the generator\n // it would fail so +8\n error += 8;\n } else {\n //we wouldn't be able to test the generator\n // so +4\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n }\n if (!millerRabin.test(prime.shrn(1))) {\n //not a safe prime\n error += 2;\n }\n var rem;\n switch (gen) {\n case '02':\n if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {\n // unsuidable generator\n error += 8;\n }\n break;\n case '05':\n rem = prime.mod(TEN);\n if (rem.cmp(THREE) && rem.cmp(SEVEN)) {\n // prime mod 10 needs to equal 3 or 7\n error += 8;\n }\n break;\n default:\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n}\n\nfunction DH(prime, generator, malleable) {\n this.setGenerator(generator);\n this.__prime = new BN(prime);\n this._prime = BN.mont(this.__prime);\n this._primeLen = prime.length;\n this._pub = undefined;\n this._priv = undefined;\n this._primeCode = undefined;\n if (malleable) {\n this.setPublicKey = setPublicKey;\n this.setPrivateKey = setPrivateKey;\n } else {\n this._primeCode = 8;\n }\n}\nObject.defineProperty(DH.prototype, 'verifyError', {\n enumerable: true,\n get: function () {\n if (typeof this._primeCode !== 'number') {\n this._primeCode = checkPrime(this.__prime, this.__gen);\n }\n return this._primeCode;\n }\n});\nDH.prototype.generateKeys = function () {\n if (!this._priv) {\n this._priv = new BN(randomBytes(this._primeLen));\n }\n this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();\n return this.getPublicKey();\n};\n\nDH.prototype.computeSecret = function (other) {\n other = new BN(other);\n other = other.toRed(this._prime);\n var secret = other.redPow(this._priv).fromRed();\n var out = new Buffer(secret.toArray());\n var prime = this.getPrime();\n if (out.length < prime.length) {\n var front = new Buffer(prime.length - out.length);\n front.fill(0);\n out = Buffer.concat([front, out]);\n }\n return out;\n};\n\nDH.prototype.getPublicKey = function getPublicKey(enc) {\n return formatReturnValue(this._pub, enc);\n};\n\nDH.prototype.getPrivateKey = function getPrivateKey(enc) {\n return formatReturnValue(this._priv, enc);\n};\n\nDH.prototype.getPrime = function (enc) {\n return formatReturnValue(this.__prime, enc);\n};\n\nDH.prototype.getGenerator = function (enc) {\n return formatReturnValue(this._gen, enc);\n};\n\nDH.prototype.setGenerator = function (gen, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(gen)) {\n gen = new Buffer(gen, enc);\n }\n this.__gen = gen;\n this._gen = new BN(gen);\n return this;\n};\n\nfunction formatReturnValue(bn, enc) {\n var buf = new Buffer(bn.toArray());\n if (!enc) {\n return buf;\n } else {\n return buf.toString(enc);\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/diffie-hellman/lib/dh.js?"); + +/***/ }), + +/***/ "./node_modules/diffie-hellman/lib/generatePrime.js": +/*!**********************************************************!*\ + !*** ./node_modules/diffie-hellman/lib/generatePrime.js ***! + \**********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var randomBytes = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\");\nmodule.exports = findPrime;\nfindPrime.simpleSieve = simpleSieve;\nfindPrime.fermatTest = fermatTest;\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js\");\nvar TWENTYFOUR = new BN(24);\nvar MillerRabin = __webpack_require__(/*! miller-rabin */ \"./node_modules/miller-rabin/lib/mr.js\");\nvar millerRabin = new MillerRabin();\nvar ONE = new BN(1);\nvar TWO = new BN(2);\nvar FIVE = new BN(5);\nvar SIXTEEN = new BN(16);\nvar EIGHT = new BN(8);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar ELEVEN = new BN(11);\nvar FOUR = new BN(4);\nvar TWELVE = new BN(12);\nvar primes = null;\n\nfunction _getPrimes() {\n if (primes !== null)\n return primes;\n\n var limit = 0x100000;\n var res = [];\n res[0] = 2;\n for (var i = 1, k = 3; k < limit; k += 2) {\n var sqrt = Math.ceil(Math.sqrt(k));\n for (var j = 0; j < i && res[j] <= sqrt; j++)\n if (k % res[j] === 0)\n break;\n\n if (i !== j && res[j] <= sqrt)\n continue;\n\n res[i++] = k;\n }\n primes = res;\n return res;\n}\n\nfunction simpleSieve(p) {\n var primes = _getPrimes();\n\n for (var i = 0; i < primes.length; i++)\n if (p.modn(primes[i]) === 0) {\n if (p.cmpn(primes[i]) === 0) {\n return true;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nfunction fermatTest(p) {\n var red = BN.mont(p);\n return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;\n}\n\nfunction findPrime(bits, gen) {\n if (bits < 16) {\n // this is what openssl does\n if (gen === 2 || gen === 5) {\n return new BN([0x8c, 0x7b]);\n } else {\n return new BN([0x8c, 0x27]);\n }\n }\n gen = new BN(gen);\n\n var num, n2;\n\n while (true) {\n num = new BN(randomBytes(Math.ceil(bits / 8)));\n while (num.bitLength() > bits) {\n num.ishrn(1);\n }\n if (num.isEven()) {\n num.iadd(ONE);\n }\n if (!num.testn(1)) {\n num.iadd(TWO);\n }\n if (!gen.cmp(TWO)) {\n while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {\n num.iadd(FOUR);\n }\n } else if (!gen.cmp(FIVE)) {\n while (num.mod(TEN).cmp(THREE)) {\n num.iadd(FOUR);\n }\n }\n n2 = num.shrn(1);\n if (simpleSieve(n2) && simpleSieve(num) &&\n fermatTest(n2) && fermatTest(num) &&\n millerRabin.test(n2) && millerRabin.test(num)) {\n return num;\n }\n }\n\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/diffie-hellman/lib/generatePrime.js?"); + +/***/ }), + +/***/ "./node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js": +/*!******************************************************************!*\ + !*** ./node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js ***! + \******************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?e7e4\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/diffie-hellman/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic.js": +/*!***********************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic.js ***! + \***********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar elliptic = exports;\n\nelliptic.version = (__webpack_require__(/*! ../package.json */ \"./node_modules/elliptic/package.json\").version);\nelliptic.utils = __webpack_require__(/*! ./elliptic/utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nelliptic.rand = __webpack_require__(/*! brorand */ \"./node_modules/brorand/index.js\");\nelliptic.curve = __webpack_require__(/*! ./elliptic/curve */ \"./node_modules/elliptic/lib/elliptic/curve/index.js\");\nelliptic.curves = __webpack_require__(/*! ./elliptic/curves */ \"./node_modules/elliptic/lib/elliptic/curves.js\");\n\n// Protocols\nelliptic.ec = __webpack_require__(/*! ./elliptic/ec */ \"./node_modules/elliptic/lib/elliptic/ec/index.js\");\nelliptic.eddsa = __webpack_require__(/*! ./elliptic/eddsa */ \"./node_modules/elliptic/lib/elliptic/eddsa/index.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curve/base.js": +/*!**********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curve/base.js ***! + \**********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar getNAF = utils.getNAF;\nvar getJSF = utils.getJSF;\nvar assert = utils.assert;\n\nfunction BaseCurve(type, conf) {\n this.type = type;\n this.p = new BN(conf.p, 16);\n\n // Use Montgomery, when there is no fast reduction for the prime\n this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);\n\n // Useful for many curves\n this.zero = new BN(0).toRed(this.red);\n this.one = new BN(1).toRed(this.red);\n this.two = new BN(2).toRed(this.red);\n\n // Curve configuration, optional\n this.n = conf.n && new BN(conf.n, 16);\n this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);\n\n // Temporary arrays\n this._wnafT1 = new Array(4);\n this._wnafT2 = new Array(4);\n this._wnafT3 = new Array(4);\n this._wnafT4 = new Array(4);\n\n this._bitLength = this.n ? this.n.bitLength() : 0;\n\n // Generalized Greg Maxwell's trick\n var adjustCount = this.n && this.p.div(this.n);\n if (!adjustCount || adjustCount.cmpn(100) > 0) {\n this.redN = null;\n } else {\n this._maxwellTrick = true;\n this.redN = this.n.toRed(this.red);\n }\n}\nmodule.exports = BaseCurve;\n\nBaseCurve.prototype.point = function point() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype.validate = function validate() {\n throw new Error('Not implemented');\n};\n\nBaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {\n assert(p.precomputed);\n var doubles = p._getDoubles();\n\n var naf = getNAF(k, 1, this._bitLength);\n var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);\n I /= 3;\n\n // Translate into more windowed form\n var repr = [];\n var j;\n var nafW;\n for (j = 0; j < naf.length; j += doubles.step) {\n nafW = 0;\n for (var l = j + doubles.step - 1; l >= j; l--)\n nafW = (nafW << 1) + naf[l];\n repr.push(nafW);\n }\n\n var a = this.jpoint(null, null, null);\n var b = this.jpoint(null, null, null);\n for (var i = I; i > 0; i--) {\n for (j = 0; j < repr.length; j++) {\n nafW = repr[j];\n if (nafW === i)\n b = b.mixedAdd(doubles.points[j]);\n else if (nafW === -i)\n b = b.mixedAdd(doubles.points[j].neg());\n }\n a = a.add(b);\n }\n return a.toP();\n};\n\nBaseCurve.prototype._wnafMul = function _wnafMul(p, k) {\n var w = 4;\n\n // Precompute window\n var nafPoints = p._getNAFPoints(w);\n w = nafPoints.wnd;\n var wnd = nafPoints.points;\n\n // Get NAF form\n var naf = getNAF(k, w, this._bitLength);\n\n // Add `this`*(N+1) for every w-NAF index\n var acc = this.jpoint(null, null, null);\n for (var i = naf.length - 1; i >= 0; i--) {\n // Count zeroes\n for (var l = 0; i >= 0 && naf[i] === 0; i--)\n l++;\n if (i >= 0)\n l++;\n acc = acc.dblp(l);\n\n if (i < 0)\n break;\n var z = naf[i];\n assert(z !== 0);\n if (p.type === 'affine') {\n // J +- P\n if (z > 0)\n acc = acc.mixedAdd(wnd[(z - 1) >> 1]);\n else\n acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());\n } else {\n // J +- J\n if (z > 0)\n acc = acc.add(wnd[(z - 1) >> 1]);\n else\n acc = acc.add(wnd[(-z - 1) >> 1].neg());\n }\n }\n return p.type === 'affine' ? acc.toP() : acc;\n};\n\nBaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,\n points,\n coeffs,\n len,\n jacobianResult) {\n var wndWidth = this._wnafT1;\n var wnd = this._wnafT2;\n var naf = this._wnafT3;\n\n // Fill all arrays\n var max = 0;\n var i;\n var j;\n var p;\n for (i = 0; i < len; i++) {\n p = points[i];\n var nafPoints = p._getNAFPoints(defW);\n wndWidth[i] = nafPoints.wnd;\n wnd[i] = nafPoints.points;\n }\n\n // Comb small window NAFs\n for (i = len - 1; i >= 1; i -= 2) {\n var a = i - 1;\n var b = i;\n if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {\n naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);\n naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);\n max = Math.max(naf[a].length, max);\n max = Math.max(naf[b].length, max);\n continue;\n }\n\n var comb = [\n points[a], /* 1 */\n null, /* 3 */\n null, /* 5 */\n points[b], /* 7 */\n ];\n\n // Try to avoid Projective points, if possible\n if (points[a].y.cmp(points[b].y) === 0) {\n comb[1] = points[a].add(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].add(points[b].neg());\n } else {\n comb[1] = points[a].toJ().mixedAdd(points[b]);\n comb[2] = points[a].toJ().mixedAdd(points[b].neg());\n }\n\n var index = [\n -3, /* -1 -1 */\n -1, /* -1 0 */\n -5, /* -1 1 */\n -7, /* 0 -1 */\n 0, /* 0 0 */\n 7, /* 0 1 */\n 5, /* 1 -1 */\n 1, /* 1 0 */\n 3, /* 1 1 */\n ];\n\n var jsf = getJSF(coeffs[a], coeffs[b]);\n max = Math.max(jsf[0].length, max);\n naf[a] = new Array(max);\n naf[b] = new Array(max);\n for (j = 0; j < max; j++) {\n var ja = jsf[0][j] | 0;\n var jb = jsf[1][j] | 0;\n\n naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];\n naf[b][j] = 0;\n wnd[a] = comb;\n }\n }\n\n var acc = this.jpoint(null, null, null);\n var tmp = this._wnafT4;\n for (i = max; i >= 0; i--) {\n var k = 0;\n\n while (i >= 0) {\n var zero = true;\n for (j = 0; j < len; j++) {\n tmp[j] = naf[j][i] | 0;\n if (tmp[j] !== 0)\n zero = false;\n }\n if (!zero)\n break;\n k++;\n i--;\n }\n if (i >= 0)\n k++;\n acc = acc.dblp(k);\n if (i < 0)\n break;\n\n for (j = 0; j < len; j++) {\n var z = tmp[j];\n p;\n if (z === 0)\n continue;\n else if (z > 0)\n p = wnd[j][(z - 1) >> 1];\n else if (z < 0)\n p = wnd[j][(-z - 1) >> 1].neg();\n\n if (p.type === 'affine')\n acc = acc.mixedAdd(p);\n else\n acc = acc.add(p);\n }\n }\n // Zeroify references\n for (i = 0; i < len; i++)\n wnd[i] = null;\n\n if (jacobianResult)\n return acc;\n else\n return acc.toP();\n};\n\nfunction BasePoint(curve, type) {\n this.curve = curve;\n this.type = type;\n this.precomputed = null;\n}\nBaseCurve.BasePoint = BasePoint;\n\nBasePoint.prototype.eq = function eq(/*other*/) {\n throw new Error('Not implemented');\n};\n\nBasePoint.prototype.validate = function validate() {\n return this.curve.validate(this);\n};\n\nBaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n bytes = utils.toArray(bytes, enc);\n\n var len = this.p.byteLength();\n\n // uncompressed, hybrid-odd, hybrid-even\n if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&\n bytes.length - 1 === 2 * len) {\n if (bytes[0] === 0x06)\n assert(bytes[bytes.length - 1] % 2 === 0);\n else if (bytes[0] === 0x07)\n assert(bytes[bytes.length - 1] % 2 === 1);\n\n var res = this.point(bytes.slice(1, 1 + len),\n bytes.slice(1 + len, 1 + 2 * len));\n\n return res;\n } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&\n bytes.length - 1 === len) {\n return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);\n }\n throw new Error('Unknown point format');\n};\n\nBasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {\n return this.encode(enc, true);\n};\n\nBasePoint.prototype._encode = function _encode(compact) {\n var len = this.curve.p.byteLength();\n var x = this.getX().toArray('be', len);\n\n if (compact)\n return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);\n\n return [ 0x04 ].concat(x, this.getY().toArray('be', len));\n};\n\nBasePoint.prototype.encode = function encode(enc, compact) {\n return utils.encode(this._encode(compact), enc);\n};\n\nBasePoint.prototype.precompute = function precompute(power) {\n if (this.precomputed)\n return this;\n\n var precomputed = {\n doubles: null,\n naf: null,\n beta: null,\n };\n precomputed.naf = this._getNAFPoints(8);\n precomputed.doubles = this._getDoubles(4, power);\n precomputed.beta = this._getBeta();\n this.precomputed = precomputed;\n\n return this;\n};\n\nBasePoint.prototype._hasDoubles = function _hasDoubles(k) {\n if (!this.precomputed)\n return false;\n\n var doubles = this.precomputed.doubles;\n if (!doubles)\n return false;\n\n return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);\n};\n\nBasePoint.prototype._getDoubles = function _getDoubles(step, power) {\n if (this.precomputed && this.precomputed.doubles)\n return this.precomputed.doubles;\n\n var doubles = [ this ];\n var acc = this;\n for (var i = 0; i < power; i += step) {\n for (var j = 0; j < step; j++)\n acc = acc.dbl();\n doubles.push(acc);\n }\n return {\n step: step,\n points: doubles,\n };\n};\n\nBasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {\n if (this.precomputed && this.precomputed.naf)\n return this.precomputed.naf;\n\n var res = [ this ];\n var max = (1 << wnd) - 1;\n var dbl = max === 1 ? null : this.dbl();\n for (var i = 1; i < max; i++)\n res[i] = res[i - 1].add(dbl);\n return {\n wnd: wnd,\n points: res,\n };\n};\n\nBasePoint.prototype._getBeta = function _getBeta() {\n return null;\n};\n\nBasePoint.prototype.dblp = function dblp(k) {\n var r = this;\n for (var i = 0; i < k; i++)\n r = r.dbl();\n return r;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curve/base.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curve/edwards.js": +/*!*************************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curve/edwards.js ***! + \*************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar assert = utils.assert;\n\nfunction EdwardsCurve(conf) {\n // NOTE: Important as we are creating point in Base.call()\n this.twisted = (conf.a | 0) !== 1;\n this.mOneA = this.twisted && (conf.a | 0) === -1;\n this.extended = this.mOneA;\n\n Base.call(this, 'edwards', conf);\n\n this.a = new BN(conf.a, 16).umod(this.red.m);\n this.a = this.a.toRed(this.red);\n this.c = new BN(conf.c, 16).toRed(this.red);\n this.c2 = this.c.redSqr();\n this.d = new BN(conf.d, 16).toRed(this.red);\n this.dd = this.d.redAdd(this.d);\n\n assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);\n this.oneC = (conf.c | 0) === 1;\n}\ninherits(EdwardsCurve, Base);\nmodule.exports = EdwardsCurve;\n\nEdwardsCurve.prototype._mulA = function _mulA(num) {\n if (this.mOneA)\n return num.redNeg();\n else\n return this.a.redMul(num);\n};\n\nEdwardsCurve.prototype._mulC = function _mulC(num) {\n if (this.oneC)\n return num;\n else\n return this.c.redMul(num);\n};\n\n// Just for compatibility with Short curve\nEdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {\n return this.point(x, y, z, t);\n};\n\nEdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var x2 = x.redSqr();\n var rhs = this.c2.redSub(this.a.redMul(x2));\n var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));\n\n var y2 = rhs.redMul(lhs.redInvm());\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {\n y = new BN(y, 16);\n if (!y.red)\n y = y.toRed(this.red);\n\n // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)\n var y2 = y.redSqr();\n var lhs = y2.redSub(this.c2);\n var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);\n var x2 = lhs.redMul(rhs.redInvm());\n\n if (x2.cmp(this.zero) === 0) {\n if (odd)\n throw new Error('invalid point');\n else\n return this.point(this.zero, y);\n }\n\n var x = x2.redSqrt();\n if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n if (x.fromRed().isOdd() !== odd)\n x = x.redNeg();\n\n return this.point(x, y);\n};\n\nEdwardsCurve.prototype.validate = function validate(point) {\n if (point.isInfinity())\n return true;\n\n // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)\n point.normalize();\n\n var x2 = point.x.redSqr();\n var y2 = point.y.redSqr();\n var lhs = x2.redMul(this.a).redAdd(y2);\n var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));\n\n return lhs.cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, y, z, t) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && y === null && z === null) {\n this.x = this.curve.zero;\n this.y = this.curve.one;\n this.z = this.curve.one;\n this.t = this.curve.zero;\n this.zOne = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = z ? new BN(z, 16) : this.curve.one;\n this.t = t && new BN(t, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n if (this.t && !this.t.red)\n this.t = this.t.toRed(this.curve.red);\n this.zOne = this.z === this.curve.one;\n\n // Use extended coordinates\n if (this.curve.extended && !this.t) {\n this.t = this.x.redMul(this.y);\n if (!this.zOne)\n this.t = this.t.redMul(this.z.redInvm());\n }\n }\n}\ninherits(Point, Base.BasePoint);\n\nEdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nEdwardsCurve.prototype.point = function point(x, y, z, t) {\n return new Point(this, x, y, z, t);\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1], obj[2]);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.x.cmpn(0) === 0 &&\n (this.y.cmp(this.z) === 0 ||\n (this.zOne && this.y.cmp(this.curve.c) === 0));\n};\n\nPoint.prototype._extDbl = function _extDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #doubling-dbl-2008-hwcd\n // 4M + 4S\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = 2 * Z1^2\n var c = this.z.redSqr();\n c = c.redIAdd(c);\n // D = a * A\n var d = this.curve._mulA(a);\n // E = (X1 + Y1)^2 - A - B\n var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);\n // G = D + B\n var g = d.redAdd(b);\n // F = G - C\n var f = g.redSub(c);\n // H = D - B\n var h = d.redSub(b);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projDbl = function _projDbl() {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #doubling-dbl-2008-bbjlp\n // #doubling-dbl-2007-bl\n // and others\n // Generally 3M + 4S or 2M + 4S\n\n // B = (X1 + Y1)^2\n var b = this.x.redAdd(this.y).redSqr();\n // C = X1^2\n var c = this.x.redSqr();\n // D = Y1^2\n var d = this.y.redSqr();\n\n var nx;\n var ny;\n var nz;\n var e;\n var h;\n var j;\n if (this.curve.twisted) {\n // E = a * C\n e = this.curve._mulA(c);\n // F = E + D\n var f = e.redAdd(d);\n if (this.zOne) {\n // X3 = (B - C - D) * (F - 2)\n nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F^2 - 2 * F\n nz = f.redSqr().redSub(f).redSub(f);\n } else {\n // H = Z1^2\n h = this.z.redSqr();\n // J = F - 2 * H\n j = f.redSub(h).redISub(h);\n // X3 = (B-C-D)*J\n nx = b.redSub(c).redISub(d).redMul(j);\n // Y3 = F * (E - D)\n ny = f.redMul(e.redSub(d));\n // Z3 = F * J\n nz = f.redMul(j);\n }\n } else {\n // E = C + D\n e = c.redAdd(d);\n // H = (c * Z1)^2\n h = this.curve._mulC(this.z).redSqr();\n // J = E - 2 * H\n j = e.redSub(h).redSub(h);\n // X3 = c * (B - E) * J\n nx = this.curve._mulC(b.redISub(e)).redMul(j);\n // Y3 = c * E * (C - D)\n ny = this.curve._mulC(e).redMul(c.redISub(d));\n // Z3 = E * J\n nz = e.redMul(j);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n // Double in extended coordinates\n if (this.curve.extended)\n return this._extDbl();\n else\n return this._projDbl();\n};\n\nPoint.prototype._extAdd = function _extAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html\n // #addition-add-2008-hwcd-3\n // 8M\n\n // A = (Y1 - X1) * (Y2 - X2)\n var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));\n // B = (Y1 + X1) * (Y2 + X2)\n var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));\n // C = T1 * k * T2\n var c = this.t.redMul(this.curve.dd).redMul(p.t);\n // D = Z1 * 2 * Z2\n var d = this.z.redMul(p.z.redAdd(p.z));\n // E = B - A\n var e = b.redSub(a);\n // F = D - C\n var f = d.redSub(c);\n // G = D + C\n var g = d.redAdd(c);\n // H = B + A\n var h = b.redAdd(a);\n // X3 = E * F\n var nx = e.redMul(f);\n // Y3 = G * H\n var ny = g.redMul(h);\n // T3 = E * H\n var nt = e.redMul(h);\n // Z3 = F * G\n var nz = f.redMul(g);\n return this.curve.point(nx, ny, nz, nt);\n};\n\nPoint.prototype._projAdd = function _projAdd(p) {\n // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html\n // #addition-add-2008-bbjlp\n // #addition-add-2007-bl\n // 10M + 1S\n\n // A = Z1 * Z2\n var a = this.z.redMul(p.z);\n // B = A^2\n var b = a.redSqr();\n // C = X1 * X2\n var c = this.x.redMul(p.x);\n // D = Y1 * Y2\n var d = this.y.redMul(p.y);\n // E = d * C * D\n var e = this.curve.d.redMul(c).redMul(d);\n // F = B - E\n var f = b.redSub(e);\n // G = B + E\n var g = b.redAdd(e);\n // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)\n var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);\n var nx = a.redMul(f).redMul(tmp);\n var ny;\n var nz;\n if (this.curve.twisted) {\n // Y3 = A * G * (D - a * C)\n ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));\n // Z3 = F * G\n nz = f.redMul(g);\n } else {\n // Y3 = A * G * (D - C)\n ny = a.redMul(g).redMul(d.redSub(c));\n // Z3 = c * F * G\n nz = this.curve._mulC(f).redMul(g);\n }\n return this.curve.point(nx, ny, nz);\n};\n\nPoint.prototype.add = function add(p) {\n if (this.isInfinity())\n return p;\n if (p.isInfinity())\n return this;\n\n if (this.curve.extended)\n return this._extAdd(p);\n else\n return this._projAdd(p);\n};\n\nPoint.prototype.mul = function mul(k) {\n if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p, k2) {\n return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);\n};\n\nPoint.prototype.normalize = function normalize() {\n if (this.zOne)\n return this;\n\n // Normalize coordinates\n var zi = this.z.redInvm();\n this.x = this.x.redMul(zi);\n this.y = this.y.redMul(zi);\n if (this.t)\n this.t = this.t.redMul(zi);\n this.z = this.curve.one;\n this.zOne = true;\n return this;\n};\n\nPoint.prototype.neg = function neg() {\n return this.curve.point(this.x.redNeg(),\n this.y,\n this.z,\n this.t && this.t.redNeg());\n};\n\nPoint.prototype.getX = function getX() {\n this.normalize();\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n this.normalize();\n return this.y.fromRed();\n};\n\nPoint.prototype.eq = function eq(other) {\n return this === other ||\n this.getX().cmp(other.getX()) === 0 &&\n this.getY().cmp(other.getY()) === 0;\n};\n\nPoint.prototype.eqXToP = function eqXToP(x) {\n var rx = x.toRed(this.curve.red).redMul(this.z);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(this.z);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\n// Compatibility with BaseCurve\nPoint.prototype.toP = Point.prototype.normalize;\nPoint.prototype.mixedAdd = Point.prototype.add;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curve/edwards.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curve/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curve/index.js ***! + \***********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar curve = exports;\n\ncurve.base = __webpack_require__(/*! ./base */ \"./node_modules/elliptic/lib/elliptic/curve/base.js\");\ncurve.short = __webpack_require__(/*! ./short */ \"./node_modules/elliptic/lib/elliptic/curve/short.js\");\ncurve.mont = __webpack_require__(/*! ./mont */ \"./node_modules/elliptic/lib/elliptic/curve/mont.js\");\ncurve.edwards = __webpack_require__(/*! ./edwards */ \"./node_modules/elliptic/lib/elliptic/curve/edwards.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curve/index.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curve/mont.js": +/*!**********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curve/mont.js ***! + \**********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\n\nfunction MontCurve(conf) {\n Base.call(this, 'mont', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.i4 = new BN(4).toRed(this.red).redInvm();\n this.two = new BN(2).toRed(this.red);\n this.a24 = this.i4.redMul(this.a.redAdd(this.two));\n}\ninherits(MontCurve, Base);\nmodule.exports = MontCurve;\n\nMontCurve.prototype.validate = function validate(point) {\n var x = point.normalize().x;\n var x2 = x.redSqr();\n var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);\n var y = rhs.redSqrt();\n\n return y.redSqr().cmp(rhs) === 0;\n};\n\nfunction Point(curve, x, z) {\n Base.BasePoint.call(this, curve, 'projective');\n if (x === null && z === null) {\n this.x = this.curve.one;\n this.z = this.curve.zero;\n } else {\n this.x = new BN(x, 16);\n this.z = new BN(z, 16);\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n }\n}\ninherits(Point, Base.BasePoint);\n\nMontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {\n return this.point(utils.toArray(bytes, enc), 1);\n};\n\nMontCurve.prototype.point = function point(x, z) {\n return new Point(this, x, z);\n};\n\nMontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {\n return Point.fromJSON(this, obj);\n};\n\nPoint.prototype.precompute = function precompute() {\n // No-op\n};\n\nPoint.prototype._encode = function _encode() {\n return this.getX().toArray('be', this.curve.p.byteLength());\n};\n\nPoint.fromJSON = function fromJSON(curve, obj) {\n return new Point(curve, obj[0], obj[1] || curve.one);\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\nPoint.prototype.dbl = function dbl() {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3\n // 2M + 2S + 4A\n\n // A = X1 + Z1\n var a = this.x.redAdd(this.z);\n // AA = A^2\n var aa = a.redSqr();\n // B = X1 - Z1\n var b = this.x.redSub(this.z);\n // BB = B^2\n var bb = b.redSqr();\n // C = AA - BB\n var c = aa.redSub(bb);\n // X3 = AA * BB\n var nx = aa.redMul(bb);\n // Z3 = C * (BB + A24 * C)\n var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.add = function add() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.diffAdd = function diffAdd(p, diff) {\n // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3\n // 4M + 2S + 6A\n\n // A = X2 + Z2\n var a = this.x.redAdd(this.z);\n // B = X2 - Z2\n var b = this.x.redSub(this.z);\n // C = X3 + Z3\n var c = p.x.redAdd(p.z);\n // D = X3 - Z3\n var d = p.x.redSub(p.z);\n // DA = D * A\n var da = d.redMul(a);\n // CB = C * B\n var cb = c.redMul(b);\n // X5 = Z1 * (DA + CB)^2\n var nx = diff.z.redMul(da.redAdd(cb).redSqr());\n // Z5 = X1 * (DA - CB)^2\n var nz = diff.x.redMul(da.redISub(cb).redSqr());\n return this.curve.point(nx, nz);\n};\n\nPoint.prototype.mul = function mul(k) {\n var t = k.clone();\n var a = this; // (N / 2) * Q + Q\n var b = this.curve.point(null, null); // (N / 2) * Q\n var c = this; // Q\n\n for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))\n bits.push(t.andln(1));\n\n for (var i = bits.length - 1; i >= 0; i--) {\n if (bits[i] === 0) {\n // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q\n a = a.diffAdd(b, c);\n // N * Q = 2 * ((N / 2) * Q + Q))\n b = b.dbl();\n } else {\n // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)\n b = a.diffAdd(b, c);\n // N * Q + Q = 2 * ((N / 2) * Q + Q)\n a = a.dbl();\n }\n }\n return b;\n};\n\nPoint.prototype.mulAdd = function mulAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.jumlAdd = function jumlAdd() {\n throw new Error('Not supported on Montgomery curve');\n};\n\nPoint.prototype.eq = function eq(other) {\n return this.getX().cmp(other.getX()) === 0;\n};\n\nPoint.prototype.normalize = function normalize() {\n this.x = this.x.redMul(this.z.redInvm());\n this.z = this.curve.one;\n return this;\n};\n\nPoint.prototype.getX = function getX() {\n // Normalize coordinates\n this.normalize();\n\n return this.x.fromRed();\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curve/mont.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curve/short.js": +/*!***********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curve/short.js ***! + \***********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\nvar Base = __webpack_require__(/*! ./base */ \"./node_modules/elliptic/lib/elliptic/curve/base.js\");\n\nvar assert = utils.assert;\n\nfunction ShortCurve(conf) {\n Base.call(this, 'short', conf);\n\n this.a = new BN(conf.a, 16).toRed(this.red);\n this.b = new BN(conf.b, 16).toRed(this.red);\n this.tinv = this.two.redInvm();\n\n this.zeroA = this.a.fromRed().cmpn(0) === 0;\n this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;\n\n // If the curve is endomorphic, precalculate beta and lambda\n this.endo = this._getEndomorphism(conf);\n this._endoWnafT1 = new Array(4);\n this._endoWnafT2 = new Array(4);\n}\ninherits(ShortCurve, Base);\nmodule.exports = ShortCurve;\n\nShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {\n // No efficient endomorphism\n if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)\n return;\n\n // Compute beta and lambda, that lambda * P = (beta * Px; Py)\n var beta;\n var lambda;\n if (conf.beta) {\n beta = new BN(conf.beta, 16).toRed(this.red);\n } else {\n var betas = this._getEndoRoots(this.p);\n // Choose the smallest beta\n beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];\n beta = beta.toRed(this.red);\n }\n if (conf.lambda) {\n lambda = new BN(conf.lambda, 16);\n } else {\n // Choose the lambda that is matching selected beta\n var lambdas = this._getEndoRoots(this.n);\n if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {\n lambda = lambdas[0];\n } else {\n lambda = lambdas[1];\n assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);\n }\n }\n\n // Get basis vectors, used for balanced length-two representation\n var basis;\n if (conf.basis) {\n basis = conf.basis.map(function(vec) {\n return {\n a: new BN(vec.a, 16),\n b: new BN(vec.b, 16),\n };\n });\n } else {\n basis = this._getEndoBasis(lambda);\n }\n\n return {\n beta: beta,\n lambda: lambda,\n basis: basis,\n };\n};\n\nShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {\n // Find roots of for x^2 + x + 1 in F\n // Root = (-1 +- Sqrt(-3)) / 2\n //\n var red = num === this.p ? this.red : BN.mont(num);\n var tinv = new BN(2).toRed(red).redInvm();\n var ntinv = tinv.redNeg();\n\n var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);\n\n var l1 = ntinv.redAdd(s).fromRed();\n var l2 = ntinv.redSub(s).fromRed();\n return [ l1, l2 ];\n};\n\nShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {\n // aprxSqrt >= sqrt(this.n)\n var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));\n\n // 3.74\n // Run EGCD, until r(L + 1) < aprxSqrt\n var u = lambda;\n var v = this.n.clone();\n var x1 = new BN(1);\n var y1 = new BN(0);\n var x2 = new BN(0);\n var y2 = new BN(1);\n\n // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)\n var a0;\n var b0;\n // First vector\n var a1;\n var b1;\n // Second vector\n var a2;\n var b2;\n\n var prevR;\n var i = 0;\n var r;\n var x;\n while (u.cmpn(0) !== 0) {\n var q = v.div(u);\n r = v.sub(q.mul(u));\n x = x2.sub(q.mul(x1));\n var y = y2.sub(q.mul(y1));\n\n if (!a1 && r.cmp(aprxSqrt) < 0) {\n a0 = prevR.neg();\n b0 = x1;\n a1 = r.neg();\n b1 = x;\n } else if (a1 && ++i === 2) {\n break;\n }\n prevR = r;\n\n v = u;\n u = r;\n x2 = x1;\n x1 = x;\n y2 = y1;\n y1 = y;\n }\n a2 = r.neg();\n b2 = x;\n\n var len1 = a1.sqr().add(b1.sqr());\n var len2 = a2.sqr().add(b2.sqr());\n if (len2.cmp(len1) >= 0) {\n a2 = a0;\n b2 = b0;\n }\n\n // Normalize signs\n if (a1.negative) {\n a1 = a1.neg();\n b1 = b1.neg();\n }\n if (a2.negative) {\n a2 = a2.neg();\n b2 = b2.neg();\n }\n\n return [\n { a: a1, b: b1 },\n { a: a2, b: b2 },\n ];\n};\n\nShortCurve.prototype._endoSplit = function _endoSplit(k) {\n var basis = this.endo.basis;\n var v1 = basis[0];\n var v2 = basis[1];\n\n var c1 = v2.b.mul(k).divRound(this.n);\n var c2 = v1.b.neg().mul(k).divRound(this.n);\n\n var p1 = c1.mul(v1.a);\n var p2 = c2.mul(v2.a);\n var q1 = c1.mul(v1.b);\n var q2 = c2.mul(v2.b);\n\n // Calculate answer\n var k1 = k.sub(p1).sub(p2);\n var k2 = q1.add(q2).neg();\n return { k1: k1, k2: k2 };\n};\n\nShortCurve.prototype.pointFromX = function pointFromX(x, odd) {\n x = new BN(x, 16);\n if (!x.red)\n x = x.toRed(this.red);\n\n var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);\n var y = y2.redSqrt();\n if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)\n throw new Error('invalid point');\n\n // XXX Is there any way to tell if the number is odd without converting it\n // to non-red form?\n var isOdd = y.fromRed().isOdd();\n if (odd && !isOdd || !odd && isOdd)\n y = y.redNeg();\n\n return this.point(x, y);\n};\n\nShortCurve.prototype.validate = function validate(point) {\n if (point.inf)\n return true;\n\n var x = point.x;\n var y = point.y;\n\n var ax = this.a.redMul(x);\n var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);\n return y.redSqr().redISub(rhs).cmpn(0) === 0;\n};\n\nShortCurve.prototype._endoWnafMulAdd =\n function _endoWnafMulAdd(points, coeffs, jacobianResult) {\n var npoints = this._endoWnafT1;\n var ncoeffs = this._endoWnafT2;\n for (var i = 0; i < points.length; i++) {\n var split = this._endoSplit(coeffs[i]);\n var p = points[i];\n var beta = p._getBeta();\n\n if (split.k1.negative) {\n split.k1.ineg();\n p = p.neg(true);\n }\n if (split.k2.negative) {\n split.k2.ineg();\n beta = beta.neg(true);\n }\n\n npoints[i * 2] = p;\n npoints[i * 2 + 1] = beta;\n ncoeffs[i * 2] = split.k1;\n ncoeffs[i * 2 + 1] = split.k2;\n }\n var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);\n\n // Clean-up references to points and coefficients\n for (var j = 0; j < i * 2; j++) {\n npoints[j] = null;\n ncoeffs[j] = null;\n }\n return res;\n };\n\nfunction Point(curve, x, y, isRed) {\n Base.BasePoint.call(this, curve, 'affine');\n if (x === null && y === null) {\n this.x = null;\n this.y = null;\n this.inf = true;\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n // Force redgomery representation when loading from JSON\n if (isRed) {\n this.x.forceRed(this.curve.red);\n this.y.forceRed(this.curve.red);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n this.inf = false;\n }\n}\ninherits(Point, Base.BasePoint);\n\nShortCurve.prototype.point = function point(x, y, isRed) {\n return new Point(this, x, y, isRed);\n};\n\nShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {\n return Point.fromJSON(this, obj, red);\n};\n\nPoint.prototype._getBeta = function _getBeta() {\n if (!this.curve.endo)\n return;\n\n var pre = this.precomputed;\n if (pre && pre.beta)\n return pre.beta;\n\n var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);\n if (pre) {\n var curve = this.curve;\n var endoMul = function(p) {\n return curve.point(p.x.redMul(curve.endo.beta), p.y);\n };\n pre.beta = beta;\n beta.precomputed = {\n beta: null,\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(endoMul),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(endoMul),\n },\n };\n }\n return beta;\n};\n\nPoint.prototype.toJSON = function toJSON() {\n if (!this.precomputed)\n return [ this.x, this.y ];\n\n return [ this.x, this.y, this.precomputed && {\n doubles: this.precomputed.doubles && {\n step: this.precomputed.doubles.step,\n points: this.precomputed.doubles.points.slice(1),\n },\n naf: this.precomputed.naf && {\n wnd: this.precomputed.naf.wnd,\n points: this.precomputed.naf.points.slice(1),\n },\n } ];\n};\n\nPoint.fromJSON = function fromJSON(curve, obj, red) {\n if (typeof obj === 'string')\n obj = JSON.parse(obj);\n var res = curve.point(obj[0], obj[1], red);\n if (!obj[2])\n return res;\n\n function obj2point(obj) {\n return curve.point(obj[0], obj[1], red);\n }\n\n var pre = obj[2];\n res.precomputed = {\n beta: null,\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: [ res ].concat(pre.doubles.points.map(obj2point)),\n },\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: [ res ].concat(pre.naf.points.map(obj2point)),\n },\n };\n return res;\n};\n\nPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nPoint.prototype.isInfinity = function isInfinity() {\n return this.inf;\n};\n\nPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.inf)\n return p;\n\n // P + O = P\n if (p.inf)\n return this;\n\n // P + P = 2P\n if (this.eq(p))\n return this.dbl();\n\n // P + (-P) = O\n if (this.neg().eq(p))\n return this.curve.point(null, null);\n\n // P + Q = O\n if (this.x.cmp(p.x) === 0)\n return this.curve.point(null, null);\n\n var c = this.y.redSub(p.y);\n if (c.cmpn(0) !== 0)\n c = c.redMul(this.x.redSub(p.x).redInvm());\n var nx = c.redSqr().redISub(this.x).redISub(p.x);\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.dbl = function dbl() {\n if (this.inf)\n return this;\n\n // 2P = O\n var ys1 = this.y.redAdd(this.y);\n if (ys1.cmpn(0) === 0)\n return this.curve.point(null, null);\n\n var a = this.curve.a;\n\n var x2 = this.x.redSqr();\n var dyinv = ys1.redInvm();\n var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);\n\n var nx = c.redSqr().redISub(this.x.redAdd(this.x));\n var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);\n return this.curve.point(nx, ny);\n};\n\nPoint.prototype.getX = function getX() {\n return this.x.fromRed();\n};\n\nPoint.prototype.getY = function getY() {\n return this.y.fromRed();\n};\n\nPoint.prototype.mul = function mul(k) {\n k = new BN(k, 16);\n if (this.isInfinity())\n return this;\n else if (this._hasDoubles(k))\n return this.curve._fixedNafMul(this, k);\n else if (this.curve.endo)\n return this.curve._endoWnafMulAdd([ this ], [ k ]);\n else\n return this.curve._wnafMul(this, k);\n};\n\nPoint.prototype.mulAdd = function mulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2);\n};\n\nPoint.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {\n var points = [ this, p2 ];\n var coeffs = [ k1, k2 ];\n if (this.curve.endo)\n return this.curve._endoWnafMulAdd(points, coeffs, true);\n else\n return this.curve._wnafMulAdd(1, points, coeffs, 2, true);\n};\n\nPoint.prototype.eq = function eq(p) {\n return this === p ||\n this.inf === p.inf &&\n (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);\n};\n\nPoint.prototype.neg = function neg(_precompute) {\n if (this.inf)\n return this;\n\n var res = this.curve.point(this.x, this.y.redNeg());\n if (_precompute && this.precomputed) {\n var pre = this.precomputed;\n var negate = function(p) {\n return p.neg();\n };\n res.precomputed = {\n naf: pre.naf && {\n wnd: pre.naf.wnd,\n points: pre.naf.points.map(negate),\n },\n doubles: pre.doubles && {\n step: pre.doubles.step,\n points: pre.doubles.points.map(negate),\n },\n };\n }\n return res;\n};\n\nPoint.prototype.toJ = function toJ() {\n if (this.inf)\n return this.curve.jpoint(null, null, null);\n\n var res = this.curve.jpoint(this.x, this.y, this.curve.one);\n return res;\n};\n\nfunction JPoint(curve, x, y, z) {\n Base.BasePoint.call(this, curve, 'jacobian');\n if (x === null && y === null && z === null) {\n this.x = this.curve.one;\n this.y = this.curve.one;\n this.z = new BN(0);\n } else {\n this.x = new BN(x, 16);\n this.y = new BN(y, 16);\n this.z = new BN(z, 16);\n }\n if (!this.x.red)\n this.x = this.x.toRed(this.curve.red);\n if (!this.y.red)\n this.y = this.y.toRed(this.curve.red);\n if (!this.z.red)\n this.z = this.z.toRed(this.curve.red);\n\n this.zOne = this.z === this.curve.one;\n}\ninherits(JPoint, Base.BasePoint);\n\nShortCurve.prototype.jpoint = function jpoint(x, y, z) {\n return new JPoint(this, x, y, z);\n};\n\nJPoint.prototype.toP = function toP() {\n if (this.isInfinity())\n return this.curve.point(null, null);\n\n var zinv = this.z.redInvm();\n var zinv2 = zinv.redSqr();\n var ax = this.x.redMul(zinv2);\n var ay = this.y.redMul(zinv2).redMul(zinv);\n\n return this.curve.point(ax, ay);\n};\n\nJPoint.prototype.neg = function neg() {\n return this.curve.jpoint(this.x, this.y.redNeg(), this.z);\n};\n\nJPoint.prototype.add = function add(p) {\n // O + P = P\n if (this.isInfinity())\n return p;\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 12M + 4S + 7A\n var pz2 = p.z.redSqr();\n var z2 = this.z.redSqr();\n var u1 = this.x.redMul(pz2);\n var u2 = p.x.redMul(z2);\n var s1 = this.y.redMul(pz2.redMul(p.z));\n var s2 = p.y.redMul(z2.redMul(this.z));\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(p.z).redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mixedAdd = function mixedAdd(p) {\n // O + P = P\n if (this.isInfinity())\n return p.toJ();\n\n // P + O = P\n if (p.isInfinity())\n return this;\n\n // 8M + 3S + 7A\n var z2 = this.z.redSqr();\n var u1 = this.x;\n var u2 = p.x.redMul(z2);\n var s1 = this.y;\n var s2 = p.y.redMul(z2).redMul(this.z);\n\n var h = u1.redSub(u2);\n var r = s1.redSub(s2);\n if (h.cmpn(0) === 0) {\n if (r.cmpn(0) !== 0)\n return this.curve.jpoint(null, null, null);\n else\n return this.dbl();\n }\n\n var h2 = h.redSqr();\n var h3 = h2.redMul(h);\n var v = u1.redMul(h2);\n\n var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);\n var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));\n var nz = this.z.redMul(h);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.dblp = function dblp(pow) {\n if (pow === 0)\n return this;\n if (this.isInfinity())\n return this;\n if (!pow)\n return this.dbl();\n\n var i;\n if (this.curve.zeroA || this.curve.threeA) {\n var r = this;\n for (i = 0; i < pow; i++)\n r = r.dbl();\n return r;\n }\n\n // 1M + 2S + 1A + N * (4S + 5M + 8A)\n // N = 1 => 6M + 6S + 9A\n var a = this.curve.a;\n var tinv = this.curve.tinv;\n\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n // Reuse results\n var jyd = jy.redAdd(jy);\n for (i = 0; i < pow; i++) {\n var jx2 = jx.redSqr();\n var jyd2 = jyd.redSqr();\n var jyd4 = jyd2.redSqr();\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var t1 = jx.redMul(jyd2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n var dny = c.redMul(t2);\n dny = dny.redIAdd(dny).redISub(jyd4);\n var nz = jyd.redMul(jz);\n if (i + 1 < pow)\n jz4 = jz4.redMul(jyd4);\n\n jx = nx;\n jz = nz;\n jyd = dny;\n }\n\n return this.curve.jpoint(jx, jyd.redMul(tinv), jz);\n};\n\nJPoint.prototype.dbl = function dbl() {\n if (this.isInfinity())\n return this;\n\n if (this.curve.zeroA)\n return this._zeroDbl();\n else if (this.curve.threeA)\n return this._threeDbl();\n else\n return this._dbl();\n};\n\nJPoint.prototype._zeroDbl = function _zeroDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 14A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // T = M ^ 2 - 2*S\n var t = m.redSqr().redISub(s).redISub(s);\n\n // 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2*Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html\n // #doubling-dbl-2009-l\n // 2M + 5S + 13A\n\n // A = X1^2\n var a = this.x.redSqr();\n // B = Y1^2\n var b = this.y.redSqr();\n // C = B^2\n var c = b.redSqr();\n // D = 2 * ((X1 + B)^2 - A - C)\n var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);\n d = d.redIAdd(d);\n // E = 3 * A\n var e = a.redAdd(a).redIAdd(a);\n // F = E^2\n var f = e.redSqr();\n\n // 8 * C\n var c8 = c.redIAdd(c);\n c8 = c8.redIAdd(c8);\n c8 = c8.redIAdd(c8);\n\n // X3 = F - 2 * D\n nx = f.redISub(d).redISub(d);\n // Y3 = E * (D - X3) - 8 * C\n ny = e.redMul(d.redISub(nx)).redISub(c8);\n // Z3 = 2 * Y1 * Z1\n nz = this.y.redMul(this.z);\n nz = nz.redIAdd(nz);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._threeDbl = function _threeDbl() {\n var nx;\n var ny;\n var nz;\n // Z = 1\n if (this.zOne) {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html\n // #doubling-mdbl-2007-bl\n // 1M + 5S + 15A\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // S = 2 * ((X1 + YY)^2 - XX - YYYY)\n var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n s = s.redIAdd(s);\n // M = 3 * XX + a\n var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);\n // T = M^2 - 2 * S\n var t = m.redSqr().redISub(s).redISub(s);\n // X3 = T\n nx = t;\n // Y3 = M * (S - T) - 8 * YYYY\n var yyyy8 = yyyy.redIAdd(yyyy);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n yyyy8 = yyyy8.redIAdd(yyyy8);\n ny = m.redMul(s.redISub(t)).redISub(yyyy8);\n // Z3 = 2 * Y1\n nz = this.y.redAdd(this.y);\n } else {\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b\n // 3M + 5S\n\n // delta = Z1^2\n var delta = this.z.redSqr();\n // gamma = Y1^2\n var gamma = this.y.redSqr();\n // beta = X1 * gamma\n var beta = this.x.redMul(gamma);\n // alpha = 3 * (X1 - delta) * (X1 + delta)\n var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));\n alpha = alpha.redAdd(alpha).redIAdd(alpha);\n // X3 = alpha^2 - 8 * beta\n var beta4 = beta.redIAdd(beta);\n beta4 = beta4.redIAdd(beta4);\n var beta8 = beta4.redAdd(beta4);\n nx = alpha.redSqr().redISub(beta8);\n // Z3 = (Y1 + Z1)^2 - gamma - delta\n nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);\n // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2\n var ggamma8 = gamma.redSqr();\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ggamma8 = ggamma8.redIAdd(ggamma8);\n ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);\n }\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype._dbl = function _dbl() {\n var a = this.curve.a;\n\n // 4M + 6S + 10A\n var jx = this.x;\n var jy = this.y;\n var jz = this.z;\n var jz4 = jz.redSqr().redSqr();\n\n var jx2 = jx.redSqr();\n var jy2 = jy.redSqr();\n\n var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));\n\n var jxd4 = jx.redAdd(jx);\n jxd4 = jxd4.redIAdd(jxd4);\n var t1 = jxd4.redMul(jy2);\n var nx = c.redSqr().redISub(t1.redAdd(t1));\n var t2 = t1.redISub(nx);\n\n var jyd8 = jy2.redSqr();\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n jyd8 = jyd8.redIAdd(jyd8);\n var ny = c.redMul(t2).redISub(jyd8);\n var nz = jy.redAdd(jy).redMul(jz);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.trpl = function trpl() {\n if (!this.curve.zeroA)\n return this.dbl().add(this);\n\n // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl\n // 5M + 10S + ...\n\n // XX = X1^2\n var xx = this.x.redSqr();\n // YY = Y1^2\n var yy = this.y.redSqr();\n // ZZ = Z1^2\n var zz = this.z.redSqr();\n // YYYY = YY^2\n var yyyy = yy.redSqr();\n // M = 3 * XX + a * ZZ2; a = 0\n var m = xx.redAdd(xx).redIAdd(xx);\n // MM = M^2\n var mm = m.redSqr();\n // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM\n var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);\n e = e.redIAdd(e);\n e = e.redAdd(e).redIAdd(e);\n e = e.redISub(mm);\n // EE = E^2\n var ee = e.redSqr();\n // T = 16*YYYY\n var t = yyyy.redIAdd(yyyy);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n t = t.redIAdd(t);\n // U = (M + E)^2 - MM - EE - T\n var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);\n // X3 = 4 * (X1 * EE - 4 * YY * U)\n var yyu4 = yy.redMul(u);\n yyu4 = yyu4.redIAdd(yyu4);\n yyu4 = yyu4.redIAdd(yyu4);\n var nx = this.x.redMul(ee).redISub(yyu4);\n nx = nx.redIAdd(nx);\n nx = nx.redIAdd(nx);\n // Y3 = 8 * Y1 * (U * (T - U) - E * EE)\n var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n ny = ny.redIAdd(ny);\n // Z3 = (Z1 + E)^2 - ZZ - EE\n var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);\n\n return this.curve.jpoint(nx, ny, nz);\n};\n\nJPoint.prototype.mul = function mul(k, kbase) {\n k = new BN(k, kbase);\n\n return this.curve._wnafMul(this, k);\n};\n\nJPoint.prototype.eq = function eq(p) {\n if (p.type === 'affine')\n return this.eq(p.toJ());\n\n if (this === p)\n return true;\n\n // x1 * z2^2 == x2 * z1^2\n var z2 = this.z.redSqr();\n var pz2 = p.z.redSqr();\n if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)\n return false;\n\n // y1 * z2^3 == y2 * z1^3\n var z3 = z2.redMul(this.z);\n var pz3 = pz2.redMul(p.z);\n return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;\n};\n\nJPoint.prototype.eqXToP = function eqXToP(x) {\n var zs = this.z.redSqr();\n var rx = x.toRed(this.curve.red).redMul(zs);\n if (this.x.cmp(rx) === 0)\n return true;\n\n var xc = x.clone();\n var t = this.curve.redN.redMul(zs);\n for (;;) {\n xc.iadd(this.curve.n);\n if (xc.cmp(this.curve.p) >= 0)\n return false;\n\n rx.redIAdd(t);\n if (this.x.cmp(rx) === 0)\n return true;\n }\n};\n\nJPoint.prototype.inspect = function inspect() {\n if (this.isInfinity())\n return '';\n return '';\n};\n\nJPoint.prototype.isInfinity = function isInfinity() {\n // XXX This code assumes that zero is always zero in red\n return this.z.cmpn(0) === 0;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curve/short.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/curves.js": +/*!******************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/curves.js ***! + \******************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar curves = exports;\n\nvar hash = __webpack_require__(/*! hash.js */ \"./node_modules/hash.js/lib/hash.js\");\nvar curve = __webpack_require__(/*! ./curve */ \"./node_modules/elliptic/lib/elliptic/curve/index.js\");\nvar utils = __webpack_require__(/*! ./utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\n\nvar assert = utils.assert;\n\nfunction PresetCurve(options) {\n if (options.type === 'short')\n this.curve = new curve.short(options);\n else if (options.type === 'edwards')\n this.curve = new curve.edwards(options);\n else\n this.curve = new curve.mont(options);\n this.g = this.curve.g;\n this.n = this.curve.n;\n this.hash = options.hash;\n\n assert(this.g.validate(), 'Invalid curve');\n assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');\n}\ncurves.PresetCurve = PresetCurve;\n\nfunction defineCurve(name, options) {\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n get: function() {\n var curve = new PresetCurve(options);\n Object.defineProperty(curves, name, {\n configurable: true,\n enumerable: true,\n value: curve,\n });\n return curve;\n },\n });\n}\n\ndefineCurve('p192', {\n type: 'short',\n prime: 'p192',\n p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',\n b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',\n n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',\n hash: hash.sha256,\n gRed: false,\n g: [\n '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',\n '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811',\n ],\n});\n\ndefineCurve('p224', {\n type: 'short',\n prime: 'p224',\n p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',\n a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',\n b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',\n n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',\n hash: hash.sha256,\n gRed: false,\n g: [\n 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',\n 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34',\n ],\n});\n\ndefineCurve('p256', {\n type: 'short',\n prime: null,\n p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',\n a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',\n b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',\n n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',\n hash: hash.sha256,\n gRed: false,\n g: [\n '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',\n '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5',\n ],\n});\n\ndefineCurve('p384', {\n type: 'short',\n prime: null,\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 ffffffff',\n a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'fffffffe ffffffff 00000000 00000000 fffffffc',\n b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +\n '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',\n n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +\n 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',\n hash: hash.sha384,\n gRed: false,\n g: [\n 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +\n '5502f25d bf55296c 3a545e38 72760ab7',\n '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +\n '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f',\n ],\n});\n\ndefineCurve('p521', {\n type: 'short',\n prime: null,\n p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff',\n a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff ffffffff ffffffff fffffffc',\n b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +\n '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +\n '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',\n n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +\n 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +\n 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',\n hash: hash.sha512,\n gRed: false,\n g: [\n '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +\n '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +\n 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',\n '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +\n '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +\n '3fad0761 353c7086 a272c240 88be9476 9fd16650',\n ],\n});\n\ndefineCurve('curve25519', {\n type: 'mont',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '76d06',\n b: '1',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '9',\n ],\n});\n\ndefineCurve('ed25519', {\n type: 'edwards',\n prime: 'p25519',\n p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',\n a: '-1',\n c: '1',\n // -121665 * (121666^(-1)) (mod P)\n d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',\n n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',\n hash: hash.sha256,\n gRed: false,\n g: [\n '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',\n\n // 4/5\n '6666666666666666666666666666666666666666666666666666666666666658',\n ],\n});\n\nvar pre;\ntry {\n pre = __webpack_require__(/*! ./precomputed/secp256k1 */ \"./node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js\");\n} catch (e) {\n pre = undefined;\n}\n\ndefineCurve('secp256k1', {\n type: 'short',\n prime: 'k256',\n p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',\n a: '0',\n b: '7',\n n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',\n h: '1',\n hash: hash.sha256,\n\n // Precomputed endomorphism\n beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',\n lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',\n basis: [\n {\n a: '3086d221a7d46bcde86c90e49284eb15',\n b: '-e4437ed6010e88286f547fa90abfe4c3',\n },\n {\n a: '114ca50f7a8e2f3f657c1108d9d44cfd8',\n b: '3086d221a7d46bcde86c90e49284eb15',\n },\n ],\n\n gRed: false,\n g: [\n '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',\n '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',\n pre,\n ],\n});\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/curves.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/ec/index.js": +/*!********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/ec/index.js ***! + \********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar HmacDRBG = __webpack_require__(/*! hmac-drbg */ \"./node_modules/hmac-drbg/lib/hmac-drbg.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar curves = __webpack_require__(/*! ../curves */ \"./node_modules/elliptic/lib/elliptic/curves.js\");\nvar rand = __webpack_require__(/*! brorand */ \"./node_modules/brorand/index.js\");\nvar assert = utils.assert;\n\nvar KeyPair = __webpack_require__(/*! ./key */ \"./node_modules/elliptic/lib/elliptic/ec/key.js\");\nvar Signature = __webpack_require__(/*! ./signature */ \"./node_modules/elliptic/lib/elliptic/ec/signature.js\");\n\nfunction EC(options) {\n if (!(this instanceof EC))\n return new EC(options);\n\n // Shortcut `elliptic.ec(curve-name)`\n if (typeof options === 'string') {\n assert(Object.prototype.hasOwnProperty.call(curves, options),\n 'Unknown curve ' + options);\n\n options = curves[options];\n }\n\n // Shortcut for `elliptic.ec(elliptic.curves.curveName)`\n if (options instanceof curves.PresetCurve)\n options = { curve: options };\n\n this.curve = options.curve.curve;\n this.n = this.curve.n;\n this.nh = this.n.ushrn(1);\n this.g = this.curve.g;\n\n // Point on curve\n this.g = options.curve.g;\n this.g.precompute(options.curve.n.bitLength() + 1);\n\n // Hash for function for DRBG\n this.hash = options.hash || options.curve.hash;\n}\nmodule.exports = EC;\n\nEC.prototype.keyPair = function keyPair(options) {\n return new KeyPair(this, options);\n};\n\nEC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {\n return KeyPair.fromPrivate(this, priv, enc);\n};\n\nEC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {\n return KeyPair.fromPublic(this, pub, enc);\n};\n\nEC.prototype.genKeyPair = function genKeyPair(options) {\n if (!options)\n options = {};\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n entropy: options.entropy || rand(this.hash.hmacStrength),\n entropyEnc: options.entropy && options.entropyEnc || 'utf8',\n nonce: this.n.toArray(),\n });\n\n var bytes = this.n.byteLength();\n var ns2 = this.n.sub(new BN(2));\n for (;;) {\n var priv = new BN(drbg.generate(bytes));\n if (priv.cmp(ns2) > 0)\n continue;\n\n priv.iaddn(1);\n return this.keyFromPrivate(priv);\n }\n};\n\nEC.prototype._truncateToN = function _truncateToN(msg, truncOnly) {\n var delta = msg.byteLength() * 8 - this.n.bitLength();\n if (delta > 0)\n msg = msg.ushrn(delta);\n if (!truncOnly && msg.cmp(this.n) >= 0)\n return msg.sub(this.n);\n else\n return msg;\n};\n\nEC.prototype.sign = function sign(msg, key, enc, options) {\n if (typeof enc === 'object') {\n options = enc;\n enc = null;\n }\n if (!options)\n options = {};\n\n key = this.keyFromPrivate(key, enc);\n msg = this._truncateToN(new BN(msg, 16));\n\n // Zero-extend key to provide enough entropy\n var bytes = this.n.byteLength();\n var bkey = key.getPrivate().toArray('be', bytes);\n\n // Zero-extend nonce to have the same byte size as N\n var nonce = msg.toArray('be', bytes);\n\n // Instantiate Hmac_DRBG\n var drbg = new HmacDRBG({\n hash: this.hash,\n entropy: bkey,\n nonce: nonce,\n pers: options.pers,\n persEnc: options.persEnc || 'utf8',\n });\n\n // Number of bytes to generate\n var ns1 = this.n.sub(new BN(1));\n\n for (var iter = 0; ; iter++) {\n var k = options.k ?\n options.k(iter) :\n new BN(drbg.generate(this.n.byteLength()));\n k = this._truncateToN(k, true);\n if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)\n continue;\n\n var kp = this.g.mul(k);\n if (kp.isInfinity())\n continue;\n\n var kpX = kp.getX();\n var r = kpX.umod(this.n);\n if (r.cmpn(0) === 0)\n continue;\n\n var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));\n s = s.umod(this.n);\n if (s.cmpn(0) === 0)\n continue;\n\n var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |\n (kpX.cmp(r) !== 0 ? 2 : 0);\n\n // Use complement of `s`, if it is > `n / 2`\n if (options.canonical && s.cmp(this.nh) > 0) {\n s = this.n.sub(s);\n recoveryParam ^= 1;\n }\n\n return new Signature({ r: r, s: s, recoveryParam: recoveryParam });\n }\n};\n\nEC.prototype.verify = function verify(msg, signature, key, enc) {\n msg = this._truncateToN(new BN(msg, 16));\n key = this.keyFromPublic(key, enc);\n signature = new Signature(signature, 'hex');\n\n // Perform primitive values validation\n var r = signature.r;\n var s = signature.s;\n if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)\n return false;\n if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)\n return false;\n\n // Validate signature\n var sinv = s.invm(this.n);\n var u1 = sinv.mul(msg).umod(this.n);\n var u2 = sinv.mul(r).umod(this.n);\n var p;\n\n if (!this.curve._maxwellTrick) {\n p = this.g.mulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n return p.getX().umod(this.n).cmp(r) === 0;\n }\n\n // NOTE: Greg Maxwell's trick, inspired by:\n // https://git.io/vad3K\n\n p = this.g.jmulAdd(u1, key.getPublic(), u2);\n if (p.isInfinity())\n return false;\n\n // Compare `p.x` of Jacobian point with `r`,\n // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the\n // inverse of `p.z^2`\n return p.eqXToP(r);\n};\n\nEC.prototype.recoverPubKey = function(msg, signature, j, enc) {\n assert((3 & j) === j, 'The recovery param is more than two bits');\n signature = new Signature(signature, enc);\n\n var n = this.n;\n var e = new BN(msg);\n var r = signature.r;\n var s = signature.s;\n\n // A set LSB signifies that the y-coordinate is odd\n var isYOdd = j & 1;\n var isSecondKey = j >> 1;\n if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)\n throw new Error('Unable to find sencond key candinate');\n\n // 1.1. Let x = r + jn.\n if (isSecondKey)\n r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);\n else\n r = this.curve.pointFromX(r, isYOdd);\n\n var rInv = signature.r.invm(n);\n var s1 = n.sub(e).mul(rInv).umod(n);\n var s2 = s.mul(rInv).umod(n);\n\n // 1.6.1 Compute Q = r^-1 (sR - eG)\n // Q = r^-1 (sR + -eG)\n return this.g.mulAdd(s1, r, s2);\n};\n\nEC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {\n signature = new Signature(signature, enc);\n if (signature.recoveryParam !== null)\n return signature.recoveryParam;\n\n for (var i = 0; i < 4; i++) {\n var Qprime;\n try {\n Qprime = this.recoverPubKey(e, signature, i);\n } catch (e) {\n continue;\n }\n\n if (Qprime.eq(Q))\n return i;\n }\n throw new Error('Unable to find valid recovery factor');\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/ec/index.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/ec/key.js": +/*!******************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/ec/key.js ***! + \******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\n\nfunction KeyPair(ec, options) {\n this.ec = ec;\n this.priv = null;\n this.pub = null;\n\n // KeyPair(ec, { priv: ..., pub: ... })\n if (options.priv)\n this._importPrivate(options.priv, options.privEnc);\n if (options.pub)\n this._importPublic(options.pub, options.pubEnc);\n}\nmodule.exports = KeyPair;\n\nKeyPair.fromPublic = function fromPublic(ec, pub, enc) {\n if (pub instanceof KeyPair)\n return pub;\n\n return new KeyPair(ec, {\n pub: pub,\n pubEnc: enc,\n });\n};\n\nKeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {\n if (priv instanceof KeyPair)\n return priv;\n\n return new KeyPair(ec, {\n priv: priv,\n privEnc: enc,\n });\n};\n\nKeyPair.prototype.validate = function validate() {\n var pub = this.getPublic();\n\n if (pub.isInfinity())\n return { result: false, reason: 'Invalid public key' };\n if (!pub.validate())\n return { result: false, reason: 'Public key is not a point' };\n if (!pub.mul(this.ec.curve.n).isInfinity())\n return { result: false, reason: 'Public key * N != O' };\n\n return { result: true, reason: null };\n};\n\nKeyPair.prototype.getPublic = function getPublic(compact, enc) {\n // compact is optional argument\n if (typeof compact === 'string') {\n enc = compact;\n compact = null;\n }\n\n if (!this.pub)\n this.pub = this.ec.g.mul(this.priv);\n\n if (!enc)\n return this.pub;\n\n return this.pub.encode(enc, compact);\n};\n\nKeyPair.prototype.getPrivate = function getPrivate(enc) {\n if (enc === 'hex')\n return this.priv.toString(16, 2);\n else\n return this.priv;\n};\n\nKeyPair.prototype._importPrivate = function _importPrivate(key, enc) {\n this.priv = new BN(key, enc || 16);\n\n // Ensure that the priv won't be bigger than n, otherwise we may fail\n // in fixed multiplication method\n this.priv = this.priv.umod(this.ec.curve.n);\n};\n\nKeyPair.prototype._importPublic = function _importPublic(key, enc) {\n if (key.x || key.y) {\n // Montgomery points only have an `x` coordinate.\n // Weierstrass/Edwards points on the other hand have both `x` and\n // `y` coordinates.\n if (this.ec.curve.type === 'mont') {\n assert(key.x, 'Need x coordinate');\n } else if (this.ec.curve.type === 'short' ||\n this.ec.curve.type === 'edwards') {\n assert(key.x && key.y, 'Need both x and y coordinate');\n }\n this.pub = this.ec.curve.point(key.x, key.y);\n return;\n }\n this.pub = this.ec.curve.decodePoint(key, enc);\n};\n\n// ECDH\nKeyPair.prototype.derive = function derive(pub) {\n if(!pub.validate()) {\n assert(pub.validate(), 'public point not validated');\n }\n return pub.mul(this.priv).getX();\n};\n\n// ECDSA\nKeyPair.prototype.sign = function sign(msg, enc, options) {\n return this.ec.sign(msg, this, enc, options);\n};\n\nKeyPair.prototype.verify = function verify(msg, signature) {\n return this.ec.verify(msg, signature, this);\n};\n\nKeyPair.prototype.inspect = function inspect() {\n return '';\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/ec/key.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/ec/signature.js": +/*!************************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/ec/signature.js ***! + \************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\n\nfunction Signature(options, enc) {\n if (options instanceof Signature)\n return options;\n\n if (this._importDER(options, enc))\n return;\n\n assert(options.r && options.s, 'Signature without r or s');\n this.r = new BN(options.r, 16);\n this.s = new BN(options.s, 16);\n if (options.recoveryParam === undefined)\n this.recoveryParam = null;\n else\n this.recoveryParam = options.recoveryParam;\n}\nmodule.exports = Signature;\n\nfunction Position() {\n this.place = 0;\n}\n\nfunction getLength(buf, p) {\n var initial = buf[p.place++];\n if (!(initial & 0x80)) {\n return initial;\n }\n var octetLen = initial & 0xf;\n\n // Indefinite length or overflow\n if (octetLen === 0 || octetLen > 4) {\n return false;\n }\n\n var val = 0;\n for (var i = 0, off = p.place; i < octetLen; i++, off++) {\n val <<= 8;\n val |= buf[off];\n val >>>= 0;\n }\n\n // Leading zeroes\n if (val <= 0x7f) {\n return false;\n }\n\n p.place = off;\n return val;\n}\n\nfunction rmPadding(buf) {\n var i = 0;\n var len = buf.length - 1;\n while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {\n i++;\n }\n if (i === 0) {\n return buf;\n }\n return buf.slice(i);\n}\n\nSignature.prototype._importDER = function _importDER(data, enc) {\n data = utils.toArray(data, enc);\n var p = new Position();\n if (data[p.place++] !== 0x30) {\n return false;\n }\n var len = getLength(data, p);\n if (len === false) {\n return false;\n }\n if ((len + p.place) !== data.length) {\n return false;\n }\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var rlen = getLength(data, p);\n if (rlen === false) {\n return false;\n }\n var r = data.slice(p.place, rlen + p.place);\n p.place += rlen;\n if (data[p.place++] !== 0x02) {\n return false;\n }\n var slen = getLength(data, p);\n if (slen === false) {\n return false;\n }\n if (data.length !== slen + p.place) {\n return false;\n }\n var s = data.slice(p.place, slen + p.place);\n if (r[0] === 0) {\n if (r[1] & 0x80) {\n r = r.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n if (s[0] === 0) {\n if (s[1] & 0x80) {\n s = s.slice(1);\n } else {\n // Leading zeroes\n return false;\n }\n }\n\n this.r = new BN(r);\n this.s = new BN(s);\n this.recoveryParam = null;\n\n return true;\n};\n\nfunction constructLength(arr, len) {\n if (len < 0x80) {\n arr.push(len);\n return;\n }\n var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);\n arr.push(octets | 0x80);\n while (--octets) {\n arr.push((len >>> (octets << 3)) & 0xff);\n }\n arr.push(len);\n}\n\nSignature.prototype.toDER = function toDER(enc) {\n var r = this.r.toArray();\n var s = this.s.toArray();\n\n // Pad values\n if (r[0] & 0x80)\n r = [ 0 ].concat(r);\n // Pad values\n if (s[0] & 0x80)\n s = [ 0 ].concat(s);\n\n r = rmPadding(r);\n s = rmPadding(s);\n\n while (!s[0] && !(s[1] & 0x80)) {\n s = s.slice(1);\n }\n var arr = [ 0x02 ];\n constructLength(arr, r.length);\n arr = arr.concat(r);\n arr.push(0x02);\n constructLength(arr, s.length);\n var backHalf = arr.concat(s);\n var res = [ 0x30 ];\n constructLength(res, backHalf.length);\n res = res.concat(backHalf);\n return utils.encode(res, enc);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/ec/signature.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/eddsa/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/eddsa/index.js ***! + \***********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar hash = __webpack_require__(/*! hash.js */ \"./node_modules/hash.js/lib/hash.js\");\nvar curves = __webpack_require__(/*! ../curves */ \"./node_modules/elliptic/lib/elliptic/curves.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar KeyPair = __webpack_require__(/*! ./key */ \"./node_modules/elliptic/lib/elliptic/eddsa/key.js\");\nvar Signature = __webpack_require__(/*! ./signature */ \"./node_modules/elliptic/lib/elliptic/eddsa/signature.js\");\n\nfunction EDDSA(curve) {\n assert(curve === 'ed25519', 'only tested with ed25519 so far');\n\n if (!(this instanceof EDDSA))\n return new EDDSA(curve);\n\n curve = curves[curve].curve;\n this.curve = curve;\n this.g = curve.g;\n this.g.precompute(curve.n.bitLength() + 1);\n\n this.pointClass = curve.point().constructor;\n this.encodingLength = Math.ceil(curve.n.bitLength() / 8);\n this.hash = hash.sha512;\n}\n\nmodule.exports = EDDSA;\n\n/**\n* @param {Array|String} message - message bytes\n* @param {Array|String|KeyPair} secret - secret bytes or a keypair\n* @returns {Signature} - signature\n*/\nEDDSA.prototype.sign = function sign(message, secret) {\n message = parseBytes(message);\n var key = this.keyFromSecret(secret);\n var r = this.hashInt(key.messagePrefix(), message);\n var R = this.g.mul(r);\n var Rencoded = this.encodePoint(R);\n var s_ = this.hashInt(Rencoded, key.pubBytes(), message)\n .mul(key.priv());\n var S = r.add(s_).umod(this.curve.n);\n return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });\n};\n\n/**\n* @param {Array} message - message bytes\n* @param {Array|String|Signature} sig - sig bytes\n* @param {Array|String|Point|KeyPair} pub - public key\n* @returns {Boolean} - true if public key matches sig of message\n*/\nEDDSA.prototype.verify = function verify(message, sig, pub) {\n message = parseBytes(message);\n sig = this.makeSignature(sig);\n var key = this.keyFromPublic(pub);\n var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);\n var SG = this.g.mul(sig.S());\n var RplusAh = sig.R().add(key.pub().mul(h));\n return RplusAh.eq(SG);\n};\n\nEDDSA.prototype.hashInt = function hashInt() {\n var hash = this.hash();\n for (var i = 0; i < arguments.length; i++)\n hash.update(arguments[i]);\n return utils.intFromLE(hash.digest()).umod(this.curve.n);\n};\n\nEDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {\n return KeyPair.fromPublic(this, pub);\n};\n\nEDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {\n return KeyPair.fromSecret(this, secret);\n};\n\nEDDSA.prototype.makeSignature = function makeSignature(sig) {\n if (sig instanceof Signature)\n return sig;\n return new Signature(this, sig);\n};\n\n/**\n* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2\n*\n* EDDSA defines methods for encoding and decoding points and integers. These are\n* helper convenience methods, that pass along to utility functions implied\n* parameters.\n*\n*/\nEDDSA.prototype.encodePoint = function encodePoint(point) {\n var enc = point.getY().toArray('le', this.encodingLength);\n enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;\n return enc;\n};\n\nEDDSA.prototype.decodePoint = function decodePoint(bytes) {\n bytes = utils.parseBytes(bytes);\n\n var lastIx = bytes.length - 1;\n var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);\n var xIsOdd = (bytes[lastIx] & 0x80) !== 0;\n\n var y = utils.intFromLE(normed);\n return this.curve.pointFromY(y, xIsOdd);\n};\n\nEDDSA.prototype.encodeInt = function encodeInt(num) {\n return num.toArray('le', this.encodingLength);\n};\n\nEDDSA.prototype.decodeInt = function decodeInt(bytes) {\n return utils.intFromLE(bytes);\n};\n\nEDDSA.prototype.isPoint = function isPoint(val) {\n return val instanceof this.pointClass;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/eddsa/index.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/eddsa/key.js": +/*!*********************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/eddsa/key.js ***! + \*********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar parseBytes = utils.parseBytes;\nvar cachedProperty = utils.cachedProperty;\n\n/**\n* @param {EDDSA} eddsa - instance\n* @param {Object} params - public/private key parameters\n*\n* @param {Array} [params.secret] - secret seed bytes\n* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)\n* @param {Array} [params.pub] - public key point encoded as bytes\n*\n*/\nfunction KeyPair(eddsa, params) {\n this.eddsa = eddsa;\n this._secret = parseBytes(params.secret);\n if (eddsa.isPoint(params.pub))\n this._pub = params.pub;\n else\n this._pubBytes = parseBytes(params.pub);\n}\n\nKeyPair.fromPublic = function fromPublic(eddsa, pub) {\n if (pub instanceof KeyPair)\n return pub;\n return new KeyPair(eddsa, { pub: pub });\n};\n\nKeyPair.fromSecret = function fromSecret(eddsa, secret) {\n if (secret instanceof KeyPair)\n return secret;\n return new KeyPair(eddsa, { secret: secret });\n};\n\nKeyPair.prototype.secret = function secret() {\n return this._secret;\n};\n\ncachedProperty(KeyPair, 'pubBytes', function pubBytes() {\n return this.eddsa.encodePoint(this.pub());\n});\n\ncachedProperty(KeyPair, 'pub', function pub() {\n if (this._pubBytes)\n return this.eddsa.decodePoint(this._pubBytes);\n return this.eddsa.g.mul(this.priv());\n});\n\ncachedProperty(KeyPair, 'privBytes', function privBytes() {\n var eddsa = this.eddsa;\n var hash = this.hash();\n var lastIx = eddsa.encodingLength - 1;\n\n var a = hash.slice(0, eddsa.encodingLength);\n a[0] &= 248;\n a[lastIx] &= 127;\n a[lastIx] |= 64;\n\n return a;\n});\n\ncachedProperty(KeyPair, 'priv', function priv() {\n return this.eddsa.decodeInt(this.privBytes());\n});\n\ncachedProperty(KeyPair, 'hash', function hash() {\n return this.eddsa.hash().update(this.secret()).digest();\n});\n\ncachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {\n return this.hash().slice(this.eddsa.encodingLength);\n});\n\nKeyPair.prototype.sign = function sign(message) {\n assert(this._secret, 'KeyPair can only verify');\n return this.eddsa.sign(message, this);\n};\n\nKeyPair.prototype.verify = function verify(message, sig) {\n return this.eddsa.verify(message, sig, this);\n};\n\nKeyPair.prototype.getSecret = function getSecret(enc) {\n assert(this._secret, 'KeyPair is public only');\n return utils.encode(this.secret(), enc);\n};\n\nKeyPair.prototype.getPublic = function getPublic(enc) {\n return utils.encode(this.pubBytes(), enc);\n};\n\nmodule.exports = KeyPair;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/eddsa/key.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/eddsa/signature.js": +/*!***************************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/eddsa/signature.js ***! + \***************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar utils = __webpack_require__(/*! ../utils */ \"./node_modules/elliptic/lib/elliptic/utils.js\");\nvar assert = utils.assert;\nvar cachedProperty = utils.cachedProperty;\nvar parseBytes = utils.parseBytes;\n\n/**\n* @param {EDDSA} eddsa - eddsa instance\n* @param {Array|Object} sig -\n* @param {Array|Point} [sig.R] - R point as Point or bytes\n* @param {Array|bn} [sig.S] - S scalar as bn or bytes\n* @param {Array} [sig.Rencoded] - R point encoded\n* @param {Array} [sig.Sencoded] - S scalar encoded\n*/\nfunction Signature(eddsa, sig) {\n this.eddsa = eddsa;\n\n if (typeof sig !== 'object')\n sig = parseBytes(sig);\n\n if (Array.isArray(sig)) {\n sig = {\n R: sig.slice(0, eddsa.encodingLength),\n S: sig.slice(eddsa.encodingLength),\n };\n }\n\n assert(sig.R && sig.S, 'Signature without R or S');\n\n if (eddsa.isPoint(sig.R))\n this._R = sig.R;\n if (sig.S instanceof BN)\n this._S = sig.S;\n\n this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;\n this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;\n}\n\ncachedProperty(Signature, 'S', function S() {\n return this.eddsa.decodeInt(this.Sencoded());\n});\n\ncachedProperty(Signature, 'R', function R() {\n return this.eddsa.decodePoint(this.Rencoded());\n});\n\ncachedProperty(Signature, 'Rencoded', function Rencoded() {\n return this.eddsa.encodePoint(this.R());\n});\n\ncachedProperty(Signature, 'Sencoded', function Sencoded() {\n return this.eddsa.encodeInt(this.S());\n});\n\nSignature.prototype.toBytes = function toBytes() {\n return this.Rencoded().concat(this.Sencoded());\n};\n\nSignature.prototype.toHex = function toHex() {\n return utils.encode(this.toBytes(), 'hex').toUpperCase();\n};\n\nmodule.exports = Signature;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/eddsa/signature.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js": +/*!*********************************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js ***! + \*********************************************************************/ +/***/ ((module) => { + +eval("module.exports = {\n doubles: {\n step: 4,\n points: [\n [\n 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',\n 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821',\n ],\n [\n '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',\n '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf',\n ],\n [\n '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',\n 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695',\n ],\n [\n '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',\n '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9',\n ],\n [\n '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',\n '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36',\n ],\n [\n '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',\n '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f',\n ],\n [\n 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',\n '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999',\n ],\n [\n '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',\n 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09',\n ],\n [\n 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',\n '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d',\n ],\n [\n 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',\n 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088',\n ],\n [\n 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',\n '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d',\n ],\n [\n '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',\n '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8',\n ],\n [\n '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',\n '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a',\n ],\n [\n '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',\n '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453',\n ],\n [\n '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',\n '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160',\n ],\n [\n '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',\n '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0',\n ],\n [\n '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',\n '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6',\n ],\n [\n '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',\n '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589',\n ],\n [\n '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',\n 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17',\n ],\n [\n 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',\n '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda',\n ],\n [\n 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',\n '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd',\n ],\n [\n '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',\n '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2',\n ],\n [\n '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',\n '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6',\n ],\n [\n 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',\n '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f',\n ],\n [\n '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',\n 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01',\n ],\n [\n 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',\n '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3',\n ],\n [\n 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',\n 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f',\n ],\n [\n 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',\n '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7',\n ],\n [\n 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',\n 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78',\n ],\n [\n 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',\n '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1',\n ],\n [\n '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',\n 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150',\n ],\n [\n '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',\n '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82',\n ],\n [\n 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',\n '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc',\n ],\n [\n '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',\n 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b',\n ],\n [\n 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',\n '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51',\n ],\n [\n 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',\n '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45',\n ],\n [\n 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',\n 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120',\n ],\n [\n '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',\n '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84',\n ],\n [\n '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',\n '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d',\n ],\n [\n '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',\n 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d',\n ],\n [\n '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',\n '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8',\n ],\n [\n 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',\n '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8',\n ],\n [\n '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',\n '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac',\n ],\n [\n '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',\n 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f',\n ],\n [\n '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',\n '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962',\n ],\n [\n 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',\n '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907',\n ],\n [\n '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',\n 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec',\n ],\n [\n 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',\n 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d',\n ],\n [\n 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',\n '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414',\n ],\n [\n '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',\n 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd',\n ],\n [\n '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',\n 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0',\n ],\n [\n 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',\n '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811',\n ],\n [\n 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',\n '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1',\n ],\n [\n 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',\n '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c',\n ],\n [\n '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',\n 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73',\n ],\n [\n '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',\n '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd',\n ],\n [\n 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',\n 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405',\n ],\n [\n '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',\n 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589',\n ],\n [\n '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',\n '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e',\n ],\n [\n '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',\n '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27',\n ],\n [\n 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',\n 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1',\n ],\n [\n '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',\n '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482',\n ],\n [\n '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',\n '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945',\n ],\n [\n 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',\n '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573',\n ],\n [\n 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',\n 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82',\n ],\n ],\n },\n naf: {\n wnd: 7,\n points: [\n [\n 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',\n '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672',\n ],\n [\n '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',\n 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6',\n ],\n [\n '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',\n '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da',\n ],\n [\n 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',\n 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37',\n ],\n [\n '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',\n 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b',\n ],\n [\n 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',\n 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81',\n ],\n [\n 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',\n '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58',\n ],\n [\n 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',\n '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77',\n ],\n [\n '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',\n '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a',\n ],\n [\n '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',\n '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c',\n ],\n [\n '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',\n '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67',\n ],\n [\n '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',\n '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402',\n ],\n [\n 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',\n 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55',\n ],\n [\n 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',\n '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482',\n ],\n [\n '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',\n 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82',\n ],\n [\n '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',\n 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396',\n ],\n [\n '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',\n '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49',\n ],\n [\n '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',\n '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf',\n ],\n [\n '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',\n '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a',\n ],\n [\n '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',\n 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7',\n ],\n [\n 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',\n 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933',\n ],\n [\n '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',\n '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a',\n ],\n [\n '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',\n '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6',\n ],\n [\n 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',\n 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37',\n ],\n [\n '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',\n '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e',\n ],\n [\n 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',\n 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6',\n ],\n [\n 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',\n 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476',\n ],\n [\n '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',\n '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40',\n ],\n [\n '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',\n '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61',\n ],\n [\n '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',\n '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683',\n ],\n [\n 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',\n '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5',\n ],\n [\n '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',\n '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b',\n ],\n [\n 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',\n '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417',\n ],\n [\n '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',\n 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868',\n ],\n [\n '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',\n 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a',\n ],\n [\n 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',\n 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6',\n ],\n [\n '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',\n '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996',\n ],\n [\n '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',\n 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e',\n ],\n [\n 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',\n 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d',\n ],\n [\n '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',\n '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2',\n ],\n [\n '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',\n 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e',\n ],\n [\n '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',\n '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437',\n ],\n [\n '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',\n 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311',\n ],\n [\n 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',\n '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4',\n ],\n [\n '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',\n '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575',\n ],\n [\n '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',\n 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d',\n ],\n [\n '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',\n 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d',\n ],\n [\n 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',\n 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629',\n ],\n [\n 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',\n 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06',\n ],\n [\n '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',\n '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374',\n ],\n [\n '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',\n '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee',\n ],\n [\n 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',\n '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1',\n ],\n [\n 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',\n 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b',\n ],\n [\n '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',\n '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661',\n ],\n [\n '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',\n '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6',\n ],\n [\n 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',\n '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e',\n ],\n [\n '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',\n '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d',\n ],\n [\n 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',\n 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc',\n ],\n [\n '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',\n 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4',\n ],\n [\n '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',\n '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c',\n ],\n [\n 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',\n '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b',\n ],\n [\n 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',\n '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913',\n ],\n [\n '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',\n '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154',\n ],\n [\n '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',\n '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865',\n ],\n [\n '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',\n 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc',\n ],\n [\n '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',\n 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224',\n ],\n [\n '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',\n '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e',\n ],\n [\n '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',\n '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6',\n ],\n [\n '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',\n '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511',\n ],\n [\n '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',\n 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b',\n ],\n [\n 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',\n 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2',\n ],\n [\n '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',\n 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c',\n ],\n [\n 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',\n '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3',\n ],\n [\n 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',\n '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d',\n ],\n [\n 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',\n '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700',\n ],\n [\n 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',\n '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4',\n ],\n [\n '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',\n 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196',\n ],\n [\n '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',\n '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4',\n ],\n [\n '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',\n 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257',\n ],\n [\n 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',\n 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13',\n ],\n [\n 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',\n '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096',\n ],\n [\n 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',\n 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38',\n ],\n [\n 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',\n '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f',\n ],\n [\n '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',\n '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448',\n ],\n [\n 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',\n '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a',\n ],\n [\n 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',\n '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4',\n ],\n [\n '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',\n '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437',\n ],\n [\n '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',\n 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7',\n ],\n [\n 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',\n '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d',\n ],\n [\n 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',\n '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a',\n ],\n [\n 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',\n '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54',\n ],\n [\n '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',\n '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77',\n ],\n [\n 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',\n 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517',\n ],\n [\n '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',\n 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10',\n ],\n [\n 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',\n 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125',\n ],\n [\n 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',\n '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e',\n ],\n [\n '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',\n 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1',\n ],\n [\n 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',\n '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2',\n ],\n [\n 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',\n '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423',\n ],\n [\n 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',\n '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8',\n ],\n [\n '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',\n 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758',\n ],\n [\n '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',\n 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375',\n ],\n [\n 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',\n '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d',\n ],\n [\n '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',\n 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec',\n ],\n [\n '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',\n '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0',\n ],\n [\n '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',\n 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c',\n ],\n [\n 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',\n 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4',\n ],\n [\n '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',\n 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f',\n ],\n [\n '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',\n '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649',\n ],\n [\n '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',\n 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826',\n ],\n [\n '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',\n '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5',\n ],\n [\n 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',\n 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87',\n ],\n [\n '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',\n '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b',\n ],\n [\n 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',\n '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc',\n ],\n [\n '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',\n '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c',\n ],\n [\n 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',\n 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f',\n ],\n [\n 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',\n '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a',\n ],\n [\n 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',\n 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46',\n ],\n [\n '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',\n 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f',\n ],\n [\n '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',\n '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03',\n ],\n [\n '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',\n 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08',\n ],\n [\n '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',\n '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8',\n ],\n [\n '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',\n '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373',\n ],\n [\n '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',\n 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3',\n ],\n [\n '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',\n '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8',\n ],\n [\n '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',\n '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1',\n ],\n [\n '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',\n '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9',\n ],\n ],\n },\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/lib/elliptic/utils.js": +/*!*****************************************************!*\ + !*** ./node_modules/elliptic/lib/elliptic/utils.js ***! + \*****************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar utils = exports;\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/elliptic/node_modules/bn.js/lib/bn.js\");\nvar minAssert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\nvar minUtils = __webpack_require__(/*! minimalistic-crypto-utils */ \"./node_modules/minimalistic-crypto-utils/lib/utils.js\");\n\nutils.assert = minAssert;\nutils.toArray = minUtils.toArray;\nutils.zero2 = minUtils.zero2;\nutils.toHex = minUtils.toHex;\nutils.encode = minUtils.encode;\n\n// Represent num in a w-NAF form\nfunction getNAF(num, w, bits) {\n var naf = new Array(Math.max(num.bitLength(), bits) + 1);\n naf.fill(0);\n\n var ws = 1 << (w + 1);\n var k = num.clone();\n\n for (var i = 0; i < naf.length; i++) {\n var z;\n var mod = k.andln(ws - 1);\n if (k.isOdd()) {\n if (mod > (ws >> 1) - 1)\n z = (ws >> 1) - mod;\n else\n z = mod;\n k.isubn(z);\n } else {\n z = 0;\n }\n\n naf[i] = z;\n k.iushrn(1);\n }\n\n return naf;\n}\nutils.getNAF = getNAF;\n\n// Represent k1, k2 in a Joint Sparse Form\nfunction getJSF(k1, k2) {\n var jsf = [\n [],\n [],\n ];\n\n k1 = k1.clone();\n k2 = k2.clone();\n var d1 = 0;\n var d2 = 0;\n var m8;\n while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {\n // First phase\n var m14 = (k1.andln(3) + d1) & 3;\n var m24 = (k2.andln(3) + d2) & 3;\n if (m14 === 3)\n m14 = -1;\n if (m24 === 3)\n m24 = -1;\n var u1;\n if ((m14 & 1) === 0) {\n u1 = 0;\n } else {\n m8 = (k1.andln(7) + d1) & 7;\n if ((m8 === 3 || m8 === 5) && m24 === 2)\n u1 = -m14;\n else\n u1 = m14;\n }\n jsf[0].push(u1);\n\n var u2;\n if ((m24 & 1) === 0) {\n u2 = 0;\n } else {\n m8 = (k2.andln(7) + d2) & 7;\n if ((m8 === 3 || m8 === 5) && m14 === 2)\n u2 = -m24;\n else\n u2 = m24;\n }\n jsf[1].push(u2);\n\n // Second phase\n if (2 * d1 === u1 + 1)\n d1 = 1 - d1;\n if (2 * d2 === u2 + 1)\n d2 = 1 - d2;\n k1.iushrn(1);\n k2.iushrn(1);\n }\n\n return jsf;\n}\nutils.getJSF = getJSF;\n\nfunction cachedProperty(obj, name, computer) {\n var key = '_' + name;\n obj.prototype[name] = function cachedProperty() {\n return this[key] !== undefined ? this[key] :\n this[key] = computer.call(this);\n };\n}\nutils.cachedProperty = cachedProperty;\n\nfunction parseBytes(bytes) {\n return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :\n bytes;\n}\nutils.parseBytes = parseBytes;\n\nfunction intFromLE(bytes) {\n return new BN(bytes, 'hex', 'le');\n}\nutils.intFromLE = intFromLE;\n\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/lib/elliptic/utils.js?"); + +/***/ }), + +/***/ "./node_modules/elliptic/node_modules/bn.js/lib/bn.js": +/*!************************************************************!*\ + !*** ./node_modules/elliptic/node_modules/bn.js/lib/bn.js ***! + \************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?7bec\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + /***/ "./node_modules/err-code/index.js": /*!****************************************!*\ !*** ./node_modules/err-code/index.js ***! @@ -1057,7 +2236,7 @@ eval("\n\n/**\n * @typedef {{ [key: string]: any }} Extensions\n * @typedef {Err /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.decrypt = exports.encrypt = void 0;\nconst crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/crypto.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nconst crypto = { web: crypto_1.crypto };\nfunction validateOpt(key, iv, mode) {\n if (!mode.startsWith(\"aes-\")) {\n throw new Error(`AES submodule doesn't support mode ${mode}`);\n }\n if (iv.length !== 16) {\n throw new Error(\"AES: wrong IV length\");\n }\n if ((mode.startsWith(\"aes-128\") && key.length !== 16) ||\n (mode.startsWith(\"aes-256\") && key.length !== 32)) {\n throw new Error(\"AES: wrong key length\");\n }\n}\nasync function getBrowserKey(mode, key, iv) {\n if (!crypto.web) {\n throw new Error(\"Browser crypto not available.\");\n }\n let keyMode;\n if ([\"aes-128-cbc\", \"aes-256-cbc\"].includes(mode)) {\n keyMode = \"cbc\";\n }\n if ([\"aes-128-ctr\", \"aes-256-ctr\"].includes(mode)) {\n keyMode = \"ctr\";\n }\n if (!keyMode) {\n throw new Error(\"AES: unsupported mode\");\n }\n const wKey = await crypto.web.subtle.importKey(\"raw\", key, { name: `AES-${keyMode.toUpperCase()}`, length: key.length * 8 }, true, [\"encrypt\", \"decrypt\"]);\n // node.js uses whole 128 bit as a counter, without nonce, instead of 64 bit\n // recommended by NIST SP800-38A\n return [wKey, { name: `aes-${keyMode}`, iv, counter: iv, length: 128 }];\n}\nasync function encrypt(msg, key, iv, mode = \"aes-128-ctr\", pkcs7PaddingEnabled = true) {\n validateOpt(key, iv, mode);\n if (crypto.web) {\n const [wKey, wOpt] = await getBrowserKey(mode, key, iv);\n const cipher = await crypto.web.subtle.encrypt(wOpt, wKey, msg);\n // Remove PKCS7 padding on cbc mode by stripping end of message\n let res = new Uint8Array(cipher);\n if (!pkcs7PaddingEnabled && wOpt.name === \"aes-cbc\" && !(msg.length % 16)) {\n res = res.slice(0, -16);\n }\n return res;\n }\n else if (crypto.node) {\n const cipher = crypto.node.createCipheriv(mode, key, iv);\n cipher.setAutoPadding(pkcs7PaddingEnabled);\n return (0, utils_js_1.concatBytes)(cipher.update(msg), cipher.final());\n }\n else {\n throw new Error(\"The environment doesn't have AES module\");\n }\n}\nexports.encrypt = encrypt;\nasync function getPadding(cypherText, key, iv, mode) {\n const lastBlock = cypherText.slice(-16);\n for (let i = 0; i < 16; i++) {\n // Undo xor of iv and fill with lastBlock ^ padding (16)\n lastBlock[i] ^= iv[i] ^ 16;\n }\n const res = await encrypt(lastBlock, key, iv, mode);\n return res.slice(0, 16);\n}\nasync function decrypt(cypherText, key, iv, mode = \"aes-128-ctr\", pkcs7PaddingEnabled = true) {\n validateOpt(key, iv, mode);\n if (crypto.web) {\n const [wKey, wOpt] = await getBrowserKey(mode, key, iv);\n // Add empty padding so Chrome will correctly decrypt message\n if (!pkcs7PaddingEnabled && wOpt.name === \"aes-cbc\") {\n const padding = await getPadding(cypherText, key, iv, mode);\n cypherText = (0, utils_js_1.concatBytes)(cypherText, padding);\n }\n const msg = await crypto.web.subtle.decrypt(wOpt, wKey, cypherText);\n const msgBytes = new Uint8Array(msg);\n // Safari always ignores padding (if no padding -> broken message)\n if (wOpt.name === \"aes-cbc\") {\n const encrypted = await encrypt(msgBytes, key, iv, mode);\n if (!(0, utils_js_1.equalsBytes)(encrypted, cypherText)) {\n throw new Error(\"AES: wrong padding\");\n }\n }\n return msgBytes;\n }\n else if (crypto.node) {\n const decipher = crypto.node.createDecipheriv(mode, key, iv);\n decipher.setAutoPadding(pkcs7PaddingEnabled);\n return (0, utils_js_1.concatBytes)(decipher.update(cypherText), decipher.final());\n }\n else {\n throw new Error(\"The environment doesn't have AES module\");\n }\n}\nexports.decrypt = decrypt;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/aes.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.encrypt = encrypt;\nexports.decrypt = decrypt;\nconst crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/crypto.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nconst crypto = { web: crypto_1.crypto };\nfunction validateOpt(key, iv, mode) {\n if (!mode.startsWith(\"aes-\")) {\n throw new Error(`AES submodule doesn't support mode ${mode}`);\n }\n if (iv.length !== 16) {\n throw new Error(\"AES: wrong IV length\");\n }\n if ((mode.startsWith(\"aes-128\") && key.length !== 16) ||\n (mode.startsWith(\"aes-256\") && key.length !== 32)) {\n throw new Error(\"AES: wrong key length\");\n }\n}\nasync function getBrowserKey(mode, key, iv) {\n if (!crypto.web) {\n throw new Error(\"Browser crypto not available.\");\n }\n let keyMode;\n if ([\"aes-128-cbc\", \"aes-256-cbc\"].includes(mode)) {\n keyMode = \"cbc\";\n }\n if ([\"aes-128-ctr\", \"aes-256-ctr\"].includes(mode)) {\n keyMode = \"ctr\";\n }\n if (!keyMode) {\n throw new Error(\"AES: unsupported mode\");\n }\n const wKey = await crypto.web.subtle.importKey(\"raw\", key, { name: `AES-${keyMode.toUpperCase()}`, length: key.length * 8 }, true, [\"encrypt\", \"decrypt\"]);\n // node.js uses whole 128 bit as a counter, without nonce, instead of 64 bit\n // recommended by NIST SP800-38A\n return [wKey, { name: `aes-${keyMode}`, iv, counter: iv, length: 128 }];\n}\nasync function encrypt(msg, key, iv, mode = \"aes-128-ctr\", pkcs7PaddingEnabled = true) {\n validateOpt(key, iv, mode);\n if (crypto.web) {\n const [wKey, wOpt] = await getBrowserKey(mode, key, iv);\n const cipher = await crypto.web.subtle.encrypt(wOpt, wKey, msg);\n // Remove PKCS7 padding on cbc mode by stripping end of message\n let res = new Uint8Array(cipher);\n if (!pkcs7PaddingEnabled && wOpt.name === \"aes-cbc\" && !(msg.length % 16)) {\n res = res.slice(0, -16);\n }\n return res;\n }\n else if (crypto.node) {\n const cipher = crypto.node.createCipheriv(mode, key, iv);\n cipher.setAutoPadding(pkcs7PaddingEnabled);\n return (0, utils_js_1.concatBytes)(cipher.update(msg), cipher.final());\n }\n else {\n throw new Error(\"The environment doesn't have AES module\");\n }\n}\nasync function getPadding(cypherText, key, iv, mode) {\n const lastBlock = cypherText.slice(-16);\n for (let i = 0; i < 16; i++) {\n // Undo xor of iv and fill with lastBlock ^ padding (16)\n lastBlock[i] ^= iv[i] ^ 16;\n }\n const res = await encrypt(lastBlock, key, iv, mode);\n return res.slice(0, 16);\n}\nasync function decrypt(cypherText, key, iv, mode = \"aes-128-ctr\", pkcs7PaddingEnabled = true) {\n validateOpt(key, iv, mode);\n if (crypto.web) {\n const [wKey, wOpt] = await getBrowserKey(mode, key, iv);\n // Add empty padding so Chrome will correctly decrypt message\n if (!pkcs7PaddingEnabled && wOpt.name === \"aes-cbc\") {\n const padding = await getPadding(cypherText, key, iv, mode);\n cypherText = (0, utils_js_1.concatBytes)(cypherText, padding);\n }\n const msg = await crypto.web.subtle.decrypt(wOpt, wKey, cypherText);\n const msgBytes = new Uint8Array(msg);\n // Safari always ignores padding (if no padding -> broken message)\n if (wOpt.name === \"aes-cbc\") {\n const encrypted = await encrypt(msgBytes, key, iv, mode);\n if (!(0, utils_js_1.equalsBytes)(encrypted, cypherText)) {\n throw new Error(\"AES: wrong padding\");\n }\n }\n return msgBytes;\n }\n else if (crypto.node) {\n const decipher = crypto.node.createDecipheriv(mode, key, iv);\n decipher.setAutoPadding(pkcs7PaddingEnabled);\n return (0, utils_js_1.concatBytes)(decipher.update(cypherText), decipher.final());\n }\n else {\n throw new Error(\"The environment doesn't have AES module\");\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/aes.js?"); /***/ }), @@ -1068,18 +2247,18 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = void 0;\nfunction number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nexports.number = number;\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nexports.bool = bool;\n// copied from utils\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nexports.bytes = bytes;\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nexports.hash = hash;\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nexports.exists = exists;\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexports.output = output;\nconst assert = { number, bool, bytes, hash, exists, output };\nexports[\"default\"] = assert;\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.output = exports.exists = exports.hash = exports.bytes = exports.bool = exports.number = exports.isBytes = void 0;\nfunction number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nexports.number = number;\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\nexports.bool = bool;\n// copied from utils\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexports.isBytes = isBytes;\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nexports.bytes = bytes;\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nexports.hash = hash;\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nexports.exists = exists;\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexports.output = output;\nconst assert = { number, bool, bytes, hash, exists, output };\nexports[\"default\"] = assert;\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js?"); /***/ }), -/***/ "./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_sha2.js": -/*!********************************************************************************!*\ - !*** ./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_sha2.js ***! - \********************************************************************************/ +/***/ "./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_md.js": +/*!******************************************************************************!*\ + !*** ./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_md.js ***! + \******************************************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.SHA2 = void 0;\nconst _assert_js_1 = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nclass SHA2 extends utils_js_1.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0, utils_js_1.createView)(this.buffer);\n }\n update(data) {\n (0, _assert_js_1.exists)(this);\n const { view, buffer, blockLen } = this;\n data = (0, utils_js_1.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0, utils_js_1.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0, _assert_js_1.exists)(this);\n (0, _assert_js_1.output)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0, utils_js_1.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\nexports.SHA2 = SHA2;\n//# sourceMappingURL=_sha2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_sha2.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.HashMD = exports.Maj = exports.Chi = void 0;\nconst _assert_js_1 = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\nexports.Chi = Chi;\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\nexports.Maj = Maj;\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nclass HashMD extends utils_js_1.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0, utils_js_1.createView)(this.buffer);\n }\n update(data) {\n (0, _assert_js_1.exists)(this);\n const { view, buffer, blockLen } = this;\n data = (0, utils_js_1.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0, utils_js_1.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0, _assert_js_1.exists)(this);\n (0, _assert_js_1.output)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0, utils_js_1.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\nexports.HashMD = HashMD;\n//# sourceMappingURL=_md.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_md.js?"); /***/ }), @@ -1134,7 +2313,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.scryptAsync = exports.scrypt = void 0;\nconst _assert_js_1 = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\");\nconst sha256_js_1 = __webpack_require__(/*! ./sha256.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js\");\nconst pbkdf2_js_1 = __webpack_require__(/*! ./pbkdf2.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/pbkdf2.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// RFC 7914 Scrypt KDF\n// Left rotate for uint32\nconst rotl = (a, b) => (a << b) | (a >>> (32 - b));\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(prev, pi, input, ii, out, oi) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7);\n x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13);\n x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7);\n x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13);\n x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7);\n x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13);\n x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7);\n x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13);\n x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7);\n x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13);\n x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7);\n x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13);\n x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7);\n x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13);\n x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7);\n x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13);\n x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\nfunction BlockMix(input, ii, out, oi, r) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++)\n out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0)\n tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n // Maxmem - 1GB+1KB by default\n const opts = (0, utils_js_1.checkOpts)({\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n }, _opts);\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n (0, _assert_js_1.number)(N);\n (0, _assert_js_1.number)(r);\n (0, _assert_js_1.number)(p);\n (0, _assert_js_1.number)(dkLen);\n (0, _assert_js_1.number)(asyncTick);\n (0, _assert_js_1.number)(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {\n // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function\n // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.\n throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32');\n }\n if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {\n throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');\n }\n if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {\n throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = (0, utils_js_1.u32)(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N));\n const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize));\n let blockMixCb = () => { };\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\nfunction scryptOutput(password, dkLen, B, V, tmp) {\n const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen });\n B.fill(0);\n V.fill(0);\n tmp.fill(0);\n return res;\n}\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n */\nfunction scrypt(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\nexports.scrypt = scrypt;\n/**\n * Scrypt KDF from RFC 7914.\n */\nasync function scryptAsync(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await (0, utils_js_1.asyncLoop)(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\nexports.scryptAsync = scryptAsync;\n//# sourceMappingURL=scrypt.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/scrypt.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.scryptAsync = exports.scrypt = void 0;\nconst _assert_js_1 = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\");\nconst sha256_js_1 = __webpack_require__(/*! ./sha256.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js\");\nconst pbkdf2_js_1 = __webpack_require__(/*! ./pbkdf2.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/pbkdf2.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// RFC 7914 Scrypt KDF\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(prev, pi, input, ii, out, oi) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= (0, utils_js_1.rotl)(x00 + x12 | 0, 7);\n x08 ^= (0, utils_js_1.rotl)(x04 + x00 | 0, 9);\n x12 ^= (0, utils_js_1.rotl)(x08 + x04 | 0, 13);\n x00 ^= (0, utils_js_1.rotl)(x12 + x08 | 0, 18);\n x09 ^= (0, utils_js_1.rotl)(x05 + x01 | 0, 7);\n x13 ^= (0, utils_js_1.rotl)(x09 + x05 | 0, 9);\n x01 ^= (0, utils_js_1.rotl)(x13 + x09 | 0, 13);\n x05 ^= (0, utils_js_1.rotl)(x01 + x13 | 0, 18);\n x14 ^= (0, utils_js_1.rotl)(x10 + x06 | 0, 7);\n x02 ^= (0, utils_js_1.rotl)(x14 + x10 | 0, 9);\n x06 ^= (0, utils_js_1.rotl)(x02 + x14 | 0, 13);\n x10 ^= (0, utils_js_1.rotl)(x06 + x02 | 0, 18);\n x03 ^= (0, utils_js_1.rotl)(x15 + x11 | 0, 7);\n x07 ^= (0, utils_js_1.rotl)(x03 + x15 | 0, 9);\n x11 ^= (0, utils_js_1.rotl)(x07 + x03 | 0, 13);\n x15 ^= (0, utils_js_1.rotl)(x11 + x07 | 0, 18);\n x01 ^= (0, utils_js_1.rotl)(x00 + x03 | 0, 7);\n x02 ^= (0, utils_js_1.rotl)(x01 + x00 | 0, 9);\n x03 ^= (0, utils_js_1.rotl)(x02 + x01 | 0, 13);\n x00 ^= (0, utils_js_1.rotl)(x03 + x02 | 0, 18);\n x06 ^= (0, utils_js_1.rotl)(x05 + x04 | 0, 7);\n x07 ^= (0, utils_js_1.rotl)(x06 + x05 | 0, 9);\n x04 ^= (0, utils_js_1.rotl)(x07 + x06 | 0, 13);\n x05 ^= (0, utils_js_1.rotl)(x04 + x07 | 0, 18);\n x11 ^= (0, utils_js_1.rotl)(x10 + x09 | 0, 7);\n x08 ^= (0, utils_js_1.rotl)(x11 + x10 | 0, 9);\n x09 ^= (0, utils_js_1.rotl)(x08 + x11 | 0, 13);\n x10 ^= (0, utils_js_1.rotl)(x09 + x08 | 0, 18);\n x12 ^= (0, utils_js_1.rotl)(x15 + x14 | 0, 7);\n x13 ^= (0, utils_js_1.rotl)(x12 + x15 | 0, 9);\n x14 ^= (0, utils_js_1.rotl)(x13 + x12 | 0, 13);\n x15 ^= (0, utils_js_1.rotl)(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\nfunction BlockMix(input, ii, out, oi, r) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++)\n out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0)\n tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n // Maxmem - 1GB+1KB by default\n const opts = (0, utils_js_1.checkOpts)({\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n }, _opts);\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n (0, _assert_js_1.number)(N);\n (0, _assert_js_1.number)(r);\n (0, _assert_js_1.number)(p);\n (0, _assert_js_1.number)(dkLen);\n (0, _assert_js_1.number)(asyncTick);\n (0, _assert_js_1.number)(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {\n // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function\n // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.\n throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32');\n }\n if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {\n throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');\n }\n if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {\n throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = (0, utils_js_1.u32)(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = (0, utils_js_1.u32)(new Uint8Array(blockSize * N));\n const tmp = (0, utils_js_1.u32)(new Uint8Array(blockSize));\n let blockMixCb = () => { };\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\nfunction scryptOutput(password, dkLen, B, V, tmp) {\n const res = (0, pbkdf2_js_1.pbkdf2)(sha256_js_1.sha256, password, B, { c: 1, dkLen });\n B.fill(0);\n V.fill(0);\n tmp.fill(0);\n return res;\n}\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n */\nfunction scrypt(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);\n if (!utils_js_1.isLE)\n (0, utils_js_1.byteSwap32)(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n if (!utils_js_1.isLE)\n (0, utils_js_1.byteSwap32)(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\nexports.scrypt = scrypt;\n/**\n * Scrypt KDF from RFC 7914.\n */\nasync function scryptAsync(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);\n if (!utils_js_1.isLE)\n (0, utils_js_1.byteSwap32)(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await (0, utils_js_1.asyncLoop)(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await (0, utils_js_1.asyncLoop)(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n if (!utils_js_1.isLE)\n (0, utils_js_1.byteSwap32)(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\nexports.scryptAsync = scryptAsync;\n//# sourceMappingURL=scrypt.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/scrypt.js?"); /***/ }), @@ -1145,7 +2324,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.sha224 = exports.sha256 = void 0;\nconst _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_sha2.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _sha2_js_1.SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());\nexports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.sha224 = exports.sha256 = void 0;\nconst _md_js_1 = __webpack_require__(/*! ./_md.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_md.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _md_js_1.HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0, utils_js_1.rotr)(W15, 7) ^ (0, utils_js_1.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0, utils_js_1.rotr)(W2, 17) ^ (0, utils_js_1.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0, utils_js_1.rotr)(E, 6) ^ (0, utils_js_1.rotr)(E, 11) ^ (0, utils_js_1.rotr)(E, 25);\n const T1 = (H + sigma1 + (0, _md_js_1.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0, utils_js_1.rotr)(A, 2) ^ (0, utils_js_1.rotr)(A, 13) ^ (0, utils_js_1.rotr)(A, 22);\n const T2 = (sigma0 + (0, _md_js_1.Maj)(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexports.sha256 = (0, utils_js_1.wrapConstructor)(() => new SHA256());\nexports.sha224 = (0, utils_js_1.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js?"); /***/ }), @@ -1156,7 +2335,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0;\nconst _sha2_js_1 = __webpack_require__(/*! ./_sha2.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_sha2.js\");\nconst _u64_js_1 = __webpack_require__(/*! ./_u64.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_u64.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nclass SHA512 extends _sha2_js_1.SHA2 {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7);\n const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6);\n const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41);\n const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39);\n const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl);\n Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexports.SHA512 = SHA512;\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512());\nexports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224());\nexports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256());\nexports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384());\n//# sourceMappingURL=sha512.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha512.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.sha384 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.SHA512 = void 0;\nconst _md_js_1 = __webpack_require__(/*! ./_md.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_md.js\");\nconst _u64_js_1 = __webpack_require__(/*! ./_u64.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_u64.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js_1.default.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nclass SHA512 extends _md_js_1.HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = _u64_js_1.default.rotrSH(W15h, W15l, 1) ^ _u64_js_1.default.rotrSH(W15h, W15l, 8) ^ _u64_js_1.default.shrSH(W15h, W15l, 7);\n const s0l = _u64_js_1.default.rotrSL(W15h, W15l, 1) ^ _u64_js_1.default.rotrSL(W15h, W15l, 8) ^ _u64_js_1.default.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = _u64_js_1.default.rotrSH(W2h, W2l, 19) ^ _u64_js_1.default.rotrBH(W2h, W2l, 61) ^ _u64_js_1.default.shrSH(W2h, W2l, 6);\n const s1l = _u64_js_1.default.rotrSL(W2h, W2l, 19) ^ _u64_js_1.default.rotrBL(W2h, W2l, 61) ^ _u64_js_1.default.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = _u64_js_1.default.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = _u64_js_1.default.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = _u64_js_1.default.rotrSH(Eh, El, 14) ^ _u64_js_1.default.rotrSH(Eh, El, 18) ^ _u64_js_1.default.rotrBH(Eh, El, 41);\n const sigma1l = _u64_js_1.default.rotrSL(Eh, El, 14) ^ _u64_js_1.default.rotrSL(Eh, El, 18) ^ _u64_js_1.default.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = _u64_js_1.default.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = _u64_js_1.default.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = _u64_js_1.default.rotrSH(Ah, Al, 28) ^ _u64_js_1.default.rotrBH(Ah, Al, 34) ^ _u64_js_1.default.rotrBH(Ah, Al, 39);\n const sigma0l = _u64_js_1.default.rotrSL(Ah, Al, 28) ^ _u64_js_1.default.rotrBL(Ah, Al, 34) ^ _u64_js_1.default.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = _u64_js_1.default.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = _u64_js_1.default.add3L(T1l, sigma0l, MAJl);\n Ah = _u64_js_1.default.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = _u64_js_1.default.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = _u64_js_1.default.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = _u64_js_1.default.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = _u64_js_1.default.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = _u64_js_1.default.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = _u64_js_1.default.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = _u64_js_1.default.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = _u64_js_1.default.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nexports.SHA512 = SHA512;\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexports.sha512 = (0, utils_js_1.wrapConstructor)(() => new SHA512());\nexports.sha512_224 = (0, utils_js_1.wrapConstructor)(() => new SHA512_224());\nexports.sha512_256 = (0, utils_js_1.wrapConstructor)(() => new SHA512_256());\nexports.sha384 = (0, utils_js_1.wrapConstructor)(() => new SHA384());\n//# sourceMappingURL=sha512.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha512.js?"); /***/ }), @@ -1167,7 +2346,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.isLE = exports.rotr = exports.createView = exports.u32 = exports.u8 = void 0;\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nconst crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/crypto.js\");\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexports.u8 = u8;\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\nexports.u32 = u32;\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\nexports.createView = createView;\n// The rotate right (circular right shift) operation for uint32\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\nexports.rotr = rotr;\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\n// Other libraries would silently corrupt the data instead of throwing an error,\n// when they don't support it.\nexports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!exports.isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n if (!isBytes(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexports.bytesToHex = bytesToHex;\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexports.hexToBytes = hexToBytes;\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\nexports.nextTick = nextTick;\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await (0, exports.nextTick)();\n ts += diff;\n }\n}\nexports.asyncLoop = asyncLoop;\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\nexports.utf8ToBytes = utf8ToBytes;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!isBytes(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\nexports.toBytes = toBytes;\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a))\n throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexports.concatBytes = concatBytes;\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexports.Hash = Hash;\nconst toStr = {}.toString;\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexports.checkOpts = checkOpts;\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexports.wrapConstructor = wrapConstructor;\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexports.wrapConstructorWithOpts = wrapConstructorWithOpts;\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {\n return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\nexports.randomBytes = randomBytes;\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js?"); +eval("\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.randomBytes = exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.checkOpts = exports.Hash = exports.concatBytes = exports.toBytes = exports.utf8ToBytes = exports.asyncLoop = exports.nextTick = exports.hexToBytes = exports.bytesToHex = exports.byteSwap32 = exports.byteSwapIfBE = exports.byteSwap = exports.isLE = exports.rotl = exports.rotr = exports.createView = exports.u32 = exports.u8 = exports.isBytes = void 0;\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nconst crypto_1 = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/crypto.js\");\nconst _assert_js_1 = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\");\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nexports.isBytes = isBytes;\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexports.u8 = u8;\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\nexports.u32 = u32;\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\nexports.createView = createView;\n// The rotate right (circular right shift) operation for uint32\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\nexports.rotr = rotr;\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nexports.rotl = rotl;\nexports.isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\nexports.byteSwap = byteSwap;\n// Conditionally byte swap if on a big-endian platform\nexports.byteSwapIfBE = exports.isLE ? (n) => n : (n) => (0, exports.byteSwap)(n);\n// In place byte swap for Uint32Array\nfunction byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = (0, exports.byteSwap)(arr[i]);\n }\n}\nexports.byteSwap32 = byteSwap32;\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n (0, _assert_js_1.bytes)(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexports.bytesToHex = bytesToHex;\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\nexports.hexToBytes = hexToBytes;\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\nexports.nextTick = nextTick;\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await (0, exports.nextTick)();\n ts += diff;\n }\n}\nexports.asyncLoop = asyncLoop;\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\nexports.utf8ToBytes = utf8ToBytes;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n (0, _assert_js_1.bytes)(data);\n return data;\n}\nexports.toBytes = toBytes;\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n (0, _assert_js_1.bytes)(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexports.concatBytes = concatBytes;\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexports.Hash = Hash;\nconst toStr = {}.toString;\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexports.checkOpts = checkOpts;\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexports.wrapConstructor = wrapConstructor;\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexports.wrapConstructorWithOpts = wrapConstructorWithOpts;\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexports.wrapXOFConstructorWithOpts = wrapXOFConstructorWithOpts;\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {\n return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\nexports.randomBytes = randomBytes;\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js?"); /***/ }), @@ -1178,7 +2357,7 @@ eval("\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.pbkdf2Sync = exports.pbkdf2 = void 0;\nconst pbkdf2_1 = __webpack_require__(/*! @noble/hashes/pbkdf2 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/pbkdf2.js\");\nconst sha256_1 = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js\");\nconst sha512_1 = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha512.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nasync function pbkdf2(password, salt, iterations, keylen, digest) {\n if (![\"sha256\", \"sha512\"].includes(digest)) {\n throw new Error(\"Only sha256 and sha512 are supported\");\n }\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, pbkdf2_1.pbkdf2Async)(digest === \"sha256\" ? sha256_1.sha256 : sha512_1.sha512, password, salt, {\n c: iterations,\n dkLen: keylen\n });\n}\nexports.pbkdf2 = pbkdf2;\nfunction pbkdf2Sync(password, salt, iterations, keylen, digest) {\n if (![\"sha256\", \"sha512\"].includes(digest)) {\n throw new Error(\"Only sha256 and sha512 are supported\");\n }\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, pbkdf2_1.pbkdf2)(digest === \"sha256\" ? sha256_1.sha256 : sha512_1.sha512, password, salt, {\n c: iterations,\n dkLen: keylen\n });\n}\nexports.pbkdf2Sync = pbkdf2Sync;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/pbkdf2.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.pbkdf2 = pbkdf2;\nexports.pbkdf2Sync = pbkdf2Sync;\nconst pbkdf2_1 = __webpack_require__(/*! @noble/hashes/pbkdf2 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/pbkdf2.js\");\nconst sha256_1 = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha256.js\");\nconst sha512_1 = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/sha512.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nasync function pbkdf2(password, salt, iterations, keylen, digest) {\n if (![\"sha256\", \"sha512\"].includes(digest)) {\n throw new Error(\"Only sha256 and sha512 are supported\");\n }\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, pbkdf2_1.pbkdf2Async)(digest === \"sha256\" ? sha256_1.sha256 : sha512_1.sha512, password, salt, {\n c: iterations,\n dkLen: keylen\n });\n}\nfunction pbkdf2Sync(password, salt, iterations, keylen, digest) {\n if (![\"sha256\", \"sha512\"].includes(digest)) {\n throw new Error(\"Only sha256 and sha512 are supported\");\n }\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, pbkdf2_1.pbkdf2)(digest === \"sha256\" ? sha256_1.sha256 : sha512_1.sha512, password, salt, {\n c: iterations,\n dkLen: keylen\n });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/pbkdf2.js?"); /***/ }), @@ -1189,7 +2368,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.getRandomBytes = exports.getRandomBytesSync = void 0;\nconst utils_1 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nfunction getRandomBytesSync(bytes) {\n return (0, utils_1.randomBytes)(bytes);\n}\nexports.getRandomBytesSync = getRandomBytesSync;\nasync function getRandomBytes(bytes) {\n return (0, utils_1.randomBytes)(bytes);\n}\nexports.getRandomBytes = getRandomBytes;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/random.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.getRandomBytesSync = getRandomBytesSync;\nexports.getRandomBytes = getRandomBytes;\nconst utils_1 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nfunction getRandomBytesSync(bytes) {\n return (0, utils_1.randomBytes)(bytes);\n}\nasync function getRandomBytes(bytes) {\n return (0, utils_1.randomBytes)(bytes);\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/random.js?"); /***/ }), @@ -1200,7 +2379,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.scryptSync = exports.scrypt = void 0;\nconst scrypt_1 = __webpack_require__(/*! @noble/hashes/scrypt */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/scrypt.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nasync function scrypt(password, salt, n, p, r, dkLen, onProgress) {\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, scrypt_1.scryptAsync)(password, salt, { N: n, r, p, dkLen, onProgress });\n}\nexports.scrypt = scrypt;\nfunction scryptSync(password, salt, n, p, r, dkLen, onProgress) {\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, scrypt_1.scrypt)(password, salt, { N: n, r, p, dkLen, onProgress });\n}\nexports.scryptSync = scryptSync;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/scrypt.js?"); +eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.scrypt = scrypt;\nexports.scryptSync = scryptSync;\nconst scrypt_1 = __webpack_require__(/*! @noble/hashes/scrypt */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/scrypt.js\");\nconst utils_js_1 = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/utils.js\");\nasync function scrypt(password, salt, n, p, r, dkLen, onProgress) {\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, scrypt_1.scryptAsync)(password, salt, { N: n, r, p, dkLen, onProgress });\n}\nfunction scryptSync(password, salt, n, p, r, dkLen, onProgress) {\n (0, utils_js_1.assertBytes)(password);\n (0, utils_js_1.assertBytes)(salt);\n return (0, scrypt_1.scrypt)(password, salt, { N: n, r, p, dkLen, onProgress });\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/scrypt.js?"); /***/ }), @@ -1222,7 +2401,7 @@ eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexpo /***/ (function(module, exports, __webpack_require__) { "use strict"; -eval("/* module decorator */ module = __webpack_require__.nmd(module);\n\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.crypto = exports.wrapHash = exports.equalsBytes = exports.hexToBytes = exports.bytesToUtf8 = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0;\nconst _assert_1 = __importDefault(__webpack_require__(/*! @noble/hashes/_assert */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\"));\nconst utils_1 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nconst assertBool = _assert_1.default.bool;\nexports.assertBool = assertBool;\nconst assertBytes = _assert_1.default.bytes;\nexports.assertBytes = assertBytes;\nvar utils_2 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nObject.defineProperty(exports, \"bytesToHex\", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } }));\nObject.defineProperty(exports, \"toHex\", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } }));\nObject.defineProperty(exports, \"concatBytes\", ({ enumerable: true, get: function () { return utils_2.concatBytes; } }));\nObject.defineProperty(exports, \"createView\", ({ enumerable: true, get: function () { return utils_2.createView; } }));\nObject.defineProperty(exports, \"utf8ToBytes\", ({ enumerable: true, get: function () { return utils_2.utf8ToBytes; } }));\n// buf.toString('utf8') -> bytesToUtf8(buf)\nfunction bytesToUtf8(data) {\n if (!(data instanceof Uint8Array)) {\n throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);\n }\n return new TextDecoder().decode(data);\n}\nexports.bytesToUtf8 = bytesToUtf8;\nfunction hexToBytes(data) {\n const sliced = data.startsWith(\"0x\") ? data.substring(2) : data;\n return (0, utils_1.hexToBytes)(sliced);\n}\nexports.hexToBytes = hexToBytes;\n// buf.equals(buf2) -> equalsBytes(buf, buf2)\nfunction equalsBytes(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\nexports.equalsBytes = equalsBytes;\n// Internal utils\nfunction wrapHash(hash) {\n return (msg) => {\n _assert_1.default.bytes(msg);\n return hash(msg);\n };\n}\nexports.wrapHash = wrapHash;\n// TODO(v3): switch away from node crypto, remove this unnecessary variable.\nexports.crypto = (() => {\n const webCrypto = typeof globalThis === \"object\" && \"crypto\" in globalThis ? globalThis.crypto : undefined;\n const nodeRequire = true &&\n typeof module.require === \"function\" &&\n module.require.bind(module);\n return {\n node: nodeRequire && !webCrypto ? nodeRequire(\"crypto\") : undefined,\n web: webCrypto\n };\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/utils.js?"); +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.crypto = exports.utf8ToBytes = exports.createView = exports.concatBytes = exports.toHex = exports.bytesToHex = exports.assertBytes = exports.assertBool = void 0;\nexports.bytesToUtf8 = bytesToUtf8;\nexports.hexToBytes = hexToBytes;\nexports.equalsBytes = equalsBytes;\nexports.wrapHash = wrapHash;\nconst _assert_1 = __importDefault(__webpack_require__(/*! @noble/hashes/_assert */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/_assert.js\"));\nconst utils_1 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nconst assertBool = _assert_1.default.bool;\nexports.assertBool = assertBool;\nconst assertBytes = _assert_1.default.bytes;\nexports.assertBytes = assertBytes;\nvar utils_2 = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/utils.js\");\nObject.defineProperty(exports, \"bytesToHex\", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } }));\nObject.defineProperty(exports, \"toHex\", ({ enumerable: true, get: function () { return utils_2.bytesToHex; } }));\nObject.defineProperty(exports, \"concatBytes\", ({ enumerable: true, get: function () { return utils_2.concatBytes; } }));\nObject.defineProperty(exports, \"createView\", ({ enumerable: true, get: function () { return utils_2.createView; } }));\nObject.defineProperty(exports, \"utf8ToBytes\", ({ enumerable: true, get: function () { return utils_2.utf8ToBytes; } }));\n// buf.toString('utf8') -> bytesToUtf8(buf)\nfunction bytesToUtf8(data) {\n if (!(data instanceof Uint8Array)) {\n throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);\n }\n return new TextDecoder().decode(data);\n}\nfunction hexToBytes(data) {\n const sliced = data.startsWith(\"0x\") ? data.substring(2) : data;\n return (0, utils_1.hexToBytes)(sliced);\n}\n// buf.equals(buf2) -> equalsBytes(buf, buf2)\nfunction equalsBytes(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n// Internal utils\nfunction wrapHash(hash) {\n return (msg) => {\n _assert_1.default.bytes(msg);\n return hash(msg);\n };\n}\n// TODO(v3): switch away from node crypto, remove this unnecessary variable.\nexports.crypto = (() => {\n const webCrypto = typeof globalThis === \"object\" && \"crypto\" in globalThis ? globalThis.crypto : undefined;\n const nodeRequire = true &&\n typeof module.require === \"function\" &&\n module.require.bind(module);\n return {\n node: nodeRequire && !webCrypto ? nodeRequire(\"crypto\") : undefined,\n web: webCrypto\n };\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/utils.js?"); /***/ }), @@ -1259,6 +2438,38 @@ eval("\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n /***/ }), +/***/ "./node_modules/events/events.js": +/*!***************************************!*\ + !*** ./node_modules/events/events.js ***! + \***************************************/ +/***/ ((module) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/events/events.js?"); + +/***/ }), + +/***/ "./node_modules/evp_bytestokey/index.js": +/*!**********************************************!*\ + !*** ./node_modules/evp_bytestokey/index.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar MD5 = __webpack_require__(/*! md5.js */ \"./node_modules/md5.js/index.js\")\n\n/* eslint-disable camelcase */\nfunction EVP_BytesToKey (password, salt, keyBits, ivLen) {\n if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')\n if (salt) {\n if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')\n if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')\n }\n\n var keyLen = keyBits / 8\n var key = Buffer.alloc(keyLen)\n var iv = Buffer.alloc(ivLen || 0)\n var tmp = Buffer.alloc(0)\n\n while (keyLen > 0 || ivLen > 0) {\n var hash = new MD5()\n hash.update(tmp)\n hash.update(password)\n if (salt) hash.update(salt)\n tmp = hash.digest()\n\n var used = 0\n\n if (keyLen > 0) {\n var keyStart = key.length - keyLen\n used = Math.min(keyLen, tmp.length)\n tmp.copy(key, keyStart, 0, used)\n keyLen -= used\n }\n\n if (used < tmp.length && ivLen > 0) {\n var ivStart = iv.length - ivLen\n var length = Math.min(ivLen, tmp.length - used)\n tmp.copy(iv, ivStart, used, used + length)\n ivLen -= length\n }\n }\n\n tmp.fill(0)\n return { key: key, iv: iv }\n}\n\nmodule.exports = EVP_BytesToKey\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/evp_bytestokey/index.js?"); + +/***/ }), + +/***/ "./node_modules/hash-base/index.js": +/*!*****************************************!*\ + !*** ./node_modules/hash-base/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar Transform = (__webpack_require__(/*! stream */ \"./node_modules/stream-browserify/index.js\").Transform)\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\n\nfunction HashBase (blockSize) {\n Transform.call(this)\n\n this._block = Buffer.allocUnsafe(blockSize)\n this._blockSize = blockSize\n this._blockOffset = 0\n this._length = [0, 0, 0, 0]\n\n this._finalized = false\n}\n\ninherits(HashBase, Transform)\n\nHashBase.prototype._transform = function (chunk, encoding, callback) {\n var error = null\n try {\n this.update(chunk, encoding)\n } catch (err) {\n error = err\n }\n\n callback(error)\n}\n\nHashBase.prototype._flush = function (callback) {\n var error = null\n try {\n this.push(this.digest())\n } catch (err) {\n error = err\n }\n\n callback(error)\n}\n\nvar useUint8Array = typeof Uint8Array !== 'undefined'\nvar useArrayBuffer = typeof ArrayBuffer !== 'undefined' &&\n typeof Uint8Array !== 'undefined' &&\n ArrayBuffer.isView &&\n (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT)\n\nfunction toBuffer (data, encoding) {\n // No need to do anything for exact instance\n // This is only valid when safe-buffer.Buffer === buffer.Buffer, i.e. when Buffer.from/Buffer.alloc existed\n if (data instanceof Buffer) return data\n\n // Convert strings to Buffer\n if (typeof data === 'string') return Buffer.from(data, encoding)\n\n /*\n * Wrap any TypedArray instances and DataViews\n * Makes sense only on engines with full TypedArray support -- let Buffer detect that\n */\n if (useArrayBuffer && ArrayBuffer.isView(data)) {\n if (data.byteLength === 0) return Buffer.alloc(0) // Bug in Node.js <6.3.1, which treats this as out-of-bounds\n var res = Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n // Recheck result size, as offset/length doesn't work on Node.js <5.10\n // We just go to Uint8Array case if this fails\n if (res.byteLength === data.byteLength) return res\n }\n\n /*\n * Uint8Array in engines where Buffer.from might not work with ArrayBuffer, just copy over\n * Doesn't make sense with other TypedArray instances\n */\n if (useUint8Array && data instanceof Uint8Array) return Buffer.from(data)\n\n /*\n * Old Buffer polyfill on an engine that doesn't have TypedArray support\n * Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed\n * Convert to our current Buffer implementation\n */\n if (\n Buffer.isBuffer(data) &&\n data.constructor &&\n typeof data.constructor.isBuffer === 'function' &&\n data.constructor.isBuffer(data)\n ) {\n return Buffer.from(data)\n }\n\n throw new TypeError('The \"data\" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')\n}\n\nHashBase.prototype.update = function (data, encoding) {\n if (this._finalized) throw new Error('Digest already called')\n\n data = toBuffer(data, encoding) // asserts correct input type\n\n // consume data\n var block = this._block\n var offset = 0\n while (this._blockOffset + data.length - offset >= this._blockSize) {\n for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]\n this._update()\n this._blockOffset = 0\n }\n while (offset < data.length) block[this._blockOffset++] = data[offset++]\n\n // update length\n for (var j = 0, carry = data.length * 8; carry > 0; ++j) {\n this._length[j] += carry\n carry = (this._length[j] / 0x0100000000) | 0\n if (carry > 0) this._length[j] -= 0x0100000000 * carry\n }\n\n return this\n}\n\nHashBase.prototype._update = function () {\n throw new Error('_update is not implemented')\n}\n\nHashBase.prototype.digest = function (encoding) {\n if (this._finalized) throw new Error('Digest already called')\n this._finalized = true\n\n var digest = this._digest()\n if (encoding !== undefined) digest = digest.toString(encoding)\n\n // reset state\n this._block.fill(0)\n this._blockOffset = 0\n for (var i = 0; i < 4; ++i) this._length[i] = 0\n\n return digest\n}\n\nHashBase.prototype._digest = function () {\n throw new Error('_digest is not implemented')\n}\n\nmodule.exports = HashBase\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/hash-base/index.js?"); + +/***/ }), + /***/ "./node_modules/hash.js/lib/hash.js": /*!******************************************!*\ !*** ./node_modules/hash.js/lib/hash.js ***! @@ -1406,7 +2617,28 @@ eval("module.exports = function (max) {\n\n if (!max) throw Error('hashlru must \**********************************************/ /***/ ((module, exports, __webpack_require__) => { -eval("var __WEBPACK_AMD_DEFINE_RESULT__;/*\n * [hi-base32]{@link https://github.com/emn178/hi-base32}\n *\n * @version 0.5.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var root = typeof window === 'object' ? window : {};\n var NODE_JS = !root.HI_BASE32_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n }\n var COMMON_JS = !root.HI_BASE32_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var BASE32_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('');\n var BASE32_DECODE_CHAR = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16,\n 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,\n 'Z': 25, '2': 26, '3': 27, '4': 28, '5': 29, '6': 30, '7': 31\n };\n\n var blocks = [0, 0, 0, 0, 0, 0, 0, 0];\n\n var throwInvalidUtf8 = function (position, partial) {\n if (partial.length > 10) {\n partial = '...' + partial.substr(-10);\n }\n var err = new Error('Decoded data is not valid UTF-8.'\n + ' Maybe try base32.decode.asBytes()?'\n + ' Partial data after reading ' + position + ' bytes: ' + partial + ' <-');\n err.position = position;\n throw err;\n };\n\n var toUtf8String = function (bytes) {\n var str = '', length = bytes.length, i = 0, followingChars = 0, b, c;\n while (i < length) {\n b = bytes[i++];\n if (b <= 0x7F) {\n str += String.fromCharCode(b);\n continue;\n } else if (b > 0xBF && b <= 0xDF) {\n c = b & 0x1F;\n followingChars = 1;\n } else if (b <= 0xEF) {\n c = b & 0x0F;\n followingChars = 2;\n } else if (b <= 0xF7) {\n c = b & 0x07;\n followingChars = 3;\n } else {\n throwInvalidUtf8(i, str);\n }\n\n for (var j = 0; j < followingChars; ++j) {\n b = bytes[i++];\n if (b < 0x80 || b > 0xBF) {\n throwInvalidUtf8(i, str);\n }\n c <<= 6;\n c += b & 0x3F;\n }\n if (c >= 0xD800 && c <= 0xDFFF) {\n throwInvalidUtf8(i, str);\n }\n if (c > 0x10FFFF) {\n throwInvalidUtf8(i, str);\n }\n\n if (c <= 0xFFFF) {\n str += String.fromCharCode(c);\n } else {\n c -= 0x10000;\n str += String.fromCharCode((c >> 10) + 0xD800);\n str += String.fromCharCode((c & 0x3FF) + 0xDC00);\n }\n }\n return str;\n };\n\n var decodeAsBytes = function (base32Str) {\n if (base32Str === '') {\n return [];\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n base32Str = base32Str.replace(/=/g, '');\n var v1, v2, v3, v4, v5, v6, v7, v8, bytes = [], index = 0, length = base32Str.length;\n\n // 4 char to 3 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n bytes[index++] = (v7 << 5 | v8) & 255;\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n }\n return bytes;\n };\n\n var encodeAscii = function (str) {\n var v1, v2, v3, v4, v5, base32Str = '', length = str.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i++);\n v5 = str.charCodeAt(i++);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encodeUtf8 = function (str) {\n var v1, v2, v3, v4, v5, code, end = false, base32Str = '',\n index = 0, i, start = 0, bytes = 0, length = str.length;\n if (str === '') {\n return base32Str;\n }\n do {\n blocks[0] = blocks[5];\n blocks[1] = blocks[6];\n blocks[2] = blocks[7];\n for (i = start; index < length && i < 5; ++index) {\n code = str.charCodeAt(index);\n if (code < 0x80) {\n blocks[i++] = code;\n } else if (code < 0x800) {\n blocks[i++] = 0xc0 | (code >> 6);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i++] = 0xe0 | (code >> 12);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++index) & 0x3ff));\n blocks[i++] = 0xf0 | (code >> 18);\n blocks[i++] = 0x80 | ((code >> 12) & 0x3f);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n }\n }\n bytes += i - start;\n start = i - 5;\n if (index === length) {\n ++index;\n }\n if (index > length && i < 6) {\n end = true;\n }\n v1 = blocks[0];\n if (i > 4) {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n v5 = blocks[4];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n } else if (i === 1) {\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (i === 2) {\n v2 = blocks[1];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (i === 3) {\n v2 = blocks[1];\n v3 = blocks[2];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n } while (!end);\n return base32Str;\n };\n\n var encodeBytes = function (bytes) {\n var v1, v2, v3, v4, v5, base32Str = '', length = bytes.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i++];\n v5 = bytes[i++];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = bytes[i++];\n v2 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encode = function (input, asciiOnly) {\n var notString = typeof(input) !== 'string';\n if (notString && input.constructor === ArrayBuffer) {\n input = new Uint8Array(input);\n }\n if (notString) {\n return encodeBytes(input);\n } else if (asciiOnly) {\n return encodeAscii(input);\n } else {\n return encodeUtf8(input);\n }\n };\n\n var decode = function (base32Str, asciiOnly) {\n if (!asciiOnly) {\n return toUtf8String(decodeAsBytes(base32Str));\n }\n if (base32Str === '') {\n return '';\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n var v1, v2, v3, v4, v5, v6, v7, v8, str = '', length = base32Str.indexOf('=');\n if (length === -1) {\n length = base32Str.length;\n }\n\n // 8 char to 5 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255) +\n String.fromCharCode((v7 << 5 | v8) & 255);\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255);\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255);\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255);\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255);\n }\n return str;\n };\n\n var exports = {\n encode: encode,\n decode: decode\n };\n decode.asBytes = decodeAsBytes;\n\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n root.base32 = exports;\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {\n return exports;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/hi-base32/src/base32.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\nvar __WEBPACK_AMD_DEFINE_RESULT__;/*\n * [hi-base32]{@link https://github.com/emn178/hi-base32}\n *\n * @version 0.5.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2018\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var root = typeof window === 'object' ? window : {};\n var NODE_JS = !root.HI_BASE32_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n }\n var COMMON_JS = !root.HI_BASE32_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var BASE32_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('');\n var BASE32_DECODE_CHAR = {\n 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8,\n 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16,\n 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24,\n 'Z': 25, '2': 26, '3': 27, '4': 28, '5': 29, '6': 30, '7': 31\n };\n\n var blocks = [0, 0, 0, 0, 0, 0, 0, 0];\n\n var throwInvalidUtf8 = function (position, partial) {\n if (partial.length > 10) {\n partial = '...' + partial.substr(-10);\n }\n var err = new Error('Decoded data is not valid UTF-8.'\n + ' Maybe try base32.decode.asBytes()?'\n + ' Partial data after reading ' + position + ' bytes: ' + partial + ' <-');\n err.position = position;\n throw err;\n };\n\n var toUtf8String = function (bytes) {\n var str = '', length = bytes.length, i = 0, followingChars = 0, b, c;\n while (i < length) {\n b = bytes[i++];\n if (b <= 0x7F) {\n str += String.fromCharCode(b);\n continue;\n } else if (b > 0xBF && b <= 0xDF) {\n c = b & 0x1F;\n followingChars = 1;\n } else if (b <= 0xEF) {\n c = b & 0x0F;\n followingChars = 2;\n } else if (b <= 0xF7) {\n c = b & 0x07;\n followingChars = 3;\n } else {\n throwInvalidUtf8(i, str);\n }\n\n for (var j = 0; j < followingChars; ++j) {\n b = bytes[i++];\n if (b < 0x80 || b > 0xBF) {\n throwInvalidUtf8(i, str);\n }\n c <<= 6;\n c += b & 0x3F;\n }\n if (c >= 0xD800 && c <= 0xDFFF) {\n throwInvalidUtf8(i, str);\n }\n if (c > 0x10FFFF) {\n throwInvalidUtf8(i, str);\n }\n\n if (c <= 0xFFFF) {\n str += String.fromCharCode(c);\n } else {\n c -= 0x10000;\n str += String.fromCharCode((c >> 10) + 0xD800);\n str += String.fromCharCode((c & 0x3FF) + 0xDC00);\n }\n }\n return str;\n };\n\n var decodeAsBytes = function (base32Str) {\n if (base32Str === '') {\n return [];\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n base32Str = base32Str.replace(/=/g, '');\n var v1, v2, v3, v4, v5, v6, v7, v8, bytes = [], index = 0, length = base32Str.length;\n\n // 4 char to 3 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n bytes[index++] = (v7 << 5 | v8) & 255;\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n bytes[index++] = (v1 << 3 | v2 >>> 2) & 255;\n bytes[index++] = (v2 << 6 | v3 << 1 | v4 >>> 4) & 255;\n bytes[index++] = (v4 << 4 | v5 >>> 1) & 255;\n bytes[index++] = (v5 << 7 | v6 << 2 | v7 >>> 3) & 255;\n }\n return bytes;\n };\n\n var encodeAscii = function (str) {\n var v1, v2, v3, v4, v5, base32Str = '', length = str.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i++);\n v5 = str.charCodeAt(i++);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = str.charCodeAt(i++);\n v2 = str.charCodeAt(i++);\n v3 = str.charCodeAt(i++);\n v4 = str.charCodeAt(i);\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encodeUtf8 = function (str) {\n var v1, v2, v3, v4, v5, code, end = false, base32Str = '',\n index = 0, i, start = 0, bytes = 0, length = str.length;\n if (str === '') {\n return base32Str;\n }\n do {\n blocks[0] = blocks[5];\n blocks[1] = blocks[6];\n blocks[2] = blocks[7];\n for (i = start; index < length && i < 5; ++index) {\n code = str.charCodeAt(index);\n if (code < 0x80) {\n blocks[i++] = code;\n } else if (code < 0x800) {\n blocks[i++] = 0xc0 | (code >> 6);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i++] = 0xe0 | (code >> 12);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++index) & 0x3ff));\n blocks[i++] = 0xf0 | (code >> 18);\n blocks[i++] = 0x80 | ((code >> 12) & 0x3f);\n blocks[i++] = 0x80 | ((code >> 6) & 0x3f);\n blocks[i++] = 0x80 | (code & 0x3f);\n }\n }\n bytes += i - start;\n start = i - 5;\n if (index === length) {\n ++index;\n }\n if (index > length && i < 6) {\n end = true;\n }\n v1 = blocks[0];\n if (i > 4) {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n v5 = blocks[4];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n } else if (i === 1) {\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (i === 2) {\n v2 = blocks[1];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (i === 3) {\n v2 = blocks[1];\n v3 = blocks[2];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else {\n v2 = blocks[1];\n v3 = blocks[2];\n v4 = blocks[3];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n } while (!end);\n return base32Str;\n };\n\n var encodeBytes = function (bytes) {\n var v1, v2, v3, v4, v5, base32Str = '', length = bytes.length;\n for (var i = 0, count = parseInt(length / 5) * 5; i < count;) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i++];\n v5 = bytes[i++];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3 | v5 >>> 5) & 31] +\n BASE32_ENCODE_CHAR[v5 & 31];\n }\n\n // remain char\n var remain = length - count;\n if (remain === 1) {\n v1 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2) & 31] +\n '======';\n } else if (remain === 2) {\n v1 = bytes[i++];\n v2 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4) & 31] +\n '====';\n } else if (remain === 3) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1) & 31] +\n '===';\n } else if (remain === 4) {\n v1 = bytes[i++];\n v2 = bytes[i++];\n v3 = bytes[i++];\n v4 = bytes[i];\n base32Str += BASE32_ENCODE_CHAR[v1 >>> 3] +\n BASE32_ENCODE_CHAR[(v1 << 2 | v2 >>> 6) & 31] +\n BASE32_ENCODE_CHAR[(v2 >>> 1) & 31] +\n BASE32_ENCODE_CHAR[(v2 << 4 | v3 >>> 4) & 31] +\n BASE32_ENCODE_CHAR[(v3 << 1 | v4 >>> 7) & 31] +\n BASE32_ENCODE_CHAR[(v4 >>> 2) & 31] +\n BASE32_ENCODE_CHAR[(v4 << 3) & 31] +\n '=';\n }\n return base32Str;\n };\n\n var encode = function (input, asciiOnly) {\n var notString = typeof(input) !== 'string';\n if (notString && input.constructor === ArrayBuffer) {\n input = new Uint8Array(input);\n }\n if (notString) {\n return encodeBytes(input);\n } else if (asciiOnly) {\n return encodeAscii(input);\n } else {\n return encodeUtf8(input);\n }\n };\n\n var decode = function (base32Str, asciiOnly) {\n if (!asciiOnly) {\n return toUtf8String(decodeAsBytes(base32Str));\n }\n if (base32Str === '') {\n return '';\n } else if (!/^[A-Z2-7=]+$/.test(base32Str)) {\n throw new Error('Invalid base32 characters');\n }\n var v1, v2, v3, v4, v5, v6, v7, v8, str = '', length = base32Str.indexOf('=');\n if (length === -1) {\n length = base32Str.length;\n }\n\n // 8 char to 5 bytes\n for (var i = 0, count = length >> 3 << 3; i < count;) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v8 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255) +\n String.fromCharCode((v7 << 5 | v8) & 255);\n }\n\n // remain bytes\n var remain = length - count;\n if (remain === 2) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255);\n } else if (remain === 4) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255);\n } else if (remain === 5) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255);\n } else if (remain === 7) {\n v1 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v2 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v3 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v4 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v5 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v6 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n v7 = BASE32_DECODE_CHAR[base32Str.charAt(i++)];\n str += String.fromCharCode((v1 << 3 | v2 >>> 2) & 255) +\n String.fromCharCode((v2 << 6 | v3 << 1 | v4 >>> 4) & 255) +\n String.fromCharCode((v4 << 4 | v5 >>> 1) & 255) +\n String.fromCharCode((v5 << 7 | v6 << 2 | v7 >>> 3) & 255);\n }\n return str;\n };\n\n var exports = {\n encode: encode,\n decode: decode\n };\n decode.asBytes = decodeAsBytes;\n\n if (COMMON_JS) {\n module.exports = exports;\n } else {\n root.base32 = exports;\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {\n return exports;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/hi-base32/src/base32.js?"); + +/***/ }), + +/***/ "./node_modules/hmac-drbg/lib/hmac-drbg.js": +/*!*************************************************!*\ + !*** ./node_modules/hmac-drbg/lib/hmac-drbg.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar hash = __webpack_require__(/*! hash.js */ \"./node_modules/hash.js/lib/hash.js\");\nvar utils = __webpack_require__(/*! minimalistic-crypto-utils */ \"./node_modules/minimalistic-crypto-utils/lib/utils.js\");\nvar assert = __webpack_require__(/*! minimalistic-assert */ \"./node_modules/minimalistic-assert/index.js\");\n\nfunction HmacDRBG(options) {\n if (!(this instanceof HmacDRBG))\n return new HmacDRBG(options);\n this.hash = options.hash;\n this.predResist = !!options.predResist;\n\n this.outLen = this.hash.outSize;\n this.minEntropy = options.minEntropy || this.hash.hmacStrength;\n\n this._reseed = null;\n this.reseedInterval = null;\n this.K = null;\n this.V = null;\n\n var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');\n var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');\n var pers = utils.toArray(options.pers, options.persEnc || 'hex');\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n this._init(entropy, nonce, pers);\n}\nmodule.exports = HmacDRBG;\n\nHmacDRBG.prototype._init = function init(entropy, nonce, pers) {\n var seed = entropy.concat(nonce).concat(pers);\n\n this.K = new Array(this.outLen / 8);\n this.V = new Array(this.outLen / 8);\n for (var i = 0; i < this.V.length; i++) {\n this.K[i] = 0x00;\n this.V[i] = 0x01;\n }\n\n this._update(seed);\n this._reseed = 1;\n this.reseedInterval = 0x1000000000000; // 2^48\n};\n\nHmacDRBG.prototype._hmac = function hmac() {\n return new hash.hmac(this.hash, this.K);\n};\n\nHmacDRBG.prototype._update = function update(seed) {\n var kmac = this._hmac()\n .update(this.V)\n .update([ 0x00 ]);\n if (seed)\n kmac = kmac.update(seed);\n this.K = kmac.digest();\n this.V = this._hmac().update(this.V).digest();\n if (!seed)\n return;\n\n this.K = this._hmac()\n .update(this.V)\n .update([ 0x01 ])\n .update(seed)\n .digest();\n this.V = this._hmac().update(this.V).digest();\n};\n\nHmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {\n // Optional entropy enc\n if (typeof entropyEnc !== 'string') {\n addEnc = add;\n add = entropyEnc;\n entropyEnc = null;\n }\n\n entropy = utils.toArray(entropy, entropyEnc);\n add = utils.toArray(add, addEnc);\n\n assert(entropy.length >= (this.minEntropy / 8),\n 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');\n\n this._update(entropy.concat(add || []));\n this._reseed = 1;\n};\n\nHmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {\n if (this._reseed > this.reseedInterval)\n throw new Error('Reseed is required');\n\n // Optional encoding\n if (typeof enc !== 'string') {\n addEnc = add;\n add = enc;\n enc = null;\n }\n\n // Optional additional data\n if (add) {\n add = utils.toArray(add, addEnc || 'hex');\n this._update(add);\n }\n\n var temp = [];\n while (temp.length < len) {\n this.V = this._hmac().update(this.V).digest();\n temp = temp.concat(this.V);\n }\n\n var res = temp.slice(0, len);\n this._update(add);\n this._reseed++;\n return utils.encode(res, enc);\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/hmac-drbg/lib/hmac-drbg.js?"); + +/***/ }), + +/***/ "./node_modules/ieee754/index.js": +/*!***************************************!*\ + !*** ./node_modules/ieee754/index.js ***! + \***************************************/ +/***/ ((__unused_webpack_module, exports) => { + +eval("/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ieee754/index.js?"); /***/ }), @@ -1424,9 +2656,9 @@ eval("if (typeof Object.create === 'function') {\n // implementation from stand /*!*******************************************!*\ !*** ./node_modules/is-electron/index.js ***! \*******************************************/ -/***/ ((module) => { +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("// https://github.com/electron/electron/issues/2288\nfunction isElectron() {\n // Renderer process\n if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {\n return true;\n }\n\n // Main process\n if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {\n return true;\n }\n\n // Detect the user agent when the `nodeIntegration` option is set to false\n if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = isElectron;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/is-electron/index.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// https://github.com/electron/electron/issues/2288\nfunction isElectron() {\n // Renderer process\n if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {\n return true;\n }\n\n // Main process\n if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {\n return true;\n }\n\n // Detect the user agent when the `nodeIntegration` option is set to false\n if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {\n return true;\n }\n\n return false;\n}\n\nmodule.exports = isElectron;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/is-electron/index.js?"); /***/ }), @@ -1447,7 +2679,7 @@ eval("\n\nmodule.exports = value => {\n\tif (Object.prototype.toString.call(valu \******************************************/ /***/ ((module, exports, __webpack_require__) => { -eval("var __WEBPACK_AMD_DEFINE_RESULT__;/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.9.3\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2023\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n\n var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray\n ? function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n }\n : Array.isArray;\n\n var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))\n ? function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n }\n : ArrayBuffer.isView;\n\n // [message: string, isString: bool]\n var formatMessage = function (message) {\n var type = typeof message;\n if (type === 'string') {\n return [message, true];\n }\n if (type !== 'object' || message === null) {\n throw new Error(INPUT_ERROR);\n }\n if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n return [new Uint8Array(message), false];\n }\n if (!isArray(message) && !isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n return [message, false];\n }\n\n var empty = function (message) {\n return formatMessage(message)[0].length === 0;\n };\n\n var cloneArray = function (array) {\n var newArray = [];\n for (var i = 0; i < array.length; ++i) {\n newArray[i] = array[i];\n }\n return newArray;\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (empty(n) && empty(s)) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var result = formatMessage(message);\n message = result[0];\n var isString = result[1];\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (isString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var result = formatMessage(str);\n str = result[0];\n var isString = result[1];\n var bytes = 0, length = str.length;\n if (isString) {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n } else {\n bytes = length;\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = (w - bytes % w) % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n array[j] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return methods;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/js-sha3/src/sha3.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\nvar __WEBPACK_AMD_DEFINE_RESULT__;/**\n * [js-sha3]{@link https://github.com/emn178/js-sha3}\n *\n * @version 0.9.3\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2015-2023\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n 'use strict';\n\n var INPUT_ERROR = 'input is invalid type';\n var FINALIZE_ERROR = 'finalize already called';\n var WINDOW = typeof window === 'object';\n var root = WINDOW ? window : {};\n if (root.JS_SHA3_NO_WINDOW) {\n WINDOW = false;\n }\n var WEB_WORKER = !WINDOW && typeof self === 'object';\n var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n if (NODE_JS) {\n root = __webpack_require__.g;\n } else if (WEB_WORKER) {\n root = self;\n }\n var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && \"object\" === 'object' && module.exports;\n var AMD = true && __webpack_require__.amdO;\n var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n var HEX_CHARS = '0123456789abcdef'.split('');\n var SHAKE_PADDING = [31, 7936, 2031616, 520093696];\n var CSHAKE_PADDING = [4, 1024, 262144, 67108864];\n var KECCAK_PADDING = [1, 256, 65536, 16777216];\n var PADDING = [6, 1536, 393216, 100663296];\n var SHIFT = [0, 8, 16, 24];\n var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,\n 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,\n 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,\n 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,\n 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];\n var BITS = [224, 256, 384, 512];\n var SHAKE_BITS = [128, 256];\n var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array', 'digest'];\n var CSHAKE_BYTEPAD = {\n '128': 168,\n '256': 136\n };\n\n\n var isArray = root.JS_SHA3_NO_NODE_JS || !Array.isArray\n ? function (obj) {\n return Object.prototype.toString.call(obj) === '[object Array]';\n }\n : Array.isArray;\n\n var isView = (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView))\n ? function (obj) {\n return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n }\n : ArrayBuffer.isView;\n\n // [message: string, isString: bool]\n var formatMessage = function (message) {\n var type = typeof message;\n if (type === 'string') {\n return [message, true];\n }\n if (type !== 'object' || message === null) {\n throw new Error(INPUT_ERROR);\n }\n if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n return [new Uint8Array(message), false];\n }\n if (!isArray(message) && !isView(message)) {\n throw new Error(INPUT_ERROR);\n }\n return [message, false];\n }\n\n var empty = function (message) {\n return formatMessage(message)[0].length === 0;\n };\n\n var cloneArray = function (array) {\n var newArray = [];\n for (var i = 0; i < array.length; ++i) {\n newArray[i] = array[i];\n }\n return newArray;\n }\n\n var createOutputMethod = function (bits, padding, outputType) {\n return function (message) {\n return new Keccak(bits, padding, bits).update(message)[outputType]();\n };\n };\n\n var createShakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits) {\n return new Keccak(bits, padding, outputBits).update(message)[outputType]();\n };\n };\n\n var createCshakeOutputMethod = function (bits, padding, outputType) {\n return function (message, outputBits, n, s) {\n return methods['cshake' + bits].update(message, outputBits, n, s)[outputType]();\n };\n };\n\n var createKmacOutputMethod = function (bits, padding, outputType) {\n return function (key, message, outputBits, s) {\n return methods['kmac' + bits].update(key, message, outputBits, s)[outputType]();\n };\n };\n\n var createOutputMethods = function (method, createMethod, bits, padding) {\n for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n var type = OUTPUT_TYPES[i];\n method[type] = createMethod(bits, padding, type);\n }\n return method;\n };\n\n var createMethod = function (bits, padding) {\n var method = createOutputMethod(bits, padding, 'hex');\n method.create = function () {\n return new Keccak(bits, padding, bits);\n };\n method.update = function (message) {\n return method.create().update(message);\n };\n return createOutputMethods(method, createOutputMethod, bits, padding);\n };\n\n var createShakeMethod = function (bits, padding) {\n var method = createShakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits) {\n return new Keccak(bits, padding, outputBits);\n };\n method.update = function (message, outputBits) {\n return method.create(outputBits).update(message);\n };\n return createOutputMethods(method, createShakeOutputMethod, bits, padding);\n };\n\n var createCshakeMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createCshakeOutputMethod(bits, padding, 'hex');\n method.create = function (outputBits, n, s) {\n if (empty(n) && empty(s)) {\n return methods['shake' + bits].create(outputBits);\n } else {\n return new Keccak(bits, padding, outputBits).bytepad([n, s], w);\n }\n };\n method.update = function (message, outputBits, n, s) {\n return method.create(outputBits, n, s).update(message);\n };\n return createOutputMethods(method, createCshakeOutputMethod, bits, padding);\n };\n\n var createKmacMethod = function (bits, padding) {\n var w = CSHAKE_BYTEPAD[bits];\n var method = createKmacOutputMethod(bits, padding, 'hex');\n method.create = function (key, outputBits, s) {\n return new Kmac(bits, padding, outputBits).bytepad(['KMAC', s], w).bytepad([key], w);\n };\n method.update = function (key, message, outputBits, s) {\n return method.create(key, outputBits, s).update(message);\n };\n return createOutputMethods(method, createKmacOutputMethod, bits, padding);\n };\n\n var algorithms = [\n { name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod },\n { name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod },\n { name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod },\n { name: 'cshake', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod },\n { name: 'kmac', padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod }\n ];\n\n var methods = {}, methodNames = [];\n\n for (var i = 0; i < algorithms.length; ++i) {\n var algorithm = algorithms[i];\n var bits = algorithm.bits;\n for (var j = 0; j < bits.length; ++j) {\n var methodName = algorithm.name + '_' + bits[j];\n methodNames.push(methodName);\n methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);\n if (algorithm.name !== 'sha3') {\n var newMethodName = algorithm.name + bits[j];\n methodNames.push(newMethodName);\n methods[newMethodName] = methods[methodName];\n }\n }\n }\n\n function Keccak(bits, padding, outputBits) {\n this.blocks = [];\n this.s = [];\n this.padding = padding;\n this.outputBits = outputBits;\n this.reset = true;\n this.finalized = false;\n this.block = 0;\n this.start = 0;\n this.blockCount = (1600 - (bits << 1)) >> 5;\n this.byteCount = this.blockCount << 2;\n this.outputBlocks = outputBits >> 5;\n this.extraBytes = (outputBits & 31) >> 3;\n\n for (var i = 0; i < 50; ++i) {\n this.s[i] = 0;\n }\n }\n\n Keccak.prototype.update = function (message) {\n if (this.finalized) {\n throw new Error(FINALIZE_ERROR);\n }\n var result = formatMessage(message);\n message = result[0];\n var isString = result[1];\n var blocks = this.blocks, byteCount = this.byteCount, length = message.length,\n blockCount = this.blockCount, index = 0, s = this.s, i, code;\n\n while (index < length) {\n if (this.reset) {\n this.reset = false;\n blocks[0] = this.block;\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n if (isString) {\n for (i = this.start; index < length && i < byteCount; ++index) {\n code = message.charCodeAt(index);\n if (code < 0x80) {\n blocks[i >> 2] |= code << SHIFT[i++ & 3];\n } else if (code < 0x800) {\n blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else if (code < 0xd800 || code >= 0xe000) {\n blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];\n blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n }\n }\n } else {\n for (i = this.start; index < length && i < byteCount; ++index) {\n blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];\n }\n }\n this.lastByteIndex = i;\n if (i >= byteCount) {\n this.start = i - byteCount;\n this.block = blocks[blockCount];\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n this.reset = true;\n } else {\n this.start = i;\n }\n }\n return this;\n };\n\n Keccak.prototype.encode = function (x, right) {\n var o = x & 255, n = 1;\n var bytes = [o];\n x = x >> 8;\n o = x & 255;\n while (o > 0) {\n bytes.unshift(o);\n x = x >> 8;\n o = x & 255;\n ++n;\n }\n if (right) {\n bytes.push(n);\n } else {\n bytes.unshift(n);\n }\n this.update(bytes);\n return bytes.length;\n };\n\n Keccak.prototype.encodeString = function (str) {\n var result = formatMessage(str);\n str = result[0];\n var isString = result[1];\n var bytes = 0, length = str.length;\n if (isString) {\n for (var i = 0; i < str.length; ++i) {\n var code = str.charCodeAt(i);\n if (code < 0x80) {\n bytes += 1;\n } else if (code < 0x800) {\n bytes += 2;\n } else if (code < 0xd800 || code >= 0xe000) {\n bytes += 3;\n } else {\n code = 0x10000 + (((code & 0x3ff) << 10) | (str.charCodeAt(++i) & 0x3ff));\n bytes += 4;\n }\n }\n } else {\n bytes = length;\n }\n bytes += this.encode(bytes * 8);\n this.update(str);\n return bytes;\n };\n\n Keccak.prototype.bytepad = function (strs, w) {\n var bytes = this.encode(w);\n for (var i = 0; i < strs.length; ++i) {\n bytes += this.encodeString(strs[i]);\n }\n var paddingBytes = (w - bytes % w) % w;\n var zeros = [];\n zeros.length = paddingBytes;\n this.update(zeros);\n return this;\n };\n\n Keccak.prototype.finalize = function () {\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;\n blocks[i >> 2] |= this.padding[i & 3];\n if (this.lastByteIndex === this.byteCount) {\n blocks[0] = blocks[blockCount];\n for (i = 1; i < blockCount + 1; ++i) {\n blocks[i] = 0;\n }\n }\n blocks[blockCount - 1] |= 0x80000000;\n for (i = 0; i < blockCount; ++i) {\n s[i] ^= blocks[i];\n }\n f(s);\n };\n\n Keccak.prototype.toString = Keccak.prototype.hex = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var hex = '', block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +\n HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +\n HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +\n HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n i = 0;\n }\n }\n if (extraBytes) {\n block = s[i];\n hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];\n if (extraBytes > 1) {\n hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];\n }\n if (extraBytes > 2) {\n hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];\n }\n }\n return hex;\n };\n\n Keccak.prototype.arrayBuffer = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var bytes = this.outputBits >> 3;\n var buffer;\n if (extraBytes) {\n buffer = new ArrayBuffer((outputBlocks + 1) << 2);\n } else {\n buffer = new ArrayBuffer(bytes);\n }\n var array = new Uint32Array(buffer);\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n array[j] = s[i];\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n array[j] = s[i];\n buffer = buffer.slice(0, bytes);\n }\n return buffer;\n };\n\n Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;\n\n Keccak.prototype.digest = Keccak.prototype.array = function () {\n this.finalize();\n\n var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,\n extraBytes = this.extraBytes, i = 0, j = 0;\n var array = [], offset, block;\n while (j < outputBlocks) {\n for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n array[offset + 1] = (block >> 8) & 0xFF;\n array[offset + 2] = (block >> 16) & 0xFF;\n array[offset + 3] = (block >> 24) & 0xFF;\n }\n if (j % blockCount === 0) {\n s = cloneArray(s);\n f(s);\n }\n }\n if (extraBytes) {\n offset = j << 2;\n block = s[i];\n array[offset] = block & 0xFF;\n if (extraBytes > 1) {\n array[offset + 1] = (block >> 8) & 0xFF;\n }\n if (extraBytes > 2) {\n array[offset + 2] = (block >> 16) & 0xFF;\n }\n }\n return array;\n };\n\n function Kmac(bits, padding, outputBits) {\n Keccak.call(this, bits, padding, outputBits);\n }\n\n Kmac.prototype = new Keccak();\n\n Kmac.prototype.finalize = function () {\n this.encode(this.outputBits, true);\n return Keccak.prototype.finalize.call(this);\n };\n\n var f = function (s) {\n var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,\n b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,\n b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,\n b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;\n for (n = 0; n < 48; n += 2) {\n c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];\n c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];\n c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];\n c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];\n c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];\n c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];\n c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];\n c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];\n c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];\n c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];\n\n h = c8 ^ ((c2 << 1) | (c3 >>> 31));\n l = c9 ^ ((c3 << 1) | (c2 >>> 31));\n s[0] ^= h;\n s[1] ^= l;\n s[10] ^= h;\n s[11] ^= l;\n s[20] ^= h;\n s[21] ^= l;\n s[30] ^= h;\n s[31] ^= l;\n s[40] ^= h;\n s[41] ^= l;\n h = c0 ^ ((c4 << 1) | (c5 >>> 31));\n l = c1 ^ ((c5 << 1) | (c4 >>> 31));\n s[2] ^= h;\n s[3] ^= l;\n s[12] ^= h;\n s[13] ^= l;\n s[22] ^= h;\n s[23] ^= l;\n s[32] ^= h;\n s[33] ^= l;\n s[42] ^= h;\n s[43] ^= l;\n h = c2 ^ ((c6 << 1) | (c7 >>> 31));\n l = c3 ^ ((c7 << 1) | (c6 >>> 31));\n s[4] ^= h;\n s[5] ^= l;\n s[14] ^= h;\n s[15] ^= l;\n s[24] ^= h;\n s[25] ^= l;\n s[34] ^= h;\n s[35] ^= l;\n s[44] ^= h;\n s[45] ^= l;\n h = c4 ^ ((c8 << 1) | (c9 >>> 31));\n l = c5 ^ ((c9 << 1) | (c8 >>> 31));\n s[6] ^= h;\n s[7] ^= l;\n s[16] ^= h;\n s[17] ^= l;\n s[26] ^= h;\n s[27] ^= l;\n s[36] ^= h;\n s[37] ^= l;\n s[46] ^= h;\n s[47] ^= l;\n h = c6 ^ ((c0 << 1) | (c1 >>> 31));\n l = c7 ^ ((c1 << 1) | (c0 >>> 31));\n s[8] ^= h;\n s[9] ^= l;\n s[18] ^= h;\n s[19] ^= l;\n s[28] ^= h;\n s[29] ^= l;\n s[38] ^= h;\n s[39] ^= l;\n s[48] ^= h;\n s[49] ^= l;\n\n b0 = s[0];\n b1 = s[1];\n b32 = (s[11] << 4) | (s[10] >>> 28);\n b33 = (s[10] << 4) | (s[11] >>> 28);\n b14 = (s[20] << 3) | (s[21] >>> 29);\n b15 = (s[21] << 3) | (s[20] >>> 29);\n b46 = (s[31] << 9) | (s[30] >>> 23);\n b47 = (s[30] << 9) | (s[31] >>> 23);\n b28 = (s[40] << 18) | (s[41] >>> 14);\n b29 = (s[41] << 18) | (s[40] >>> 14);\n b20 = (s[2] << 1) | (s[3] >>> 31);\n b21 = (s[3] << 1) | (s[2] >>> 31);\n b2 = (s[13] << 12) | (s[12] >>> 20);\n b3 = (s[12] << 12) | (s[13] >>> 20);\n b34 = (s[22] << 10) | (s[23] >>> 22);\n b35 = (s[23] << 10) | (s[22] >>> 22);\n b16 = (s[33] << 13) | (s[32] >>> 19);\n b17 = (s[32] << 13) | (s[33] >>> 19);\n b48 = (s[42] << 2) | (s[43] >>> 30);\n b49 = (s[43] << 2) | (s[42] >>> 30);\n b40 = (s[5] << 30) | (s[4] >>> 2);\n b41 = (s[4] << 30) | (s[5] >>> 2);\n b22 = (s[14] << 6) | (s[15] >>> 26);\n b23 = (s[15] << 6) | (s[14] >>> 26);\n b4 = (s[25] << 11) | (s[24] >>> 21);\n b5 = (s[24] << 11) | (s[25] >>> 21);\n b36 = (s[34] << 15) | (s[35] >>> 17);\n b37 = (s[35] << 15) | (s[34] >>> 17);\n b18 = (s[45] << 29) | (s[44] >>> 3);\n b19 = (s[44] << 29) | (s[45] >>> 3);\n b10 = (s[6] << 28) | (s[7] >>> 4);\n b11 = (s[7] << 28) | (s[6] >>> 4);\n b42 = (s[17] << 23) | (s[16] >>> 9);\n b43 = (s[16] << 23) | (s[17] >>> 9);\n b24 = (s[26] << 25) | (s[27] >>> 7);\n b25 = (s[27] << 25) | (s[26] >>> 7);\n b6 = (s[36] << 21) | (s[37] >>> 11);\n b7 = (s[37] << 21) | (s[36] >>> 11);\n b38 = (s[47] << 24) | (s[46] >>> 8);\n b39 = (s[46] << 24) | (s[47] >>> 8);\n b30 = (s[8] << 27) | (s[9] >>> 5);\n b31 = (s[9] << 27) | (s[8] >>> 5);\n b12 = (s[18] << 20) | (s[19] >>> 12);\n b13 = (s[19] << 20) | (s[18] >>> 12);\n b44 = (s[29] << 7) | (s[28] >>> 25);\n b45 = (s[28] << 7) | (s[29] >>> 25);\n b26 = (s[38] << 8) | (s[39] >>> 24);\n b27 = (s[39] << 8) | (s[38] >>> 24);\n b8 = (s[48] << 14) | (s[49] >>> 18);\n b9 = (s[49] << 14) | (s[48] >>> 18);\n\n s[0] = b0 ^ (~b2 & b4);\n s[1] = b1 ^ (~b3 & b5);\n s[10] = b10 ^ (~b12 & b14);\n s[11] = b11 ^ (~b13 & b15);\n s[20] = b20 ^ (~b22 & b24);\n s[21] = b21 ^ (~b23 & b25);\n s[30] = b30 ^ (~b32 & b34);\n s[31] = b31 ^ (~b33 & b35);\n s[40] = b40 ^ (~b42 & b44);\n s[41] = b41 ^ (~b43 & b45);\n s[2] = b2 ^ (~b4 & b6);\n s[3] = b3 ^ (~b5 & b7);\n s[12] = b12 ^ (~b14 & b16);\n s[13] = b13 ^ (~b15 & b17);\n s[22] = b22 ^ (~b24 & b26);\n s[23] = b23 ^ (~b25 & b27);\n s[32] = b32 ^ (~b34 & b36);\n s[33] = b33 ^ (~b35 & b37);\n s[42] = b42 ^ (~b44 & b46);\n s[43] = b43 ^ (~b45 & b47);\n s[4] = b4 ^ (~b6 & b8);\n s[5] = b5 ^ (~b7 & b9);\n s[14] = b14 ^ (~b16 & b18);\n s[15] = b15 ^ (~b17 & b19);\n s[24] = b24 ^ (~b26 & b28);\n s[25] = b25 ^ (~b27 & b29);\n s[34] = b34 ^ (~b36 & b38);\n s[35] = b35 ^ (~b37 & b39);\n s[44] = b44 ^ (~b46 & b48);\n s[45] = b45 ^ (~b47 & b49);\n s[6] = b6 ^ (~b8 & b0);\n s[7] = b7 ^ (~b9 & b1);\n s[16] = b16 ^ (~b18 & b10);\n s[17] = b17 ^ (~b19 & b11);\n s[26] = b26 ^ (~b28 & b20);\n s[27] = b27 ^ (~b29 & b21);\n s[36] = b36 ^ (~b38 & b30);\n s[37] = b37 ^ (~b39 & b31);\n s[46] = b46 ^ (~b48 & b40);\n s[47] = b47 ^ (~b49 & b41);\n s[8] = b8 ^ (~b0 & b2);\n s[9] = b9 ^ (~b1 & b3);\n s[18] = b18 ^ (~b10 & b12);\n s[19] = b19 ^ (~b11 & b13);\n s[28] = b28 ^ (~b20 & b22);\n s[29] = b29 ^ (~b21 & b23);\n s[38] = b38 ^ (~b30 & b32);\n s[39] = b39 ^ (~b31 & b33);\n s[48] = b48 ^ (~b40 & b42);\n s[49] = b49 ^ (~b41 & b43);\n\n s[0] ^= RC[n];\n s[1] ^= RC[n + 1];\n }\n };\n\n if (COMMON_JS) {\n module.exports = methods;\n } else {\n for (i = 0; i < methodNames.length; ++i) {\n root[methodNames[i]] = methods[methodNames[i]];\n }\n if (AMD) {\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\n return methods;\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n }\n }\n})();\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/js-sha3/src/sha3.js?"); /***/ }), @@ -1461,6 +2693,17 @@ eval("/* module decorator */ module = __webpack_require__.nmd(module);\nvar __WE /***/ }), +/***/ "./node_modules/md5.js/index.js": +/*!**************************************!*\ + !*** ./node_modules/md5.js/index.js ***! + \**************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar HashBase = __webpack_require__(/*! hash-base */ \"./node_modules/hash-base/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar ARRAY16 = new Array(16)\n\nfunction MD5 () {\n HashBase.call(this, 64)\n\n // state\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n}\n\ninherits(MD5, HashBase)\n\nMD5.prototype._update = function () {\n var M = ARRAY16\n for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)\n\n var a = this._a\n var b = this._b\n var c = this._c\n var d = this._d\n\n a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)\n d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)\n c = fnF(c, d, a, b, M[2], 0x242070db, 17)\n b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)\n a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)\n d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)\n c = fnF(c, d, a, b, M[6], 0xa8304613, 17)\n b = fnF(b, c, d, a, M[7], 0xfd469501, 22)\n a = fnF(a, b, c, d, M[8], 0x698098d8, 7)\n d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)\n c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)\n b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)\n a = fnF(a, b, c, d, M[12], 0x6b901122, 7)\n d = fnF(d, a, b, c, M[13], 0xfd987193, 12)\n c = fnF(c, d, a, b, M[14], 0xa679438e, 17)\n b = fnF(b, c, d, a, M[15], 0x49b40821, 22)\n\n a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)\n d = fnG(d, a, b, c, M[6], 0xc040b340, 9)\n c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)\n b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)\n a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)\n d = fnG(d, a, b, c, M[10], 0x02441453, 9)\n c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)\n b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)\n a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)\n d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)\n c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)\n b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)\n a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)\n d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)\n c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)\n b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)\n\n a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)\n d = fnH(d, a, b, c, M[8], 0x8771f681, 11)\n c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)\n b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)\n a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)\n d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)\n c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)\n b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)\n a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)\n d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)\n c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)\n b = fnH(b, c, d, a, M[6], 0x04881d05, 23)\n a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)\n d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)\n c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)\n b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)\n\n a = fnI(a, b, c, d, M[0], 0xf4292244, 6)\n d = fnI(d, a, b, c, M[7], 0x432aff97, 10)\n c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)\n b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)\n a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)\n d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)\n c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)\n b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)\n a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)\n d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)\n c = fnI(c, d, a, b, M[6], 0xa3014314, 15)\n b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)\n a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)\n d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)\n c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)\n b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)\n\n this._a = (this._a + a) | 0\n this._b = (this._b + b) | 0\n this._c = (this._c + c) | 0\n this._d = (this._d + d) | 0\n}\n\nMD5.prototype._digest = function () {\n // create padding and handle blocks\n this._block[this._blockOffset++] = 0x80\n if (this._blockOffset > 56) {\n this._block.fill(0, this._blockOffset, 64)\n this._update()\n this._blockOffset = 0\n }\n\n this._block.fill(0, this._blockOffset, 56)\n this._block.writeUInt32LE(this._length[0], 56)\n this._block.writeUInt32LE(this._length[1], 60)\n this._update()\n\n // produce result\n var buffer = Buffer.allocUnsafe(16)\n buffer.writeInt32LE(this._a, 0)\n buffer.writeInt32LE(this._b, 4)\n buffer.writeInt32LE(this._c, 8)\n buffer.writeInt32LE(this._d, 12)\n return buffer\n}\n\nfunction rotl (x, n) {\n return (x << n) | (x >>> (32 - n))\n}\n\nfunction fnF (a, b, c, d, m, k, s) {\n return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnG (a, b, c, d, m, k, s) {\n return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnH (a, b, c, d, m, k, s) {\n return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0\n}\n\nfunction fnI (a, b, c, d, m, k, s) {\n return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0\n}\n\nmodule.exports = MD5\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/md5.js/index.js?"); + +/***/ }), + /***/ "./node_modules/merge-options/index.js": /*!*********************************************!*\ !*** ./node_modules/merge-options/index.js ***! @@ -1472,6 +2715,26 @@ eval("\nconst isOptionObject = __webpack_require__(/*! is-plain-obj */ \"./node_ /***/ }), +/***/ "./node_modules/miller-rabin/lib/mr.js": +/*!*********************************************!*\ + !*** ./node_modules/miller-rabin/lib/mr.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var bn = __webpack_require__(/*! bn.js */ \"./node_modules/miller-rabin/node_modules/bn.js/lib/bn.js\");\nvar brorand = __webpack_require__(/*! brorand */ \"./node_modules/brorand/index.js\");\n\nfunction MillerRabin(rand) {\n this.rand = rand || new brorand.Rand();\n}\nmodule.exports = MillerRabin;\n\nMillerRabin.create = function create(rand) {\n return new MillerRabin(rand);\n};\n\nMillerRabin.prototype._randbelow = function _randbelow(n) {\n var len = n.bitLength();\n var min_bytes = Math.ceil(len / 8);\n\n // Generage random bytes until a number less than n is found.\n // This ensures that 0..n-1 have an equal probability of being selected.\n do\n var a = new bn(this.rand.generate(min_bytes));\n while (a.cmp(n) >= 0);\n\n return a;\n};\n\nMillerRabin.prototype._randrange = function _randrange(start, stop) {\n // Generate a random number greater than or equal to start and less than stop.\n var size = stop.sub(start);\n return start.add(this._randbelow(size));\n};\n\nMillerRabin.prototype.test = function test(n, k, cb) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n var prime = true;\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n if (cb)\n cb(a);\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return false;\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s)\n return false;\n }\n\n return prime;\n};\n\nMillerRabin.prototype.getDivisor = function getDivisor(n, k) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n\n var g = n.gcd(a);\n if (g.cmpn(1) !== 0)\n return g;\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return x.fromRed().subn(1).gcd(n);\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s) {\n x = x.redSqr();\n return x.fromRed().subn(1).gcd(n);\n }\n }\n\n return false;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/miller-rabin/lib/mr.js?"); + +/***/ }), + +/***/ "./node_modules/miller-rabin/node_modules/bn.js/lib/bn.js": +/*!****************************************************************!*\ + !*** ./node_modules/miller-rabin/node_modules/bn.js/lib/bn.js ***! + \****************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?0aec\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/miller-rabin/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + /***/ "./node_modules/minimalistic-assert/index.js": /*!***************************************************!*\ !*** ./node_modules/minimalistic-assert/index.js ***! @@ -1482,13 +2745,44 @@ eval("module.exports = assert;\n\nfunction assert(val, msg) {\n if (!val)\n /***/ }), +/***/ "./node_modules/minimalistic-crypto-utils/lib/utils.js": +/*!*************************************************************!*\ + !*** ./node_modules/minimalistic-crypto-utils/lib/utils.js ***! + \*************************************************************/ +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +eval("\n\nvar utils = exports;\n\nfunction toArray(msg, enc) {\n if (Array.isArray(msg))\n return msg.slice();\n if (!msg)\n return [];\n var res = [];\n if (typeof msg !== 'string') {\n for (var i = 0; i < msg.length; i++)\n res[i] = msg[i] | 0;\n return res;\n }\n if (enc === 'hex') {\n msg = msg.replace(/[^a-z0-9]+/ig, '');\n if (msg.length % 2 !== 0)\n msg = '0' + msg;\n for (var i = 0; i < msg.length; i += 2)\n res.push(parseInt(msg[i] + msg[i + 1], 16));\n } else {\n for (var i = 0; i < msg.length; i++) {\n var c = msg.charCodeAt(i);\n var hi = c >> 8;\n var lo = c & 0xff;\n if (hi)\n res.push(hi, lo);\n else\n res.push(lo);\n }\n }\n return res;\n}\nutils.toArray = toArray;\n\nfunction zero2(word) {\n if (word.length === 1)\n return '0' + word;\n else\n return word;\n}\nutils.zero2 = zero2;\n\nfunction toHex(msg) {\n var res = '';\n for (var i = 0; i < msg.length; i++)\n res += zero2(msg[i].toString(16));\n return res;\n}\nutils.toHex = toHex;\n\nutils.encode = function encode(arr, enc) {\n if (enc === 'hex')\n return toHex(arr);\n else\n return arr;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/minimalistic-crypto-utils/lib/utils.js?"); + +/***/ }), + /***/ "./node_modules/ms/index.js": /*!**********************************!*\ !*** ./node_modules/ms/index.js ***! \**********************************/ /***/ ((module) => { -eval("/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ms/index.js?"); +eval("/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ms/index.js?"); + +/***/ }), + +/***/ "./node_modules/murmurhash3js-revisited/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/murmurhash3js-revisited/index.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = __webpack_require__(/*! ./lib/murmurHash3js */ \"./node_modules/murmurhash3js-revisited/lib/murmurHash3js.js\");\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/murmurhash3js-revisited/index.js?"); + +/***/ }), + +/***/ "./node_modules/murmurhash3js-revisited/lib/murmurHash3js.js": +/*!*******************************************************************!*\ + !*** ./node_modules/murmurhash3js-revisited/lib/murmurHash3js.js ***! + \*******************************************************************/ +/***/ (function(module, exports) { + +eval("/* jshint -W086: true */\n// +----------------------------------------------------------------------+\n// | murmurHash3js.js v3.0.1 // https://github.com/pid/murmurHash3js\n// | A javascript implementation of MurmurHash3's x86 hashing algorithms. |\n// |----------------------------------------------------------------------|\n// | Copyright (c) 2012-2015 Karan Lyons |\n// | https://github.com/karanlyons/murmurHash3.js/blob/c1778f75792abef7bdd74bc85d2d4e1a3d25cfe9/murmurHash3.js |\n// | Freely distributable under the MIT license. |\n// +----------------------------------------------------------------------+\n\n;(function (root, undefined) {\n 'use strict';\n\n // Create a local object that'll be exported or referenced globally.\n var library = {\n 'version': '3.0.0',\n 'x86': {},\n 'x64': {},\n 'inputValidation': true\n };\n\n // PRIVATE FUNCTIONS\n // -----------------\n\n function _validBytes(bytes) {\n // check the input is an array or a typed array\n if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) {\n return false;\n }\n\n // check all bytes are actually bytes\n for (var i = 0; i < bytes.length; i++) {\n if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) {\n return false;\n }\n }\n return true;\n }\n\n function _x86Multiply(m, n) {\n //\n // Given two 32bit ints, returns the two multiplied together as a\n // 32bit int.\n //\n\n return ((m & 0xffff) * n) + ((((m >>> 16) * n) & 0xffff) << 16);\n }\n\n function _x86Rotl(m, n) {\n //\n // Given a 32bit int and an int representing a number of bit positions,\n // returns the 32bit int rotated left by that number of positions.\n //\n\n return (m << n) | (m >>> (32 - n));\n }\n\n function _x86Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x86 mix of that block.\n //\n\n h ^= h >>> 16;\n h = _x86Multiply(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = _x86Multiply(h, 0xc2b2ae35);\n h ^= h >>> 16;\n\n return h;\n }\n\n function _x64Add(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // added together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] + n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] + n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] + n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += m[0] + n[0];\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Multiply(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // multiplied together as a 64bit int (as an array of two 32bit ints).\n //\n\n m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];\n n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];\n var o = [0, 0, 0, 0];\n\n o[3] += m[3] * n[3];\n o[2] += o[3] >>> 16;\n o[3] &= 0xffff;\n\n o[2] += m[2] * n[3];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[2] += m[3] * n[2];\n o[1] += o[2] >>> 16;\n o[2] &= 0xffff;\n\n o[1] += m[1] * n[3];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[2] * n[2];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[1] += m[3] * n[1];\n o[0] += o[1] >>> 16;\n o[1] &= 0xffff;\n\n o[0] += (m[0] * n[3]) + (m[1] * n[2]) + (m[2] * n[1]) + (m[3] * n[0]);\n o[0] &= 0xffff;\n\n return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];\n }\n\n function _x64Rotl(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) rotated left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 32) {\n return [m[1], m[0]];\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];\n } else {\n n -= 32;\n return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];\n }\n }\n\n function _x64LeftShift(m, n) {\n //\n // Given a 64bit int (as an array of two 32bit ints) and an int\n // representing a number of bit positions, returns the 64bit int (as an\n // array of two 32bit ints) shifted left by that number of positions.\n //\n\n n %= 64;\n\n if (n === 0) {\n return m;\n } else if (n < 32) {\n return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];\n } else {\n return [m[1] << (n - 32), 0];\n }\n }\n\n function _x64Xor(m, n) {\n //\n // Given two 64bit ints (as an array of two 32bit ints) returns the two\n // xored together as a 64bit int (as an array of two 32bit ints).\n //\n\n return [m[0] ^ n[0], m[1] ^ n[1]];\n }\n\n function _x64Fmix(h) {\n //\n // Given a block, returns murmurHash3's final x64 mix of that block.\n // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the\n // only place where we need to right shift 64bit ints.)\n //\n\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xff51afd7, 0xed558ccd]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n h = _x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);\n h = _x64Xor(h, [0, h[0] >>> 1]);\n\n return h;\n }\n\n // PUBLIC FUNCTIONS\n // ----------------\n\n library.x86.hash32 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 32 bit hash\n // using the x86 flavor of MurmurHash3, as an unsigned int.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 4;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n\n var k1 = 0;\n\n var c1 = 0xcc9e2d51;\n var c2 = 0x1b873593;\n\n for (var i = 0; i < blocks; i = i + 4) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n\n h1 ^= k1;\n h1 = _x86Rotl(h1, 13);\n h1 = _x86Multiply(h1, 5) + 0xe6546b64;\n }\n\n k1 = 0;\n\n switch (remainder) {\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h1 = _x86Fmix(h1);\n\n return h1 >>> 0;\n };\n\n library.x86.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x86 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n\n seed = seed || 0;\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = seed;\n var h2 = seed;\n var h3 = seed;\n var h4 = seed;\n\n var k1 = 0;\n var k2 = 0;\n var k3 = 0;\n var k4 = 0;\n\n var c1 = 0x239b961b;\n var c2 = 0xab0e9789;\n var c3 = 0x38b34ae5;\n var c4 = 0xa1e38b93;\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = (bytes[i]) | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);\n k2 = (bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24);\n k3 = (bytes[i + 8]) | (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24);\n k4 = (bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24);\n\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n\n h1 = _x86Rotl(h1, 19);\n h1 += h2;\n h1 = _x86Multiply(h1, 5) + 0x561ccd1b;\n\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n h2 = _x86Rotl(h2, 17);\n h2 += h3;\n h2 = _x86Multiply(h2, 5) + 0x0bcaa747;\n\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n h3 = _x86Rotl(h3, 15);\n h3 += h4;\n h3 = _x86Multiply(h3, 5) + 0x96cd1c35;\n\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n h4 = _x86Rotl(h4, 13);\n h4 += h1;\n h4 = _x86Multiply(h4, 5) + 0x32ac3b17;\n }\n\n k1 = 0;\n k2 = 0;\n k3 = 0;\n k4 = 0;\n\n switch (remainder) {\n case 15:\n k4 ^= bytes[i + 14] << 16;\n\n case 14:\n k4 ^= bytes[i + 13] << 8;\n\n case 13:\n k4 ^= bytes[i + 12];\n k4 = _x86Multiply(k4, c4);\n k4 = _x86Rotl(k4, 18);\n k4 = _x86Multiply(k4, c1);\n h4 ^= k4;\n\n case 12:\n k3 ^= bytes[i + 11] << 24;\n\n case 11:\n k3 ^= bytes[i + 10] << 16;\n\n case 10:\n k3 ^= bytes[i + 9] << 8;\n\n case 9:\n k3 ^= bytes[i + 8];\n k3 = _x86Multiply(k3, c3);\n k3 = _x86Rotl(k3, 17);\n k3 = _x86Multiply(k3, c4);\n h3 ^= k3;\n\n case 8:\n k2 ^= bytes[i + 7] << 24;\n\n case 7:\n k2 ^= bytes[i + 6] << 16;\n\n case 6:\n k2 ^= bytes[i + 5] << 8;\n\n case 5:\n k2 ^= bytes[i + 4];\n k2 = _x86Multiply(k2, c2);\n k2 = _x86Rotl(k2, 16);\n k2 = _x86Multiply(k2, c3);\n h2 ^= k2;\n\n case 4:\n k1 ^= bytes[i + 3] << 24;\n\n case 3:\n k1 ^= bytes[i + 2] << 16;\n\n case 2:\n k1 ^= bytes[i + 1] << 8;\n\n case 1:\n k1 ^= bytes[i];\n k1 = _x86Multiply(k1, c1);\n k1 = _x86Rotl(k1, 15);\n k1 = _x86Multiply(k1, c2);\n h1 ^= k1;\n }\n\n h1 ^= bytes.length;\n h2 ^= bytes.length;\n h3 ^= bytes.length;\n h4 ^= bytes.length;\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n h1 = _x86Fmix(h1);\n h2 = _x86Fmix(h2);\n h3 = _x86Fmix(h3);\n h4 = _x86Fmix(h4);\n\n h1 += h2;\n h1 += h3;\n h1 += h4;\n h2 += h1;\n h3 += h1;\n h4 += h1;\n\n return (\"00000000\" + (h1 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h3 >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h4 >>> 0).toString(16)).slice(-8);\n };\n\n library.x64.hash128 = function (bytes, seed) {\n //\n // Given a string and an optional seed as an int, returns a 128 bit\n // hash using the x64 flavor of MurmurHash3, as an unsigned hex.\n //\n if (library.inputValidation && !_validBytes(bytes)) {\n return undefined;\n }\n seed = seed || 0;\n\n var remainder = bytes.length % 16;\n var blocks = bytes.length - remainder;\n\n var h1 = [0, seed];\n var h2 = [0, seed];\n\n var k1 = [0, 0];\n var k2 = [0, 0];\n\n var c1 = [0x87c37b91, 0x114253d5];\n var c2 = [0x4cf5ad43, 0x2745937f];\n\n for (var i = 0; i < blocks; i = i + 16) {\n k1 = [(bytes[i + 4]) | (bytes[i + 5] << 8) | (bytes[i + 6] << 16) | (bytes[i + 7] << 24), (bytes[i]) |\n (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24)];\n k2 = [(bytes[i + 12]) | (bytes[i + 13] << 8) | (bytes[i + 14] << 16) | (bytes[i + 15] << 24), (bytes[i + 8]) |\n (bytes[i + 9] << 8) | (bytes[i + 10] << 16) | (bytes[i + 11] << 24)];\n\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n\n h1 = _x64Rotl(h1, 27);\n h1 = _x64Add(h1, h2);\n h1 = _x64Add(_x64Multiply(h1, [0, 5]), [0, 0x52dce729]);\n\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n h2 = _x64Rotl(h2, 31);\n h2 = _x64Add(h2, h1);\n h2 = _x64Add(_x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);\n }\n\n k1 = [0, 0];\n k2 = [0, 0];\n\n switch (remainder) {\n case 15:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 14]], 48));\n\n case 14:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 13]], 40));\n\n case 13:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 12]], 32));\n\n case 12:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 11]], 24));\n\n case 11:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 10]], 16));\n\n case 10:\n k2 = _x64Xor(k2, _x64LeftShift([0, bytes[i + 9]], 8));\n\n case 9:\n k2 = _x64Xor(k2, [0, bytes[i + 8]]);\n k2 = _x64Multiply(k2, c2);\n k2 = _x64Rotl(k2, 33);\n k2 = _x64Multiply(k2, c1);\n h2 = _x64Xor(h2, k2);\n\n case 8:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 7]], 56));\n\n case 7:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 6]], 48));\n\n case 6:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 5]], 40));\n\n case 5:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 4]], 32));\n\n case 4:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 3]], 24));\n\n case 3:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 2]], 16));\n\n case 2:\n k1 = _x64Xor(k1, _x64LeftShift([0, bytes[i + 1]], 8));\n\n case 1:\n k1 = _x64Xor(k1, [0, bytes[i]]);\n k1 = _x64Multiply(k1, c1);\n k1 = _x64Rotl(k1, 31);\n k1 = _x64Multiply(k1, c2);\n h1 = _x64Xor(h1, k1);\n }\n\n h1 = _x64Xor(h1, [0, bytes.length]);\n h2 = _x64Xor(h2, [0, bytes.length]);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n h1 = _x64Fmix(h1);\n h2 = _x64Fmix(h2);\n\n h1 = _x64Add(h1, h2);\n h2 = _x64Add(h2, h1);\n\n return (\"00000000\" + (h1[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h1[1] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[0] >>> 0).toString(16)).slice(-8) + (\"00000000\" + (h2[1] >>> 0).toString(16)).slice(-8);\n };\n\n // INITIALIZATION\n // --------------\n\n // Export murmurHash3 for CommonJS, either as an AMD module or just as part\n // of the global object.\n if (true) {\n\n if ( true && module.exports) {\n exports = module.exports = library;\n }\n\n exports.murmurHash3 = library;\n\n } else {}\n})(this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/murmurhash3js-revisited/lib/murmurHash3js.js?"); /***/ }), @@ -1526,9 +2820,9 @@ eval("/**\n * Javascript implementation of Abstract Syntax Notation Number One.\ /*!**********************************************!*\ !*** ./node_modules/node-forge/lib/baseN.js ***! \**********************************************/ -/***/ ((module) => { +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/baseN.js?"); +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"?7d1a\")[\"Buffer\"];\n/**\n * Base-N/Base-X encoding/decoding functions.\n *\n * Original implementation from base-x:\n * https://github.com/cryptocoinjs/base-x\n *\n * Which is MIT licensed:\n *\n * The MIT License (MIT)\n *\n * Copyright base-x contributors (c) 2016\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\nvar api = {};\nmodule.exports = api;\n\n// baseN alphabet indexes\nvar _reverseAlphabets = {};\n\n/**\n * BaseN-encodes a Uint8Array using the given alphabet.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the baseN-encoded output string.\n */\napi.encode = function(input, alphabet, maxline) {\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n if(maxline !== undefined && typeof maxline !== 'number') {\n throw new TypeError('\"maxline\" must be a number.');\n }\n\n var output = '';\n\n if(!(input instanceof Uint8Array)) {\n // assume forge byte buffer\n output = _encodeWithByteBuffer(input, alphabet);\n } else {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length; ++i) {\n for(var j = 0, carry = input[i]; j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n // deal with leading zeros\n for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n }\n\n if(maxline) {\n var regex = new RegExp('.{1,' + maxline + '}', 'g');\n output = output.match(regex).join('\\r\\n');\n }\n\n return output;\n};\n\n/**\n * Decodes a baseN-encoded (using the given alphabet) string to a\n * Uint8Array.\n *\n * @param input the baseN-encoded input string.\n *\n * @return the Uint8Array.\n */\napi.decode = function(input, alphabet) {\n if(typeof input !== 'string') {\n throw new TypeError('\"input\" must be a string.');\n }\n if(typeof alphabet !== 'string') {\n throw new TypeError('\"alphabet\" must be a string.');\n }\n\n var table = _reverseAlphabets[alphabet];\n if(!table) {\n // compute reverse alphabet\n table = _reverseAlphabets[alphabet] = [];\n for(var i = 0; i < alphabet.length; ++i) {\n table[alphabet.charCodeAt(i)] = i;\n }\n }\n\n // remove whitespace characters\n input = input.replace(/\\s/g, '');\n\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var bytes = [0];\n for(var i = 0; i < input.length; i++) {\n var value = table[input.charCodeAt(i)];\n if(value === undefined) {\n return;\n }\n\n for(var j = 0, carry = value; j < bytes.length; ++j) {\n carry += bytes[j] * base;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n\n while(carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // deal with leading zeros\n for(var k = 0; input[k] === first && k < input.length - 1; ++k) {\n bytes.push(0);\n }\n\n if(typeof Buffer !== 'undefined') {\n return Buffer.from(bytes.reverse());\n }\n\n return new Uint8Array(bytes.reverse());\n};\n\nfunction _encodeWithByteBuffer(input, alphabet) {\n var i = 0;\n var base = alphabet.length;\n var first = alphabet.charAt(0);\n var digits = [0];\n for(i = 0; i < input.length(); ++i) {\n for(var j = 0, carry = input.at(i); j < digits.length; ++j) {\n carry += digits[j] << 8;\n digits[j] = carry % base;\n carry = (carry / base) | 0;\n }\n\n while(carry > 0) {\n digits.push(carry % base);\n carry = (carry / base) | 0;\n }\n }\n\n var output = '';\n\n // deal with leading zeros\n for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {\n output += first;\n }\n // convert digits to a string\n for(i = digits.length - 1; i >= 0; --i) {\n output += alphabet[digits[i]];\n }\n\n return output;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/baseN.js?"); /***/ }), @@ -1628,7 +2922,7 @@ eval("/**\n * Password-based encryption functions.\n *\n * @author Dave Longley\ \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\n__webpack_require__(/*! ./hmac */ \"./node_modules/node-forge/lib/hmac.js\");\n__webpack_require__(/*! ./md */ \"./node_modules/node-forge/lib/md.js\");\n__webpack_require__(/*! ./util */ \"./node_modules/node-forge/lib/util.js\");\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = __webpack_require__(/*! crypto */ \"?b254\");\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/pbkdf2.js?"); +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"?7d1a\")[\"Buffer\"];\n/**\n * Password-Based Key-Derivation Function #2 implementation.\n *\n * See RFC 2898 for details.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2013 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\n__webpack_require__(/*! ./hmac */ \"./node_modules/node-forge/lib/hmac.js\");\n__webpack_require__(/*! ./md */ \"./node_modules/node-forge/lib/md.js\");\n__webpack_require__(/*! ./util */ \"./node_modules/node-forge/lib/util.js\");\n\nvar pkcs5 = forge.pkcs5 = forge.pkcs5 || {};\n\nvar crypto;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript) {\n crypto = __webpack_require__(/*! crypto */ \"?b254\");\n}\n\n/**\n * Derives a key from a password.\n *\n * @param p the password as a binary-encoded string of bytes.\n * @param s the salt as a binary-encoded string of bytes.\n * @param c the iteration count, a positive integer.\n * @param dkLen the intended length, in bytes, of the derived key,\n * (max: 2^32 - 1) * hash length of the PRF.\n * @param [md] the message digest (or algorithm identifier as a string) to use\n * in the PRF, defaults to SHA-1.\n * @param [callback(err, key)] presence triggers asynchronous version, called\n * once the operation completes.\n *\n * @return the derived key, as a binary-encoded string of bytes, for the\n * synchronous version (if no callback is specified).\n */\nmodule.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function(\n p, s, c, dkLen, md, callback) {\n if(typeof md === 'function') {\n callback = md;\n md = null;\n }\n\n // use native implementation if possible and not disabled, note that\n // some node versions only support SHA-1, others allow digest to be changed\n if(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n crypto.pbkdf2 && (md === null || typeof md !== 'object') &&\n (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {\n if(typeof md !== 'string') {\n // default prf to SHA-1\n md = 'sha1';\n }\n p = Buffer.from(p, 'binary');\n s = Buffer.from(s, 'binary');\n if(!callback) {\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');\n }\n return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');\n }\n if(crypto.pbkdf2Sync.length === 4) {\n return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {\n if(err) {\n return callback(err);\n }\n callback(null, key.toString('binary'));\n });\n }\n\n if(typeof md === 'undefined' || md === null) {\n // default prf to SHA-1\n md = 'sha1';\n }\n if(typeof md === 'string') {\n if(!(md in forge.md.algorithms)) {\n throw new Error('Unknown hash algorithm: ' + md);\n }\n md = forge.md[md].create();\n }\n\n var hLen = md.digestLength;\n\n /* 1. If dkLen > (2^32 - 1) * hLen, output \"derived key too long\" and\n stop. */\n if(dkLen > (0xFFFFFFFF * hLen)) {\n var err = new Error('Derived key is too long.');\n if(callback) {\n return callback(err);\n }\n throw err;\n }\n\n /* 2. Let len be the number of hLen-octet blocks in the derived key,\n rounding up, and let r be the number of octets in the last\n block:\n\n len = CEIL(dkLen / hLen),\n r = dkLen - (len - 1) * hLen. */\n var len = Math.ceil(dkLen / hLen);\n var r = dkLen - (len - 1) * hLen;\n\n /* 3. For each block of the derived key apply the function F defined\n below to the password P, the salt S, the iteration count c, and\n the block index to compute the block:\n\n T_1 = F(P, S, c, 1),\n T_2 = F(P, S, c, 2),\n ...\n T_len = F(P, S, c, len),\n\n where the function F is defined as the exclusive-or sum of the\n first c iterates of the underlying pseudorandom function PRF\n applied to the password P and the concatenation of the salt S\n and the block index i:\n\n F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c\n\n where\n\n u_1 = PRF(P, S || INT(i)),\n u_2 = PRF(P, u_1),\n ...\n u_c = PRF(P, u_{c-1}).\n\n Here, INT(i) is a four-octet encoding of the integer i, most\n significant octet first. */\n var prf = forge.hmac.create();\n prf.start(md, p);\n var dk = '';\n var xor, u_c, u_c1;\n\n // sync version\n if(!callback) {\n for(var i = 1; i <= len; ++i) {\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n for(var j = 2; j <= c; ++j) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n }\n /* 5. Output the derived key DK. */\n return dk;\n }\n\n // async version\n var i = 1, j;\n function outer() {\n if(i > len) {\n // done\n return callback(null, dk);\n }\n\n // PRF(P, S || INT(i)) (first iteration)\n prf.start(null, null);\n prf.update(s);\n prf.update(forge.util.int32ToBytes(i));\n xor = u_c1 = prf.digest().getBytes();\n\n // PRF(P, u_{c-1}) (other iterations)\n j = 2;\n inner();\n }\n\n function inner() {\n if(j <= c) {\n prf.start(null, null);\n prf.update(u_c1);\n u_c = prf.digest().getBytes();\n // F(p, s, c, i)\n xor = forge.util.xorBytes(xor, u_c, hLen);\n u_c1 = u_c;\n ++j;\n return forge.util.setImmediate(inner);\n }\n\n /* 4. Concatenate the blocks and extract the first dkLen octets to\n produce a derived key DK:\n\n DK = T_1 || T_2 || ... || T_len<0..r-1> */\n dk += (i < len) ? xor : xor.substr(0, r);\n\n ++i;\n outer();\n }\n\n outer();\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/pbkdf2.js?"); /***/ }), @@ -1668,7 +2962,7 @@ eval("/**\n * Prime number generation API.\n *\n * @author Dave Longley\n *\n * \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\n__webpack_require__(/*! ./util */ \"./node_modules/node-forge/lib/util.js\");\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = __webpack_require__(/*! crypto */ \"?b254\");\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/prng.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n/**\n * A javascript implementation of a cryptographically-secure\n * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed\n * here though the use of SHA-256 is not enforced; when generating an\n * a PRNG context, the hashing algorithm and block cipher used for\n * the generator are specified via a plugin.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2014 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\n__webpack_require__(/*! ./util */ \"./node_modules/node-forge/lib/util.js\");\n\nvar _crypto = null;\nif(forge.util.isNodejs && !forge.options.usePureJavaScript &&\n !process.versions['node-webkit']) {\n _crypto = __webpack_require__(/*! crypto */ \"?b254\");\n}\n\n/* PRNG API */\nvar prng = module.exports = forge.prng = forge.prng || {};\n\n/**\n * Creates a new PRNG context.\n *\n * A PRNG plugin must be passed in that will provide:\n *\n * 1. A function that initializes the key and seed of a PRNG context. It\n * will be given a 16 byte key and a 16 byte seed. Any key expansion\n * or transformation of the seed from a byte string into an array of\n * integers (or similar) should be performed.\n * 2. The cryptographic function used by the generator. It takes a key and\n * a seed.\n * 3. A seed increment function. It takes the seed and returns seed + 1.\n * 4. An api to create a message digest.\n *\n * For an example, see random.js.\n *\n * @param plugin the PRNG plugin to use.\n */\nprng.create = function(plugin) {\n var ctx = {\n plugin: plugin,\n key: null,\n seed: null,\n time: null,\n // number of reseeds so far\n reseeds: 0,\n // amount of data generated so far\n generated: 0,\n // no initial key bytes\n keyBytes: ''\n };\n\n // create 32 entropy pools (each is a message digest)\n var md = plugin.md;\n var pools = new Array(32);\n for(var i = 0; i < 32; ++i) {\n pools[i] = md.create();\n }\n ctx.pools = pools;\n\n // entropy pools are written to cyclically, starting at index 0\n ctx.pool = 0;\n\n /**\n * Generates random bytes. The bytes may be generated synchronously or\n * asynchronously. Web workers must use the asynchronous interface or\n * else the behavior is undefined.\n *\n * @param count the number of random bytes to generate.\n * @param [callback(err, bytes)] called once the operation completes.\n *\n * @return count random bytes as a string.\n */\n ctx.generate = function(count, callback) {\n // do synchronously\n if(!callback) {\n return ctx.generateSync(count);\n }\n\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n var b = forge.util.createBuffer();\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generate` call\n ctx.key = null;\n\n generate();\n\n function generate(err) {\n if(err) {\n return callback(err);\n }\n\n // sufficient bytes generated\n if(b.length() >= count) {\n return callback(null, b.getBytes(count));\n }\n\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n // prevent stack overflow\n return forge.util.nextTick(function() {\n _reseed(generate);\n });\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n\n forge.util.setImmediate(generate);\n }\n };\n\n /**\n * Generates random bytes synchronously.\n *\n * @param count the number of random bytes to generate.\n *\n * @return count random bytes as a string.\n */\n ctx.generateSync = function(count) {\n // simple generator using counter-based CBC\n var cipher = ctx.plugin.cipher;\n var increment = ctx.plugin.increment;\n var formatKey = ctx.plugin.formatKey;\n var formatSeed = ctx.plugin.formatSeed;\n\n // paranoid deviation from Fortuna:\n // reset key for every request to protect previously\n // generated random bytes should the key be discovered;\n // there is no 100ms based reseeding because of this\n // forced reseed for every `generateSync` call\n ctx.key = null;\n\n var b = forge.util.createBuffer();\n while(b.length() < count) {\n // if amount of data generated is greater than 1 MiB, trigger reseed\n if(ctx.generated > 0xfffff) {\n ctx.key = null;\n }\n\n if(ctx.key === null) {\n _reseedSync();\n }\n\n // generate the random bytes\n var bytes = cipher(ctx.key, ctx.seed);\n ctx.generated += bytes.length;\n b.putBytes(bytes);\n\n // generate bytes for a new key and seed\n ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));\n ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));\n }\n\n return b.getBytes(count);\n };\n\n /**\n * Private function that asynchronously reseeds a generator.\n *\n * @param callback(err) called once the operation completes.\n */\n function _reseed(callback) {\n if(ctx.pools[0].messageLength >= 32) {\n _seed();\n return callback();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.seedFile(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n ctx.collect(bytes);\n _seed();\n callback();\n });\n }\n\n /**\n * Private function that synchronously reseeds a generator.\n */\n function _reseedSync() {\n if(ctx.pools[0].messageLength >= 32) {\n return _seed();\n }\n // not enough seed data...\n var needed = (32 - ctx.pools[0].messageLength) << 5;\n ctx.collect(ctx.seedFileSync(needed));\n _seed();\n }\n\n /**\n * Private function that seeds a generator once enough bytes are available.\n */\n function _seed() {\n // update reseed count\n ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;\n\n // goal is to update `key` via:\n // key = hash(key + s)\n // where 's' is all collected entropy from selected pools, then...\n\n // create a plugin-based message digest\n var md = ctx.plugin.md.create();\n\n // consume current key bytes\n md.update(ctx.keyBytes);\n\n // digest the entropy of pools whose index k meet the\n // condition 'n mod 2^k == 0' where n is the number of reseeds\n var _2powK = 1;\n for(var k = 0; k < 32; ++k) {\n if(ctx.reseeds % _2powK === 0) {\n md.update(ctx.pools[k].digest().getBytes());\n ctx.pools[k].start();\n }\n _2powK = _2powK << 1;\n }\n\n // get digest for key bytes\n ctx.keyBytes = md.digest().getBytes();\n\n // paranoid deviation from Fortuna:\n // update `seed` via `seed = hash(key)`\n // instead of initializing to zero once and only\n // ever incrementing it\n md.start();\n md.update(ctx.keyBytes);\n var seedBytes = md.digest().getBytes();\n\n // update state\n ctx.key = ctx.plugin.formatKey(ctx.keyBytes);\n ctx.seed = ctx.plugin.formatSeed(seedBytes);\n ctx.generated = 0;\n }\n\n /**\n * The built-in default seedFile. This seedFile is used when entropy\n * is needed immediately.\n *\n * @param needed the number of bytes that are needed.\n *\n * @return the random bytes.\n */\n function defaultSeedFile(needed) {\n // use window.crypto.getRandomValues strong source of entropy if available\n var getRandomValues = null;\n var globalScope = forge.util.globalScope;\n var _crypto = globalScope.crypto || globalScope.msCrypto;\n if(_crypto && _crypto.getRandomValues) {\n getRandomValues = function(arr) {\n return _crypto.getRandomValues(arr);\n };\n }\n\n var b = forge.util.createBuffer();\n if(getRandomValues) {\n while(b.length() < needed) {\n // max byte length is 65536 before QuotaExceededError is thrown\n // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues\n var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);\n var entropy = new Uint32Array(Math.floor(count));\n try {\n getRandomValues(entropy);\n for(var i = 0; i < entropy.length; ++i) {\n b.putInt32(entropy[i]);\n }\n } catch(e) {\n /* only ignore QuotaExceededError */\n if(!(typeof QuotaExceededError !== 'undefined' &&\n e instanceof QuotaExceededError)) {\n throw e;\n }\n }\n }\n }\n\n // be sad and add some weak random data\n if(b.length() < needed) {\n /* Draws from Park-Miller \"minimal standard\" 31 bit PRNG,\n implemented with David G. Carta's optimization: with 32 bit math\n and without division (Public Domain). */\n var hi, lo, next;\n var seed = Math.floor(Math.random() * 0x010000);\n while(b.length() < needed) {\n lo = 16807 * (seed & 0xFFFF);\n hi = 16807 * (seed >> 16);\n lo += (hi & 0x7FFF) << 16;\n lo += hi >> 15;\n lo = (lo & 0x7FFFFFFF) + (lo >> 31);\n seed = lo & 0xFFFFFFFF;\n\n // consume lower 3 bytes of seed\n for(var i = 0; i < 3; ++i) {\n // throw in more pseudo random\n next = seed >>> (i << 3);\n next ^= Math.floor(Math.random() * 0x0100);\n b.putByte(next & 0xFF);\n }\n }\n }\n\n return b.getBytes(needed);\n }\n // initialize seed file APIs\n if(_crypto) {\n // use nodejs async API\n ctx.seedFile = function(needed, callback) {\n _crypto.randomBytes(needed, function(err, bytes) {\n if(err) {\n return callback(err);\n }\n callback(null, bytes.toString());\n });\n };\n // use nodejs sync API\n ctx.seedFileSync = function(needed) {\n return _crypto.randomBytes(needed).toString();\n };\n } else {\n ctx.seedFile = function(needed, callback) {\n try {\n callback(null, defaultSeedFile(needed));\n } catch(e) {\n callback(e);\n }\n };\n ctx.seedFileSync = defaultSeedFile;\n }\n\n /**\n * Adds entropy to a prng ctx's accumulator.\n *\n * @param bytes the bytes of entropy as a string.\n */\n ctx.collect = function(bytes) {\n // iterate over pools distributing entropy cyclically\n var count = bytes.length;\n for(var i = 0; i < count; ++i) {\n ctx.pools[ctx.pool].update(bytes.substr(i, 1));\n ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;\n }\n };\n\n /**\n * Collects an integer of n bits.\n *\n * @param i the integer entropy.\n * @param n the number of bits in the integer.\n */\n ctx.collectInt = function(i, n) {\n var bytes = '';\n for(var x = 0; x < n; x += 8) {\n bytes += String.fromCharCode((i >> x) & 0xFF);\n }\n ctx.collect(bytes);\n };\n\n /**\n * Registers a Web Worker to receive immediate entropy from the main thread.\n * This method is required until Web Workers can access the native crypto\n * API. This method should be called twice for each created worker, once in\n * the main thread, and once in the worker itself.\n *\n * @param worker the worker to register.\n */\n ctx.registerWorker = function(worker) {\n // worker receives random bytes\n if(worker === self) {\n ctx.seedFile = function(needed, callback) {\n function listener(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n self.removeEventListener('message', listener);\n callback(data.forge.prng.err, data.forge.prng.bytes);\n }\n }\n self.addEventListener('message', listener);\n self.postMessage({forge: {prng: {needed: needed}}});\n };\n } else {\n // main thread sends random bytes upon request\n var listener = function(e) {\n var data = e.data;\n if(data.forge && data.forge.prng) {\n ctx.seedFile(data.forge.prng.needed, function(err, bytes) {\n worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});\n });\n }\n };\n // TODO: do we need to remove the event listener when the worker dies?\n worker.addEventListener('message', listener);\n }\n };\n\n return ctx;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/prng.js?"); /***/ }), @@ -1738,7 +3032,132 @@ eval("/**\n * Secure Hash Algorithm with a 1024-bit block size implementation.\n \*********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { -eval("/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\nvar baseN = __webpack_require__(/*! ./baseN */ \"./node_modules/node-forge/lib/baseN.js\");\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return __webpack_require__.g;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/util.js?"); +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"?7d1a\")[\"Buffer\"];\n/**\n * Utility functions for web applications.\n *\n * @author Dave Longley\n *\n * Copyright (c) 2010-2018 Digital Bazaar, Inc.\n */\nvar forge = __webpack_require__(/*! ./forge */ \"./node_modules/node-forge/lib/forge.js\");\nvar baseN = __webpack_require__(/*! ./baseN */ \"./node_modules/node-forge/lib/baseN.js\");\n\n/* Utilities API */\nvar util = module.exports = forge.util = forge.util || {};\n\n// define setImmediate and nextTick\n(function() {\n // use native nextTick (unless we're in webpack)\n // webpack (or better node-libs-browser polyfill) sets process.browser.\n // this way we can detect webpack properly\n if(typeof process !== 'undefined' && process.nextTick && !process.browser) {\n util.nextTick = process.nextTick;\n if(typeof setImmediate === 'function') {\n util.setImmediate = setImmediate;\n } else {\n // polyfill setImmediate with nextTick, older versions of node\n // (those w/o setImmediate) won't totally starve IO\n util.setImmediate = util.nextTick;\n }\n return;\n }\n\n // polyfill nextTick with native setImmediate\n if(typeof setImmediate === 'function') {\n util.setImmediate = function() { return setImmediate.apply(undefined, arguments); };\n util.nextTick = function(callback) {\n return setImmediate(callback);\n };\n return;\n }\n\n /* Note: A polyfill upgrade pattern is used here to allow combining\n polyfills. For example, MutationObserver is fast, but blocks UI updates,\n so it needs to allow UI updates periodically, so it falls back on\n postMessage or setTimeout. */\n\n // polyfill with setTimeout\n util.setImmediate = function(callback) {\n setTimeout(callback, 0);\n };\n\n // upgrade polyfill to use postMessage\n if(typeof window !== 'undefined' &&\n typeof window.postMessage === 'function') {\n var msg = 'forge.setImmediate';\n var callbacks = [];\n util.setImmediate = function(callback) {\n callbacks.push(callback);\n // only send message when one hasn't been sent in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n window.postMessage(msg, '*');\n }\n };\n function handler(event) {\n if(event.source === window && event.data === msg) {\n event.stopPropagation();\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }\n }\n window.addEventListener('message', handler, true);\n }\n\n // upgrade polyfill to use MutationObserver\n if(typeof MutationObserver !== 'undefined') {\n // polyfill with MutationObserver\n var now = Date.now();\n var attr = true;\n var div = document.createElement('div');\n var callbacks = [];\n new MutationObserver(function() {\n var copy = callbacks.slice();\n callbacks.length = 0;\n copy.forEach(function(callback) {\n callback();\n });\n }).observe(div, {attributes: true});\n var oldSetImmediate = util.setImmediate;\n util.setImmediate = function(callback) {\n if(Date.now() - now > 15) {\n now = Date.now();\n oldSetImmediate(callback);\n } else {\n callbacks.push(callback);\n // only trigger observer when it hasn't been triggered in\n // the current turn of the event loop\n if(callbacks.length === 1) {\n div.setAttribute('a', attr = !attr);\n }\n }\n };\n }\n\n util.nextTick = util.setImmediate;\n})();\n\n// check if running under Node.js\nutil.isNodejs =\n typeof process !== 'undefined' && process.versions && process.versions.node;\n\n\n// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while\n// it will point to `window` in the main thread.\n// To remain compatible with older browsers, we fall back to 'window' if 'self'\n// is not available.\nutil.globalScope = (function() {\n if(util.isNodejs) {\n return __webpack_require__.g;\n }\n\n return typeof self === 'undefined' ? window : self;\n})();\n\n// define isArray\nutil.isArray = Array.isArray || function(x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n};\n\n// define isArrayBuffer\nutil.isArrayBuffer = function(x) {\n return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;\n};\n\n// define isArrayBufferView\nutil.isArrayBufferView = function(x) {\n return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined;\n};\n\n/**\n * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for\n * algorithms where bit manipulation, JavaScript limitations, and/or algorithm\n * design only allow for byte operations of a limited size.\n *\n * @param n number of bits.\n *\n * Throw Error if n invalid.\n */\nfunction _checkBitsParam(n) {\n if(!(n === 8 || n === 16 || n === 24 || n === 32)) {\n throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);\n }\n}\n\n// TODO: set ByteBuffer to best available backing\nutil.ByteBuffer = ByteStringBuffer;\n\n/** Buffer w/BinaryString backing */\n\n/**\n * Constructor for a binary string backed byte buffer.\n *\n * @param [b] the bytes to wrap (either encoded as string, one byte per\n * character, or as an ArrayBuffer or Typed Array).\n */\nfunction ByteStringBuffer(b) {\n // TODO: update to match DataBuffer API\n\n // the data in this buffer\n this.data = '';\n // the pointer for reading from this buffer\n this.read = 0;\n\n if(typeof b === 'string') {\n this.data = b;\n } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) {\n if(typeof Buffer !== 'undefined' && b instanceof Buffer) {\n this.data = b.toString('binary');\n } else {\n // convert native buffer to forge buffer\n // FIXME: support native buffers internally instead\n var arr = new Uint8Array(b);\n try {\n this.data = String.fromCharCode.apply(null, arr);\n } catch(e) {\n for(var i = 0; i < arr.length; ++i) {\n this.putByte(arr[i]);\n }\n }\n }\n } else if(b instanceof ByteStringBuffer ||\n (typeof b === 'object' && typeof b.data === 'string' &&\n typeof b.read === 'number')) {\n // copy existing buffer\n this.data = b.data;\n this.read = b.read;\n }\n\n // used for v8 optimization\n this._constructedStringLength = 0;\n}\nutil.ByteStringBuffer = ByteStringBuffer;\n\n/* Note: This is an optimization for V8-based browsers. When V8 concatenates\n a string, the strings are only joined logically using a \"cons string\" or\n \"constructed/concatenated string\". These containers keep references to one\n another and can result in very large memory usage. For example, if a 2MB\n string is constructed by concatenating 4 bytes together at a time, the\n memory usage will be ~44MB; so ~22x increase. The strings are only joined\n together when an operation requiring their joining takes place, such as\n substr(). This function is called when adding data to this buffer to ensure\n these types of strings are periodically joined to reduce the memory\n footprint. */\nvar _MAX_CONSTRUCTED_STRING_LENGTH = 4096;\nutil.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {\n this._constructedStringLength += x;\n if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {\n // this substr() should cause the constructed string to join\n this.data.substr(0, 1);\n this._constructedStringLength = 0;\n }\n};\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.ByteStringBuffer.prototype.length = function() {\n return this.data.length - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.ByteStringBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putByte = function(b) {\n return this.putBytes(String.fromCharCode(b));\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.fillWithByte = function(b, n) {\n b = String.fromCharCode(b);\n var d = this.data;\n while(n > 0) {\n if(n & 1) {\n d += b;\n }\n n >>>= 1;\n if(n > 0) {\n b += b;\n }\n }\n this.data = d;\n this._optimizeConstructedString(n);\n return this;\n};\n\n/**\n * Puts bytes in this buffer.\n *\n * @param bytes the bytes (as a binary encoded string) to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBytes = function(bytes) {\n this.data += bytes;\n this._optimizeConstructedString(bytes.length);\n return this;\n};\n\n/**\n * Puts a UTF-16 encoded string into this buffer.\n *\n * @param str the string to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putString = function(str) {\n return this.putBytes(util.encodeUtf8(str));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32 = function(i) {\n return this.putBytes(\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt16Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF));\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt24Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF));\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt32Le = function(i) {\n return this.putBytes(\n String.fromCharCode(i & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 24 & 0xFF));\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n var bytes = '';\n do {\n n -= 8;\n bytes += String.fromCharCode((i >> n) & 0xFF);\n } while(n > 0);\n return this.putBytes(bytes);\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putSignedInt = function(i, n) {\n // putInt checks n\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.putBuffer = function(buffer) {\n return this.putBytes(buffer.getBytes());\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.getByte = function() {\n return this.data.charCodeAt(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 8 ^\n this.data.charCodeAt(this.read + 1));\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 16 ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32 = function() {\n var rval = (\n this.data.charCodeAt(this.read) << 24 ^\n this.data.charCodeAt(this.read + 1) << 16 ^\n this.data.charCodeAt(this.read + 2) << 8 ^\n this.data.charCodeAt(this.read + 3));\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.ByteStringBuffer.prototype.getInt16Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.ByteStringBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.ByteStringBuffer.prototype.getInt32Le = function() {\n var rval = (\n this.data.charCodeAt(this.read) ^\n this.data.charCodeAt(this.read + 1) << 8 ^\n this.data.charCodeAt(this.read + 2) << 16 ^\n this.data.charCodeAt(this.read + 3) << 24);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by ceil(n/8).\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.charCodeAt(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.ByteStringBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer. Note that the resulting string is binary encoded (in node.js this\n * encoding is referred to as `binary`, it is *not* `utf8`).\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.ByteStringBuffer.prototype.getBytes = function(count) {\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.ByteStringBuffer.prototype.bytes = function(count) {\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.ByteStringBuffer.prototype.at = function(i) {\n return this.data.charCodeAt(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.setAt = function(i, b) {\n this.data = this.data.substr(0, this.read + i) +\n String.fromCharCode(b) +\n this.data.substr(this.read + i + 1);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.ByteStringBuffer.prototype.last = function() {\n return this.data.charCodeAt(this.data.length - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.ByteStringBuffer.prototype.copy = function() {\n var c = util.createBuffer(this.data);\n c.read = this.read;\n return c;\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.compact = function() {\n if(this.read > 0) {\n this.data = this.data.slice(this.read);\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.clear = function() {\n this.data = '';\n this.read = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.ByteStringBuffer.prototype.truncate = function(count) {\n var len = Math.max(0, this.length() - count);\n this.data = this.data.substr(this.read, len);\n this.read = 0;\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.ByteStringBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.length; ++i) {\n var b = this.data.charCodeAt(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a UTF-16 string (standard JavaScript string).\n *\n * @return a UTF-16 string.\n */\nutil.ByteStringBuffer.prototype.toString = function() {\n return util.decodeUtf8(this.bytes());\n};\n\n/** End Buffer w/BinaryString backing */\n\n/** Buffer w/UInt8Array backing */\n\n/**\n * FIXME: Experimental. Do not use yet.\n *\n * Constructor for an ArrayBuffer-backed byte buffer.\n *\n * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a\n * TypedArray.\n *\n * If a string is given, its encoding should be provided as an option,\n * otherwise it will default to 'binary'. A 'binary' string is encoded such\n * that each character is one byte in length and size.\n *\n * If an ArrayBuffer, DataView, or TypedArray is given, it will be used\n * *directly* without any copying. Note that, if a write to the buffer requires\n * more space, the buffer will allocate a new backing ArrayBuffer to\n * accommodate. The starting read and write offsets for the buffer may be\n * given as options.\n *\n * @param [b] the initial bytes for this buffer.\n * @param options the options to use:\n * [readOffset] the starting read offset to use (default: 0).\n * [writeOffset] the starting write offset to use (default: the\n * length of the first parameter).\n * [growSize] the minimum amount, in bytes, to grow the buffer by to\n * accommodate writes (default: 1024).\n * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the\n * first parameter, if it is a string (default: 'binary').\n */\nfunction DataBuffer(b, options) {\n // default options\n options = options || {};\n\n // pointers for read from/write to buffer\n this.read = options.readOffset || 0;\n this.growSize = options.growSize || 1024;\n\n var isArrayBuffer = util.isArrayBuffer(b);\n var isArrayBufferView = util.isArrayBufferView(b);\n if(isArrayBuffer || isArrayBufferView) {\n // use ArrayBuffer directly\n if(isArrayBuffer) {\n this.data = new DataView(b);\n } else {\n // TODO: adjust read/write offset based on the type of view\n // or specify that this must be done in the options ... that the\n // offsets are byte-based\n this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);\n }\n this.write = ('writeOffset' in options ?\n options.writeOffset : this.data.byteLength);\n return;\n }\n\n // initialize to empty array buffer and add any given bytes using putBytes\n this.data = new DataView(new ArrayBuffer(0));\n this.write = 0;\n\n if(b !== null && b !== undefined) {\n this.putBytes(b);\n }\n\n if('writeOffset' in options) {\n this.write = options.writeOffset;\n }\n}\nutil.DataBuffer = DataBuffer;\n\n/**\n * Gets the number of bytes in this buffer.\n *\n * @return the number of bytes in this buffer.\n */\nutil.DataBuffer.prototype.length = function() {\n return this.write - this.read;\n};\n\n/**\n * Gets whether or not this buffer is empty.\n *\n * @return true if this buffer is empty, false if not.\n */\nutil.DataBuffer.prototype.isEmpty = function() {\n return this.length() <= 0;\n};\n\n/**\n * Ensures this buffer has enough empty space to accommodate the given number\n * of bytes. An optional parameter may be given that indicates a minimum\n * amount to grow the buffer if necessary. If the parameter is not given,\n * the buffer will be grown by some previously-specified default amount\n * or heuristic.\n *\n * @param amount the number of bytes to accommodate.\n * @param [growSize] the minimum amount, in bytes, to grow the buffer by if\n * necessary.\n */\nutil.DataBuffer.prototype.accommodate = function(amount, growSize) {\n if(this.length() >= amount) {\n return this;\n }\n growSize = Math.max(growSize || this.growSize, amount);\n\n // grow buffer\n var src = new Uint8Array(\n this.data.buffer, this.data.byteOffset, this.data.byteLength);\n var dst = new Uint8Array(this.length() + growSize);\n dst.set(src);\n this.data = new DataView(dst.buffer);\n\n return this;\n};\n\n/**\n * Puts a byte in this buffer.\n *\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putByte = function(b) {\n this.accommodate(1);\n this.data.setUint8(this.write++, b);\n return this;\n};\n\n/**\n * Puts a byte in this buffer N times.\n *\n * @param b the byte to put.\n * @param n the number of bytes of value b to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.fillWithByte = function(b, n) {\n this.accommodate(n);\n for(var i = 0; i < n; ++i) {\n this.data.setUint8(b);\n }\n return this;\n};\n\n/**\n * Puts bytes in this buffer. The bytes may be given as a string, an\n * ArrayBuffer, a DataView, or a TypedArray.\n *\n * @param bytes the bytes to put.\n * @param [encoding] the encoding for the first parameter ('binary', 'utf8',\n * 'utf16', 'hex'), if it is a string (default: 'binary').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBytes = function(bytes, encoding) {\n if(util.isArrayBufferView(bytes)) {\n var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n var len = src.byteLength - src.byteOffset;\n this.accommodate(len);\n var dst = new Uint8Array(this.data.buffer, this.write);\n dst.set(src);\n this.write += len;\n return this;\n }\n\n if(util.isArrayBuffer(bytes)) {\n var src = new Uint8Array(bytes);\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(this.data.buffer);\n dst.set(src, this.write);\n this.write += src.byteLength;\n return this;\n }\n\n // bytes is a util.DataBuffer or equivalent\n if(bytes instanceof util.DataBuffer ||\n (typeof bytes === 'object' &&\n typeof bytes.read === 'number' && typeof bytes.write === 'number' &&\n util.isArrayBufferView(bytes.data))) {\n var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());\n this.accommodate(src.byteLength);\n var dst = new Uint8Array(bytes.data.byteLength, this.write);\n dst.set(src);\n this.write += src.byteLength;\n return this;\n }\n\n if(bytes instanceof util.ByteStringBuffer) {\n // copy binary string and process as the same as a string parameter below\n bytes = bytes.data;\n encoding = 'binary';\n }\n\n // string conversion\n encoding = encoding || 'binary';\n if(typeof bytes === 'string') {\n var view;\n\n // decode from string\n if(encoding === 'hex') {\n this.accommodate(Math.ceil(bytes.length / 2));\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.hex.decode(bytes, view, this.write);\n return this;\n }\n if(encoding === 'base64') {\n this.accommodate(Math.ceil(bytes.length / 4) * 3);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.base64.decode(bytes, view, this.write);\n return this;\n }\n\n // encode text as UTF-8 bytes\n if(encoding === 'utf8') {\n // encode as UTF-8 then decode string as raw binary\n bytes = util.encodeUtf8(bytes);\n encoding = 'binary';\n }\n\n // decode string as raw binary\n if(encoding === 'binary' || encoding === 'raw') {\n // one byte per character\n this.accommodate(bytes.length);\n view = new Uint8Array(this.data.buffer, this.write);\n this.write += util.binary.raw.decode(view);\n return this;\n }\n\n // encode text as UTF-16 bytes\n if(encoding === 'utf16') {\n // two bytes per character\n this.accommodate(bytes.length * 2);\n view = new Uint16Array(this.data.buffer, this.write);\n this.write += util.text.utf16.encode(view);\n return this;\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n }\n\n throw Error('Invalid parameter: ' + bytes);\n};\n\n/**\n * Puts the given buffer into this buffer.\n *\n * @param buffer the buffer to put into this one.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putBuffer = function(buffer) {\n this.putBytes(buffer);\n buffer.clear();\n return this;\n};\n\n/**\n * Puts a string into this buffer.\n *\n * @param str the string to put.\n * @param [encoding] the encoding for the string (default: 'utf16').\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putString = function(str) {\n return this.putBytes(str, 'utf16');\n};\n\n/**\n * Puts a 16-bit integer in this buffer in big-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16 = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in big-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24 = function(i) {\n this.accommodate(3);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in big-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32 = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts a 16-bit integer in this buffer in little-endian order.\n *\n * @param i the 16-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt16Le = function(i) {\n this.accommodate(2);\n this.data.setInt16(this.write, i, true);\n this.write += 2;\n return this;\n};\n\n/**\n * Puts a 24-bit integer in this buffer in little-endian order.\n *\n * @param i the 24-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt24Le = function(i) {\n this.accommodate(3);\n this.data.setInt8(this.write, i >> 16 & 0xFF);\n this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);\n this.write += 3;\n return this;\n};\n\n/**\n * Puts a 32-bit integer in this buffer in little-endian order.\n *\n * @param i the 32-bit integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt32Le = function(i) {\n this.accommodate(4);\n this.data.setInt32(this.write, i, true);\n this.write += 4;\n return this;\n};\n\n/**\n * Puts an n-bit integer in this buffer in big-endian order.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n do {\n n -= 8;\n this.data.setInt8(this.write++, (i >> n) & 0xFF);\n } while(n > 0);\n return this;\n};\n\n/**\n * Puts a signed n-bit integer in this buffer in big-endian order. Two's\n * complement representation is used.\n *\n * @param i the n-bit integer.\n * @param n the number of bits in the integer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.putSignedInt = function(i, n) {\n _checkBitsParam(n);\n this.accommodate(n / 8);\n if(i < 0) {\n i += 2 << (n - 1);\n }\n return this.putInt(i, n);\n};\n\n/**\n * Gets a byte from this buffer and advances the read pointer by 1.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.getByte = function() {\n return this.data.getInt8(this.read++);\n};\n\n/**\n * Gets a uint16 from this buffer in big-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16 = function() {\n var rval = this.data.getInt16(this.read);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in big-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24 = function() {\n var rval = (\n this.data.getInt16(this.read) << 8 ^\n this.data.getInt8(this.read + 2));\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in big-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32 = function() {\n var rval = this.data.getInt32(this.read);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets a uint16 from this buffer in little-endian order and advances the read\n * pointer by 2.\n *\n * @return the uint16.\n */\nutil.DataBuffer.prototype.getInt16Le = function() {\n var rval = this.data.getInt16(this.read, true);\n this.read += 2;\n return rval;\n};\n\n/**\n * Gets a uint24 from this buffer in little-endian order and advances the read\n * pointer by 3.\n *\n * @return the uint24.\n */\nutil.DataBuffer.prototype.getInt24Le = function() {\n var rval = (\n this.data.getInt8(this.read) ^\n this.data.getInt16(this.read + 1, true) << 8);\n this.read += 3;\n return rval;\n};\n\n/**\n * Gets a uint32 from this buffer in little-endian order and advances the read\n * pointer by 4.\n *\n * @return the word.\n */\nutil.DataBuffer.prototype.getInt32Le = function() {\n var rval = this.data.getInt32(this.read, true);\n this.read += 4;\n return rval;\n};\n\n/**\n * Gets an n-bit integer from this buffer in big-endian order and advances the\n * read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getInt = function(n) {\n _checkBitsParam(n);\n var rval = 0;\n do {\n // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.\n rval = (rval << 8) + this.data.getInt8(this.read++);\n n -= 8;\n } while(n > 0);\n return rval;\n};\n\n/**\n * Gets a signed n-bit integer from this buffer in big-endian order, using\n * two's complement, and advances the read pointer by n/8.\n *\n * @param n the number of bits in the integer (8, 16, 24, or 32).\n *\n * @return the integer.\n */\nutil.DataBuffer.prototype.getSignedInt = function(n) {\n // getInt checks n\n var x = this.getInt(n);\n var max = 2 << (n - 2);\n if(x >= max) {\n x -= max << 1;\n }\n return x;\n};\n\n/**\n * Reads bytes out as a binary encoded string and clears them from the\n * buffer.\n *\n * @param count the number of bytes to read, undefined or null for all.\n *\n * @return a binary encoded string of bytes.\n */\nutil.DataBuffer.prototype.getBytes = function(count) {\n // TODO: deprecate this method, it is poorly named and\n // this.toString('binary') replaces it\n // add a toTypedArray()/toArrayBuffer() function\n var rval;\n if(count) {\n // read count bytes\n count = Math.min(this.length(), count);\n rval = this.data.slice(this.read, this.read + count);\n this.read += count;\n } else if(count === 0) {\n rval = '';\n } else {\n // read all bytes, optimize to only copy when needed\n rval = (this.read === 0) ? this.data : this.data.slice(this.read);\n this.clear();\n }\n return rval;\n};\n\n/**\n * Gets a binary encoded string of the bytes from this buffer without\n * modifying the read pointer.\n *\n * @param count the number of bytes to get, omit to get all.\n *\n * @return a string full of binary encoded characters.\n */\nutil.DataBuffer.prototype.bytes = function(count) {\n // TODO: deprecate this method, it is poorly named, add \"getString()\"\n return (typeof(count) === 'undefined' ?\n this.data.slice(this.read) :\n this.data.slice(this.read, this.read + count));\n};\n\n/**\n * Gets a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n *\n * @return the byte.\n */\nutil.DataBuffer.prototype.at = function(i) {\n return this.data.getUint8(this.read + i);\n};\n\n/**\n * Puts a byte at the given index without modifying the read pointer.\n *\n * @param i the byte index.\n * @param b the byte to put.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.setAt = function(i, b) {\n this.data.setUint8(i, b);\n return this;\n};\n\n/**\n * Gets the last byte without modifying the read pointer.\n *\n * @return the last byte.\n */\nutil.DataBuffer.prototype.last = function() {\n return this.data.getUint8(this.write - 1);\n};\n\n/**\n * Creates a copy of this buffer.\n *\n * @return the copy.\n */\nutil.DataBuffer.prototype.copy = function() {\n return new util.DataBuffer(this);\n};\n\n/**\n * Compacts this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.compact = function() {\n if(this.read > 0) {\n var src = new Uint8Array(this.data.buffer, this.read);\n var dst = new Uint8Array(src.byteLength);\n dst.set(src);\n this.data = new DataView(dst);\n this.write -= this.read;\n this.read = 0;\n }\n return this;\n};\n\n/**\n * Clears this buffer.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.clear = function() {\n this.data = new DataView(new ArrayBuffer(0));\n this.read = this.write = 0;\n return this;\n};\n\n/**\n * Shortens this buffer by triming bytes off of the end of this buffer.\n *\n * @param count the number of bytes to trim off.\n *\n * @return this buffer.\n */\nutil.DataBuffer.prototype.truncate = function(count) {\n this.write = Math.max(0, this.length() - count);\n this.read = Math.min(this.read, this.write);\n return this;\n};\n\n/**\n * Converts this buffer to a hexadecimal string.\n *\n * @return a hexadecimal string.\n */\nutil.DataBuffer.prototype.toHex = function() {\n var rval = '';\n for(var i = this.read; i < this.data.byteLength; ++i) {\n var b = this.data.getUint8(i);\n if(b < 16) {\n rval += '0';\n }\n rval += b.toString(16);\n }\n return rval;\n};\n\n/**\n * Converts this buffer to a string, using the given encoding. If no\n * encoding is given, 'utf8' (UTF-8) is used.\n *\n * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',\n * 'base64' (default: 'utf8').\n *\n * @return a string representation of the bytes in this buffer.\n */\nutil.DataBuffer.prototype.toString = function(encoding) {\n var view = new Uint8Array(this.data, this.read, this.length());\n encoding = encoding || 'utf8';\n\n // encode to string\n if(encoding === 'binary' || encoding === 'raw') {\n return util.binary.raw.encode(view);\n }\n if(encoding === 'hex') {\n return util.binary.hex.encode(view);\n }\n if(encoding === 'base64') {\n return util.binary.base64.encode(view);\n }\n\n // decode to text\n if(encoding === 'utf8') {\n return util.text.utf8.decode(view);\n }\n if(encoding === 'utf16') {\n return util.text.utf16.decode(view);\n }\n\n throw new Error('Invalid encoding: ' + encoding);\n};\n\n/** End Buffer w/UInt8Array backing */\n\n/**\n * Creates a buffer that stores bytes. A value may be given to populate the\n * buffer with data. This value can either be string of encoded bytes or a\n * regular string of characters. When passing a string of binary encoded\n * bytes, the encoding `raw` should be given. This is also the default. When\n * passing a string of characters, the encoding `utf8` should be given.\n *\n * @param [input] a string with encoded bytes to store in the buffer.\n * @param [encoding] (default: 'raw', other: 'utf8').\n */\nutil.createBuffer = function(input, encoding) {\n // TODO: deprecate, use new ByteBuffer() instead\n encoding = encoding || 'raw';\n if(input !== undefined && encoding === 'utf8') {\n input = util.encodeUtf8(input);\n }\n return new util.ByteBuffer(input);\n};\n\n/**\n * Fills a string with a particular value. If you want the string to be a byte\n * string, pass in String.fromCharCode(theByte).\n *\n * @param c the character to fill the string with, use String.fromCharCode\n * to fill the string with a byte value.\n * @param n the number of characters of value c to fill with.\n *\n * @return the filled string.\n */\nutil.fillString = function(c, n) {\n var s = '';\n while(n > 0) {\n if(n & 1) {\n s += c;\n }\n n >>>= 1;\n if(n > 0) {\n c += c;\n }\n }\n return s;\n};\n\n/**\n * Performs a per byte XOR between two byte strings and returns the result as a\n * string of bytes.\n *\n * @param s1 first string of bytes.\n * @param s2 second string of bytes.\n * @param n the number of bytes to XOR.\n *\n * @return the XOR'd result.\n */\nutil.xorBytes = function(s1, s2, n) {\n var s3 = '';\n var b = '';\n var t = '';\n var i = 0;\n var c = 0;\n for(; n > 0; --n, ++i) {\n b = s1.charCodeAt(i) ^ s2.charCodeAt(i);\n if(c >= 10) {\n s3 += t;\n t = '';\n c = 0;\n }\n t += String.fromCharCode(b);\n ++c;\n }\n s3 += t;\n return s3;\n};\n\n/**\n * Converts a hex string into a 'binary' encoded string of bytes.\n *\n * @param hex the hexadecimal string to convert.\n *\n * @return the binary-encoded string of bytes.\n */\nutil.hexToBytes = function(hex) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.decode instead.\"\n var rval = '';\n var i = 0;\n if(hex.length & 1 == 1) {\n // odd number of characters, convert first character alone\n i = 1;\n rval += String.fromCharCode(parseInt(hex[0], 16));\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n }\n return rval;\n};\n\n/**\n * Converts a 'binary' encoded string of bytes to hex.\n *\n * @param bytes the byte string to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.bytesToHex = function(bytes) {\n // TODO: deprecate: \"Deprecated. Use util.binary.hex.encode instead.\"\n return util.createBuffer(bytes).toHex();\n};\n\n/**\n * Converts an 32-bit integer to 4-big-endian byte string.\n *\n * @param i the integer.\n *\n * @return the byte string.\n */\nutil.int32ToBytes = function(i) {\n return (\n String.fromCharCode(i >> 24 & 0xFF) +\n String.fromCharCode(i >> 16 & 0xFF) +\n String.fromCharCode(i >> 8 & 0xFF) +\n String.fromCharCode(i & 0xFF));\n};\n\n// base64 characters, reverse mapping\nvar _base64 =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nvar _base64Idx = [\n/*43 -43 = 0*/\n/*'+', 1, 2, 3,'/' */\n 62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n -1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n -1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\n// base58 characters (Bitcoin alphabet)\nvar _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Base64 encodes a 'binary' encoded string of bytes.\n *\n * @param input the binary encoded string of bytes to base64-encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output.\n */\nutil.encode64 = function(input, maxline) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.encode instead.\"\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.length) {\n chr1 = input.charCodeAt(i++);\n chr2 = input.charCodeAt(i++);\n chr3 = input.charCodeAt(i++);\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Base64 decodes a string into a 'binary' encoded string of bytes.\n *\n * @param input the base64-encoded input.\n *\n * @return the binary encoded string.\n */\nutil.decode64 = function(input) {\n // TODO: deprecate: \"Deprecated. Use util.binary.base64.decode instead.\"\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n var output = '';\n var enc1, enc2, enc3, enc4;\n var i = 0;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));\n if(enc4 !== 64) {\n // decoded 3 bytes\n output += String.fromCharCode(((enc3 & 3) << 6) | enc4);\n }\n }\n }\n\n return output;\n};\n\n/**\n * Encodes the given string of characters (a standard JavaScript\n * string) as a binary encoded string where the bytes represent\n * a UTF-8 encoded string of characters. Non-ASCII characters will be\n * encoded as multiple bytes according to UTF-8.\n *\n * @param str a standard string of characters to encode.\n *\n * @return the binary encoded string.\n */\nutil.encodeUtf8 = function(str) {\n return unescape(encodeURIComponent(str));\n};\n\n/**\n * Decodes a binary encoded string that contains bytes that\n * represent a UTF-8 encoded string of characters -- into a\n * string of characters (a standard JavaScript string).\n *\n * @param str the binary encoded string to decode.\n *\n * @return the resulting standard string of characters.\n */\nutil.decodeUtf8 = function(str) {\n return decodeURIComponent(escape(str));\n};\n\n// binary encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.binary = {\n raw: {},\n hex: {},\n base64: {},\n base58: {},\n baseN : {\n encode: baseN.encode,\n decode: baseN.decode\n }\n};\n\n/**\n * Encodes a Uint8Array as a binary-encoded string. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param bytes the Uint8Array to encode.\n *\n * @return the binary-encoded string.\n */\nutil.binary.raw.encode = function(bytes) {\n return String.fromCharCode.apply(null, bytes);\n};\n\n/**\n * Decodes a binary-encoded string to a Uint8Array. This encoding uses\n * a value between 0 and 255 for each character.\n *\n * @param str the binary-encoded string to decode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.raw.decode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or\n * ByteBuffer as a string of hexadecimal characters.\n *\n * @param bytes the bytes to convert.\n *\n * @return the string of hexadecimal characters.\n */\nutil.binary.hex.encode = util.bytesToHex;\n\n/**\n * Decodes a hex-encoded string to a Uint8Array.\n *\n * @param hex the hexadecimal string to convert.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.hex.decode = function(hex, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(hex.length / 2));\n }\n offset = offset || 0;\n var i = 0, j = offset;\n if(hex.length & 1) {\n // odd number of characters, convert first character alone\n i = 1;\n out[j++] = parseInt(hex[0], 16);\n }\n // convert 2 characters (1 byte) at a time\n for(; i < hex.length; i += 2) {\n out[j++] = parseInt(hex.substr(i, 2), 16);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Base64-encodes a Uint8Array.\n *\n * @param input the Uint8Array to encode.\n * @param maxline the maximum number of encoded characters per line to use,\n * defaults to none.\n *\n * @return the base64-encoded output string.\n */\nutil.binary.base64.encode = function(input, maxline) {\n var line = '';\n var output = '';\n var chr1, chr2, chr3;\n var i = 0;\n while(i < input.byteLength) {\n chr1 = input[i++];\n chr2 = input[i++];\n chr3 = input[i++];\n\n // encode 4 character group\n line += _base64.charAt(chr1 >> 2);\n line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));\n if(isNaN(chr2)) {\n line += '==';\n } else {\n line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));\n line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);\n }\n\n if(maxline && line.length > maxline) {\n output += line.substr(0, maxline) + '\\r\\n';\n line = line.substr(maxline);\n }\n }\n output += line;\n return output;\n};\n\n/**\n * Decodes a base64-encoded string to a Uint8Array.\n *\n * @param input the base64-encoded input string.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.binary.base64.decode = function(input, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n }\n\n // remove all non-base64 characters\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\n offset = offset || 0;\n var enc1, enc2, enc3, enc4;\n var i = 0, j = offset;\n\n while(i < input.length) {\n enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n out[j++] = (enc1 << 2) | (enc2 >> 4);\n if(enc3 !== 64) {\n // decoded at least 2 bytes\n out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);\n if(enc4 !== 64) {\n // decoded 3 bytes\n out[j++] = ((enc3 & 3) << 6) | enc4;\n }\n }\n }\n\n // make sure result is the exact decoded length\n return output ? (j - offset) : out.subarray(0, j);\n};\n\n// add support for base58 encoding/decoding with Bitcoin alphabet\nutil.binary.base58.encode = function(input, maxline) {\n return util.binary.baseN.encode(input, _base58, maxline);\n};\nutil.binary.base58.decode = function(input, maxline) {\n return util.binary.baseN.decode(input, _base58, maxline);\n};\n\n// text encoding/decoding tools\n// FIXME: Experimental. Do not use yet.\nutil.text = {\n utf8: {},\n utf16: {}\n};\n\n/**\n * Encodes the given string as UTF-8 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf8.encode = function(str, output, offset) {\n str = util.encodeUtf8(str);\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length);\n }\n offset = offset || 0;\n var j = offset;\n for(var i = 0; i < str.length; ++i) {\n out[j++] = str.charCodeAt(i);\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-8 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf8.decode = function(bytes) {\n return util.decodeUtf8(String.fromCharCode.apply(null, bytes));\n};\n\n/**\n * Encodes the given string as UTF-16 in a Uint8Array.\n *\n * @param str the string to encode.\n * @param [output] an optional Uint8Array to write the output to; if it\n * is too small, an exception will be thrown.\n * @param [offset] the start offset for writing to the output (default: 0).\n *\n * @return the Uint8Array or the number of bytes written if output was given.\n */\nutil.text.utf16.encode = function(str, output, offset) {\n var out = output;\n if(!out) {\n out = new Uint8Array(str.length * 2);\n }\n var view = new Uint16Array(out.buffer);\n offset = offset || 0;\n var j = offset;\n var k = offset;\n for(var i = 0; i < str.length; ++i) {\n view[k++] = str.charCodeAt(i);\n j += 2;\n }\n return output ? (j - offset) : out;\n};\n\n/**\n * Decodes the UTF-16 contents from a Uint8Array.\n *\n * @param bytes the Uint8Array to decode.\n *\n * @return the resulting string.\n */\nutil.text.utf16.decode = function(bytes) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n};\n\n/**\n * Deflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true to return only raw deflate data, false to include zlib\n * header and trailer.\n *\n * @return the deflated data as a string.\n */\nutil.deflate = function(api, bytes, raw) {\n bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);\n\n // strip zlib header and trailer if necessary\n if(raw) {\n // zlib header is 2 bytes (CMF,FLG) where FLG indicates that\n // there is a 4-byte DICT (alder-32) block before the data if\n // its 5th bit is set\n var start = 2;\n var flg = bytes.charCodeAt(1);\n if(flg & 0x20) {\n start = 6;\n }\n // zlib trailer is 4 bytes of adler-32\n bytes = bytes.substring(start, bytes.length - 4);\n }\n\n return bytes;\n};\n\n/**\n * Inflates the given data using a flash interface.\n *\n * @param api the flash interface.\n * @param bytes the data.\n * @param raw true if the incoming data has no zlib header or trailer and is\n * raw DEFLATE data.\n *\n * @return the inflated data as a string, null on error.\n */\nutil.inflate = function(api, bytes, raw) {\n // TODO: add zlib header and trailer if necessary/possible\n var rval = api.inflate(util.encode64(bytes)).rval;\n return (rval === null) ? null : util.decode64(rval);\n};\n\n/**\n * Sets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param obj the storage object, null to remove.\n */\nvar _setStorageObject = function(api, id, obj) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n var rval;\n if(obj === null) {\n rval = api.removeItem(id);\n } else {\n // json-encode and base64-encode object\n obj = util.encode64(JSON.stringify(obj));\n rval = api.setItem(id, obj);\n }\n\n // handle potential flash error\n if(typeof(rval) !== 'undefined' && rval.rval !== true) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n};\n\n/**\n * Gets a storage object.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n *\n * @return the storage object entry or null if none exists.\n */\nvar _getStorageObject = function(api, id) {\n if(!api) {\n throw new Error('WebStorage not available.');\n }\n\n // get the existing entry\n var rval = api.getItem(id);\n\n /* Note: We check api.init because we can't do (api == localStorage)\n on IE because of \"Class doesn't support Automation\" exception. Only\n the flash api has an init method so this works too, but we need a\n better solution in the future. */\n\n // flash returns item wrapped in an object, handle special case\n if(api.init) {\n if(rval.rval === null) {\n if(rval.error) {\n var error = new Error(rval.error.message);\n error.id = rval.error.id;\n error.name = rval.error.name;\n throw error;\n }\n // no error, but also no item\n rval = null;\n } else {\n rval = rval.rval;\n }\n }\n\n // handle decoding\n if(rval !== null) {\n // base64-decode and json-decode data\n rval = JSON.parse(util.decode64(rval));\n }\n\n return rval;\n};\n\n/**\n * Stores an item in local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n */\nvar _setItem = function(api, id, key, data) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj === null) {\n // create a new storage object\n obj = {};\n }\n // update key\n obj[key] = data;\n\n // set storage object\n _setStorageObject(api, id, obj);\n};\n\n/**\n * Gets an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n *\n * @return the item.\n */\nvar _getItem = function(api, id, key) {\n // get storage object\n var rval = _getStorageObject(api, id);\n if(rval !== null) {\n // return data at key\n rval = (key in rval) ? rval[key] : null;\n }\n\n return rval;\n};\n\n/**\n * Removes an item from local storage.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n */\nvar _removeItem = function(api, id, key) {\n // get storage object\n var obj = _getStorageObject(api, id);\n if(obj !== null && key in obj) {\n // remove key\n delete obj[key];\n\n // see if entry has no keys remaining\n var empty = true;\n for(var prop in obj) {\n empty = false;\n break;\n }\n if(empty) {\n // remove entry entirely if no keys are left\n obj = null;\n }\n\n // set storage object\n _setStorageObject(api, id, obj);\n }\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * @param api the storage interface.\n * @param id the storage ID to use.\n */\nvar _clearItems = function(api, id) {\n _setStorageObject(api, id, null);\n};\n\n/**\n * Calls a storage function.\n *\n * @param func the function to call.\n * @param args the arguments for the function.\n * @param location the location argument.\n *\n * @return the return value from the function.\n */\nvar _callStorageFunction = function(func, args, location) {\n var rval = null;\n\n // default storage types\n if(typeof(location) === 'undefined') {\n location = ['web', 'flash'];\n }\n\n // apply storage types in order of preference\n var type;\n var done = false;\n var exception = null;\n for(var idx in location) {\n type = location[idx];\n try {\n if(type === 'flash' || type === 'both') {\n if(args[0] === null) {\n throw new Error('Flash local storage not available.');\n }\n rval = func.apply(this, args);\n done = (type === 'flash');\n }\n if(type === 'web' || type === 'both') {\n args[0] = localStorage;\n rval = func.apply(this, args);\n done = true;\n }\n } catch(ex) {\n exception = ex;\n }\n if(done) {\n break;\n }\n }\n\n if(!done) {\n throw exception;\n }\n\n return rval;\n};\n\n/**\n * Stores an item on local disk.\n *\n * The available types of local storage include 'flash', 'web', and 'both'.\n *\n * The type 'flash' refers to flash local storage (SharedObject). In order\n * to use flash local storage, the 'api' parameter must be valid. The type\n * 'web' refers to WebStorage, if supported by the browser. The type 'both'\n * refers to storing using both 'flash' and 'web', not just one or the\n * other.\n *\n * The location array should list the storage types to use in order of\n * preference:\n *\n * ['flash']: flash only storage\n * ['web']: web only storage\n * ['both']: try to store in both\n * ['flash','web']: store in flash first, but if not available, 'web'\n * ['web','flash']: store in web first, but if not available, 'flash'\n *\n * The location array defaults to: ['web', 'flash']\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param data the data for the item (any javascript object/primitive).\n * @param location an array with the preferred types of storage to use.\n */\nutil.setItem = function(api, id, key, data, location) {\n _callStorageFunction(_setItem, arguments, location);\n};\n\n/**\n * Gets an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface, null to use only WebStorage.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n *\n * @return the item.\n */\nutil.getItem = function(api, id, key, location) {\n return _callStorageFunction(_getItem, arguments, location);\n};\n\n/**\n * Removes an item on local disk.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface.\n * @param id the storage ID to use.\n * @param key the key for the item.\n * @param location an array with the preferred types of storage to use.\n */\nutil.removeItem = function(api, id, key, location) {\n _callStorageFunction(_removeItem, arguments, location);\n};\n\n/**\n * Clears the local disk storage identified by the given ID.\n *\n * Set setItem() for details on storage types.\n *\n * @param api the flash interface if flash is available.\n * @param id the storage ID to use.\n * @param location an array with the preferred types of storage to use.\n */\nutil.clearItems = function(api, id, location) {\n _callStorageFunction(_clearItems, arguments, location);\n};\n\n/**\n * Check if an object is empty.\n *\n * Taken from:\n * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937\n *\n * @param object the object to check.\n */\nutil.isEmpty = function(obj) {\n for(var prop in obj) {\n if(obj.hasOwnProperty(prop)) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Format with simple printf-style interpolation.\n *\n * %%: literal '%'\n * %s,%o: convert next argument into a string.\n *\n * @param format the string to format.\n * @param ... arguments to interpolate into the format string.\n */\nutil.format = function(format) {\n var re = /%./g;\n // current match\n var match;\n // current part\n var part;\n // current arg index\n var argi = 0;\n // collected parts to recombine later\n var parts = [];\n // last index found\n var last = 0;\n // loop while matches remain\n while((match = re.exec(format))) {\n part = format.substring(last, re.lastIndex - 2);\n // don't add empty strings (ie, parts between %s%s)\n if(part.length > 0) {\n parts.push(part);\n }\n last = re.lastIndex;\n // switch on % code\n var code = match[0][1];\n switch(code) {\n case 's':\n case 'o':\n // check if enough arguments were given\n if(argi < arguments.length) {\n parts.push(arguments[argi++ + 1]);\n } else {\n parts.push('');\n }\n break;\n // FIXME: do proper formating for numbers, etc\n //case 'f':\n //case 'd':\n case '%':\n parts.push('%');\n break;\n default:\n parts.push('<%' + code + '?>');\n }\n }\n // add trailing part of format string\n parts.push(format.substring(last));\n return parts.join('');\n};\n\n/**\n * Formats a number.\n *\n * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/\n */\nutil.formatNumber = function(number, decimals, dec_point, thousands_sep) {\n // http://kevin.vanzonneveld.net\n // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)\n // + bugfix by: Michael White (http://crestidg.com)\n // + bugfix by: Benjamin Lupton\n // + bugfix by: Allan Jensen (http://www.winternet.no)\n // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)\n // * example 1: number_format(1234.5678, 2, '.', '');\n // * returns 1: 1234.57\n\n var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;\n var d = dec_point === undefined ? ',' : dec_point;\n var t = thousands_sep === undefined ?\n '.' : thousands_sep, s = n < 0 ? '-' : '';\n var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';\n var j = (i.length > 3) ? i.length % 3 : 0;\n return s + (j ? i.substr(0, j) + t : '') +\n i.substr(j).replace(/(\\d{3})(?=\\d)/g, '$1' + t) +\n (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');\n};\n\n/**\n * Formats a byte size.\n *\n * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/\n */\nutil.formatSize = function(size) {\n if(size >= 1073741824) {\n size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';\n } else if(size >= 1048576) {\n size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB';\n } else if(size >= 1024) {\n size = util.formatNumber(size / 1024, 0) + ' KiB';\n } else {\n size = util.formatNumber(size, 0) + ' bytes';\n }\n return size;\n};\n\n/**\n * Converts an IPv4 or IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv4 or IPv6 address to convert.\n *\n * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't\n * be parsed.\n */\nutil.bytesFromIP = function(ip) {\n if(ip.indexOf('.') !== -1) {\n return util.bytesFromIPv4(ip);\n }\n if(ip.indexOf(':') !== -1) {\n return util.bytesFromIPv6(ip);\n }\n return null;\n};\n\n/**\n * Converts an IPv4 string representation into bytes (in network order).\n *\n * @param ip the IPv4 address to convert.\n *\n * @return the 4-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv4 = function(ip) {\n ip = ip.split('.');\n if(ip.length !== 4) {\n return null;\n }\n var b = util.createBuffer();\n for(var i = 0; i < ip.length; ++i) {\n var num = parseInt(ip[i], 10);\n if(isNaN(num)) {\n return null;\n }\n b.putByte(num);\n }\n return b.getBytes();\n};\n\n/**\n * Converts an IPv6 string representation into bytes (in network order).\n *\n * @param ip the IPv6 address to convert.\n *\n * @return the 16-byte address or null if the address can't be parsed.\n */\nutil.bytesFromIPv6 = function(ip) {\n var blanks = 0;\n ip = ip.split(':').filter(function(e) {\n if(e.length === 0) ++blanks;\n return true;\n });\n var zeros = (8 - ip.length + blanks) * 2;\n var b = util.createBuffer();\n for(var i = 0; i < 8; ++i) {\n if(!ip[i] || ip[i].length === 0) {\n b.fillWithByte(0, zeros);\n zeros = 0;\n continue;\n }\n var bytes = util.hexToBytes(ip[i]);\n if(bytes.length < 2) {\n b.putByte(0);\n }\n b.putBytes(bytes);\n }\n return b.getBytes();\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation or 16-bytes into\n * an IPv6 string representation. The bytes must be in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,\n * respectively, are given, otherwise null.\n */\nutil.bytesToIP = function(bytes) {\n if(bytes.length === 4) {\n return util.bytesToIPv4(bytes);\n }\n if(bytes.length === 16) {\n return util.bytesToIPv6(bytes);\n }\n return null;\n};\n\n/**\n * Converts 4-bytes into an IPv4 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv4 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv4 = function(bytes) {\n if(bytes.length !== 4) {\n return null;\n }\n var ip = [];\n for(var i = 0; i < bytes.length; ++i) {\n ip.push(bytes.charCodeAt(i));\n }\n return ip.join('.');\n};\n\n/**\n * Converts 16-bytes into an IPv16 string representation. The bytes must be\n * in network order.\n *\n * @param bytes the bytes to convert.\n *\n * @return the IPv16 string representation or null for an invalid # of bytes.\n */\nutil.bytesToIPv6 = function(bytes) {\n if(bytes.length !== 16) {\n return null;\n }\n var ip = [];\n var zeroGroups = [];\n var zeroMaxGroup = 0;\n for(var i = 0; i < bytes.length; i += 2) {\n var hex = util.bytesToHex(bytes[i] + bytes[i + 1]);\n // canonicalize zero representation\n while(hex[0] === '0' && hex !== '0') {\n hex = hex.substr(1);\n }\n if(hex === '0') {\n var last = zeroGroups[zeroGroups.length - 1];\n var idx = ip.length;\n if(!last || idx !== last.end + 1) {\n zeroGroups.push({start: idx, end: idx});\n } else {\n last.end = idx;\n if((last.end - last.start) >\n (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {\n zeroMaxGroup = zeroGroups.length - 1;\n }\n }\n }\n ip.push(hex);\n }\n if(zeroGroups.length > 0) {\n var group = zeroGroups[zeroMaxGroup];\n // only shorten group of length > 0\n if(group.end - group.start > 0) {\n ip.splice(group.start, group.end - group.start + 1, '');\n if(group.start === 0) {\n ip.unshift('');\n }\n if(group.end === 7) {\n ip.push('');\n }\n }\n }\n return ip.join(':');\n};\n\n/**\n * Estimates the number of processes that can be run concurrently. If\n * creating Web Workers, keep in mind that the main JavaScript process needs\n * its own core.\n *\n * @param options the options to use:\n * update true to force an update (not use the cached value).\n * @param callback(err, max) called once the operation completes.\n */\nutil.estimateCores = function(options, callback) {\n if(typeof options === 'function') {\n callback = options;\n options = {};\n }\n options = options || {};\n if('cores' in util && !options.update) {\n return callback(null, util.cores);\n }\n if(typeof navigator !== 'undefined' &&\n 'hardwareConcurrency' in navigator &&\n navigator.hardwareConcurrency > 0) {\n util.cores = navigator.hardwareConcurrency;\n return callback(null, util.cores);\n }\n if(typeof Worker === 'undefined') {\n // workers not available\n util.cores = 1;\n return callback(null, util.cores);\n }\n if(typeof Blob === 'undefined') {\n // can't estimate, default to 2\n util.cores = 2;\n return callback(null, util.cores);\n }\n\n // create worker concurrency estimation code as blob\n var blobUrl = URL.createObjectURL(new Blob(['(',\n function() {\n self.addEventListener('message', function(e) {\n // run worker for 4 ms\n var st = Date.now();\n var et = st + 4;\n while(Date.now() < et);\n self.postMessage({st: st, et: et});\n });\n }.toString(),\n ')()'], {type: 'application/javascript'}));\n\n // take 5 samples using 16 workers\n sample([], 5, 16);\n\n function sample(max, samples, numWorkers) {\n if(samples === 0) {\n // get overlap average\n var avg = Math.floor(max.reduce(function(avg, x) {\n return avg + x;\n }, 0) / max.length);\n util.cores = Math.max(1, avg);\n URL.revokeObjectURL(blobUrl);\n return callback(null, util.cores);\n }\n map(numWorkers, function(err, results) {\n max.push(reduce(numWorkers, results));\n sample(max, samples - 1, numWorkers);\n });\n }\n\n function map(numWorkers, callback) {\n var workers = [];\n var results = [];\n for(var i = 0; i < numWorkers; ++i) {\n var worker = new Worker(blobUrl);\n worker.addEventListener('message', function(e) {\n results.push(e.data);\n if(results.length === numWorkers) {\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].terminate();\n }\n callback(null, results);\n }\n });\n workers.push(worker);\n }\n for(var i = 0; i < numWorkers; ++i) {\n workers[i].postMessage(i);\n }\n }\n\n function reduce(numWorkers, results) {\n // find overlapping time windows\n var overlaps = [];\n for(var n = 0; n < numWorkers; ++n) {\n var r1 = results[n];\n var overlap = overlaps[n] = [];\n for(var i = 0; i < numWorkers; ++i) {\n if(n === i) {\n continue;\n }\n var r2 = results[i];\n if((r1.st > r2.st && r1.st < r2.et) ||\n (r2.st > r1.st && r2.st < r1.et)) {\n overlap.push(i);\n }\n }\n }\n // get maximum overlaps ... don't include overlapping worker itself\n // as the main JS process was also being scheduled during the work and\n // would have to be subtracted from the estimate anyway\n return overlaps.reduce(function(max, overlap) {\n return Math.max(max, overlap.length);\n }, 0);\n }\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/node-forge/lib/util.js?"); + +/***/ }), + +/***/ "./node_modules/parse-asn1/asn1.js": +/*!*****************************************!*\ + !*** ./node_modules/parse-asn1/asn1.js ***! + \*****************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js\n// Fedor, you are amazing.\n\n\n\nvar asn1 = __webpack_require__(/*! asn1.js */ \"./node_modules/asn1.js/lib/asn1.js\");\n\nexports.certificate = __webpack_require__(/*! ./certificate */ \"./node_modules/parse-asn1/certificate.js\");\n\nvar RSAPrivateKey = asn1.define('RSAPrivateKey', function () {\n\tthis.seq().obj(\n\t\tthis.key('version')['int'](),\n\t\tthis.key('modulus')['int'](),\n\t\tthis.key('publicExponent')['int'](),\n\t\tthis.key('privateExponent')['int'](),\n\t\tthis.key('prime1')['int'](),\n\t\tthis.key('prime2')['int'](),\n\t\tthis.key('exponent1')['int'](),\n\t\tthis.key('exponent2')['int'](),\n\t\tthis.key('coefficient')['int']()\n\t);\n});\nexports.RSAPrivateKey = RSAPrivateKey;\n\nvar RSAPublicKey = asn1.define('RSAPublicKey', function () {\n\tthis.seq().obj(\n\t\tthis.key('modulus')['int'](),\n\t\tthis.key('publicExponent')['int']()\n\t);\n});\nexports.RSAPublicKey = RSAPublicKey;\n\nvar AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {\n\tthis.seq().obj(\n\t\tthis.key('algorithm').objid(),\n\t\tthis.key('none').null_().optional(),\n\t\tthis.key('curve').objid().optional(),\n\t\tthis.key('params').seq().obj(\n\t\t\tthis.key('p')['int'](),\n\t\t\tthis.key('q')['int'](),\n\t\t\tthis.key('g')['int']()\n\t\t).optional()\n\t);\n});\n\nvar PublicKey = asn1.define('SubjectPublicKeyInfo', function () {\n\tthis.seq().obj(\n\t\tthis.key('algorithm').use(AlgorithmIdentifier),\n\t\tthis.key('subjectPublicKey').bitstr()\n\t);\n});\nexports.PublicKey = PublicKey;\n\nvar PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {\n\tthis.seq().obj(\n\t\tthis.key('version')['int'](),\n\t\tthis.key('algorithm').use(AlgorithmIdentifier),\n\t\tthis.key('subjectPrivateKey').octstr()\n\t);\n});\nexports.PrivateKey = PrivateKeyInfo;\nvar EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {\n\tthis.seq().obj(\n\t\tthis.key('algorithm').seq().obj(\n\t\t\tthis.key('id').objid(),\n\t\t\tthis.key('decrypt').seq().obj(\n\t\t\t\tthis.key('kde').seq().obj(\n\t\t\t\t\tthis.key('id').objid(),\n\t\t\t\t\tthis.key('kdeparams').seq().obj(\n\t\t\t\t\t\tthis.key('salt').octstr(),\n\t\t\t\t\t\tthis.key('iters')['int']()\n\t\t\t\t\t)\n\t\t\t\t),\n\t\t\t\tthis.key('cipher').seq().obj(\n\t\t\t\t\tthis.key('algo').objid(),\n\t\t\t\t\tthis.key('iv').octstr()\n\t\t\t\t)\n\t\t\t)\n\t\t),\n\t\tthis.key('subjectPrivateKey').octstr()\n\t);\n});\n\nexports.EncryptedPrivateKey = EncryptedPrivateKeyInfo;\n\nvar DSAPrivateKey = asn1.define('DSAPrivateKey', function () {\n\tthis.seq().obj(\n\t\tthis.key('version')['int'](),\n\t\tthis.key('p')['int'](),\n\t\tthis.key('q')['int'](),\n\t\tthis.key('g')['int'](),\n\t\tthis.key('pub_key')['int'](),\n\t\tthis.key('priv_key')['int']()\n\t);\n});\nexports.DSAPrivateKey = DSAPrivateKey;\n\nexports.DSAparam = asn1.define('DSAparam', function () {\n\tthis['int']();\n});\n\nvar ECParameters = asn1.define('ECParameters', function () {\n\tthis.choice({\n\t\tnamedCurve: this.objid()\n\t});\n});\n\nvar ECPrivateKey = asn1.define('ECPrivateKey', function () {\n\tthis.seq().obj(\n\t\tthis.key('version')['int'](),\n\t\tthis.key('privateKey').octstr(),\n\t\tthis.key('parameters').optional().explicit(0).use(ECParameters),\n\t\tthis.key('publicKey').optional().explicit(1).bitstr()\n\t);\n});\nexports.ECPrivateKey = ECPrivateKey;\n\nexports.signature = asn1.define('signature', function () {\n\tthis.seq().obj(\n\t\tthis.key('r')['int'](),\n\t\tthis.key('s')['int']()\n\t);\n});\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/parse-asn1/asn1.js?"); + +/***/ }), + +/***/ "./node_modules/parse-asn1/certificate.js": +/*!************************************************!*\ + !*** ./node_modules/parse-asn1/certificate.js ***! + \************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js\n// thanks to @Rantanen\n\n\n\nvar asn = __webpack_require__(/*! asn1.js */ \"./node_modules/asn1.js/lib/asn1.js\");\n\nvar Time = asn.define('Time', function () {\n\tthis.choice({\n\t\tutcTime: this.utctime(),\n\t\tgeneralTime: this.gentime()\n\t});\n});\n\nvar AttributeTypeValue = asn.define('AttributeTypeValue', function () {\n\tthis.seq().obj(\n\t\tthis.key('type').objid(),\n\t\tthis.key('value').any()\n\t);\n});\n\nvar AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {\n\tthis.seq().obj(\n\t\tthis.key('algorithm').objid(),\n\t\tthis.key('parameters').optional(),\n\t\tthis.key('curve').objid().optional()\n\t);\n});\n\nvar SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {\n\tthis.seq().obj(\n\t\tthis.key('algorithm').use(AlgorithmIdentifier),\n\t\tthis.key('subjectPublicKey').bitstr()\n\t);\n});\n\nvar RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {\n\tthis.setof(AttributeTypeValue);\n});\n\nvar RDNSequence = asn.define('RDNSequence', function () {\n\tthis.seqof(RelativeDistinguishedName);\n});\n\nvar Name = asn.define('Name', function () {\n\tthis.choice({\n\t\trdnSequence: this.use(RDNSequence)\n\t});\n});\n\nvar Validity = asn.define('Validity', function () {\n\tthis.seq().obj(\n\t\tthis.key('notBefore').use(Time),\n\t\tthis.key('notAfter').use(Time)\n\t);\n});\n\nvar Extension = asn.define('Extension', function () {\n\tthis.seq().obj(\n\t\tthis.key('extnID').objid(),\n\t\tthis.key('critical').bool().def(false),\n\t\tthis.key('extnValue').octstr()\n\t);\n});\n\nvar TBSCertificate = asn.define('TBSCertificate', function () {\n\tthis.seq().obj(\n\t\tthis.key('version').explicit(0)['int']().optional(),\n\t\tthis.key('serialNumber')['int'](),\n\t\tthis.key('signature').use(AlgorithmIdentifier),\n\t\tthis.key('issuer').use(Name),\n\t\tthis.key('validity').use(Validity),\n\t\tthis.key('subject').use(Name),\n\t\tthis.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),\n\t\tthis.key('issuerUniqueID').implicit(1).bitstr().optional(),\n\t\tthis.key('subjectUniqueID').implicit(2).bitstr().optional(),\n\t\tthis.key('extensions').explicit(3).seqof(Extension).optional()\n\t);\n});\n\nvar X509Certificate = asn.define('X509Certificate', function () {\n\tthis.seq().obj(\n\t\tthis.key('tbsCertificate').use(TBSCertificate),\n\t\tthis.key('signatureAlgorithm').use(AlgorithmIdentifier),\n\t\tthis.key('signatureValue').bitstr()\n\t);\n});\n\nmodule.exports = X509Certificate;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/parse-asn1/certificate.js?"); + +/***/ }), + +/***/ "./node_modules/parse-asn1/fixProc.js": +/*!********************************************!*\ + !*** ./node_modules/parse-asn1/fixProc.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\n// adapted from https://github.com/apatil/pemstrip\nvar findProc = /Proc-Type: 4,ENCRYPTED[\\n\\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\\n\\r]+([0-9A-z\\n\\r+/=]+)[\\n\\r]+/m;\nvar startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m;\nvar fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\\n\\r+/=]+)-----END \\1-----$/m;\nvar evp = __webpack_require__(/*! evp_bytestokey */ \"./node_modules/evp_bytestokey/index.js\");\nvar ciphers = __webpack_require__(/*! browserify-aes */ \"./node_modules/browserify-aes/browser.js\");\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\nmodule.exports = function (okey, password) {\n\tvar key = okey.toString();\n\tvar match = key.match(findProc);\n\tvar decrypted;\n\tif (!match) {\n\t\tvar match2 = key.match(fullRegex);\n\t\tdecrypted = Buffer.from(match2[2].replace(/[\\r\\n]/g, ''), 'base64');\n\t} else {\n\t\tvar suite = 'aes' + match[1];\n\t\tvar iv = Buffer.from(match[2], 'hex');\n\t\tvar cipherText = Buffer.from(match[3].replace(/[\\r\\n]/g, ''), 'base64');\n\t\tvar cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key;\n\t\tvar out = [];\n\t\tvar cipher = ciphers.createDecipheriv(suite, cipherKey, iv);\n\t\tout.push(cipher.update(cipherText));\n\t\tout.push(cipher['final']());\n\t\tdecrypted = Buffer.concat(out);\n\t}\n\tvar tag = key.match(startRegex)[1];\n\treturn {\n\t\ttag: tag,\n\t\tdata: decrypted\n\t};\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/parse-asn1/fixProc.js?"); + +/***/ }), + +/***/ "./node_modules/parse-asn1/index.js": +/*!******************************************!*\ + !*** ./node_modules/parse-asn1/index.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar asn1 = __webpack_require__(/*! ./asn1 */ \"./node_modules/parse-asn1/asn1.js\");\nvar aesid = __webpack_require__(/*! ./aesid.json */ \"./node_modules/parse-asn1/aesid.json\");\nvar fixProc = __webpack_require__(/*! ./fixProc */ \"./node_modules/parse-asn1/fixProc.js\");\nvar ciphers = __webpack_require__(/*! browserify-aes */ \"./node_modules/browserify-aes/browser.js\");\nvar compat = __webpack_require__(/*! pbkdf2 */ \"./node_modules/pbkdf2/browser.js\");\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\n\nfunction decrypt(data, password) {\n\tvar salt = data.algorithm.decrypt.kde.kdeparams.salt;\n\tvar iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10);\n\tvar algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')];\n\tvar iv = data.algorithm.decrypt.cipher.iv;\n\tvar cipherText = data.subjectPrivateKey;\n\tvar keylen = parseInt(algo.split('-')[1], 10) / 8;\n\tvar key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1');\n\tvar cipher = ciphers.createDecipheriv(algo, key, iv);\n\tvar out = [];\n\tout.push(cipher.update(cipherText));\n\tout.push(cipher['final']());\n\treturn Buffer.concat(out);\n}\n\nfunction parseKeys(buffer) {\n\tvar password;\n\tif (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {\n\t\tpassword = buffer.passphrase;\n\t\tbuffer = buffer.key;\n\t}\n\tif (typeof buffer === 'string') {\n\t\tbuffer = Buffer.from(buffer);\n\t}\n\n\tvar stripped = fixProc(buffer, password);\n\n\tvar type = stripped.tag;\n\tvar data = stripped.data;\n\tvar subtype, ndata;\n\tswitch (type) {\n\t\tcase 'CERTIFICATE':\n\t\t\tndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo;\n\t\t\t// falls through\n\t\tcase 'PUBLIC KEY':\n\t\t\tif (!ndata) {\n\t\t\t\tndata = asn1.PublicKey.decode(data, 'der');\n\t\t\t}\n\t\t\tsubtype = ndata.algorithm.algorithm.join('.');\n\t\t\tswitch (subtype) {\n\t\t\t\tcase '1.2.840.113549.1.1.1':\n\t\t\t\t\treturn asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der');\n\t\t\t\tcase '1.2.840.10045.2.1':\n\t\t\t\t\tndata.subjectPrivateKey = ndata.subjectPublicKey;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: 'ec',\n\t\t\t\t\t\tdata: ndata\n\t\t\t\t\t};\n\t\t\t\tcase '1.2.840.10040.4.1':\n\t\t\t\t\tndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der');\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: 'dsa',\n\t\t\t\t\t\tdata: ndata.algorithm.params\n\t\t\t\t\t};\n\t\t\t\tdefault: throw new Error('unknown key id ' + subtype);\n\t\t\t}\n\t\t\t// throw new Error('unknown key type ' + type)\n\t\tcase 'ENCRYPTED PRIVATE KEY':\n\t\t\tdata = asn1.EncryptedPrivateKey.decode(data, 'der');\n\t\t\tdata = decrypt(data, password);\n\t\t\t// falls through\n\t\tcase 'PRIVATE KEY':\n\t\t\tndata = asn1.PrivateKey.decode(data, 'der');\n\t\t\tsubtype = ndata.algorithm.algorithm.join('.');\n\t\t\tswitch (subtype) {\n\t\t\t\tcase '1.2.840.113549.1.1.1':\n\t\t\t\t\treturn asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der');\n\t\t\t\tcase '1.2.840.10045.2.1':\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcurve: ndata.algorithm.curve,\n\t\t\t\t\t\tprivateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey\n\t\t\t\t\t};\n\t\t\t\tcase '1.2.840.10040.4.1':\n\t\t\t\t\tndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der');\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: 'dsa',\n\t\t\t\t\t\tparams: ndata.algorithm.params\n\t\t\t\t\t};\n\t\t\t\tdefault: throw new Error('unknown key id ' + subtype);\n\t\t\t}\n\t\t\t// throw new Error('unknown key type ' + type)\n\t\tcase 'RSA PUBLIC KEY':\n\t\t\treturn asn1.RSAPublicKey.decode(data, 'der');\n\t\tcase 'RSA PRIVATE KEY':\n\t\t\treturn asn1.RSAPrivateKey.decode(data, 'der');\n\t\tcase 'DSA PRIVATE KEY':\n\t\t\treturn {\n\t\t\t\ttype: 'dsa',\n\t\t\t\tparams: asn1.DSAPrivateKey.decode(data, 'der')\n\t\t\t};\n\t\tcase 'EC PRIVATE KEY':\n\t\t\tdata = asn1.ECPrivateKey.decode(data, 'der');\n\t\t\treturn {\n\t\t\t\tcurve: data.parameters.value,\n\t\t\t\tprivateKey: data.privateKey\n\t\t\t};\n\t\tdefault: throw new Error('unknown key type ' + type);\n\t}\n}\nparseKeys.signature = asn1.signature;\n\nmodule.exports = parseKeys;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/parse-asn1/index.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/browser.js": +/*!****************************************!*\ + !*** ./node_modules/pbkdf2/browser.js ***! + \****************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("exports.pbkdf2 = __webpack_require__(/*! ./lib/async */ \"./node_modules/pbkdf2/lib/async.js\")\nexports.pbkdf2Sync = __webpack_require__(/*! ./lib/sync */ \"./node_modules/pbkdf2/lib/sync-browser.js\")\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/browser.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/lib/async.js": +/*!******************************************!*\ + !*** ./node_modules/pbkdf2/lib/async.js ***! + \******************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar checkParameters = __webpack_require__(/*! ./precondition */ \"./node_modules/pbkdf2/lib/precondition.js\")\nvar defaultEncoding = __webpack_require__(/*! ./default-encoding */ \"./node_modules/pbkdf2/lib/default-encoding.js\")\nvar sync = __webpack_require__(/*! ./sync */ \"./node_modules/pbkdf2/lib/sync-browser.js\")\nvar toBuffer = __webpack_require__(/*! ./to-buffer */ \"./node_modules/pbkdf2/lib/to-buffer.js\")\n\nvar ZERO_BUF\nvar subtle = __webpack_require__.g.crypto && __webpack_require__.g.crypto.subtle\nvar toBrowser = {\n sha: 'SHA-1',\n 'sha-1': 'SHA-1',\n sha1: 'SHA-1',\n sha256: 'SHA-256',\n 'sha-256': 'SHA-256',\n sha384: 'SHA-384',\n 'sha-384': 'SHA-384',\n 'sha-512': 'SHA-512',\n sha512: 'SHA-512'\n}\nvar checks = []\nfunction checkNative (algo) {\n if (__webpack_require__.g.process && !__webpack_require__.g.process.browser) {\n return Promise.resolve(false)\n }\n if (!subtle || !subtle.importKey || !subtle.deriveBits) {\n return Promise.resolve(false)\n }\n if (checks[algo] !== undefined) {\n return checks[algo]\n }\n ZERO_BUF = ZERO_BUF || Buffer.alloc(8)\n var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)\n .then(function () {\n return true\n }).catch(function () {\n return false\n })\n checks[algo] = prom\n return prom\n}\nvar nextTick\nfunction getNextTick () {\n if (nextTick) {\n return nextTick\n }\n if (__webpack_require__.g.process && __webpack_require__.g.process.nextTick) {\n nextTick = __webpack_require__.g.process.nextTick\n } else if (__webpack_require__.g.queueMicrotask) {\n nextTick = __webpack_require__.g.queueMicrotask\n } else if (__webpack_require__.g.setImmediate) {\n nextTick = __webpack_require__.g.setImmediate\n } else {\n nextTick = __webpack_require__.g.setTimeout\n }\n return nextTick\n}\nfunction browserPbkdf2 (password, salt, iterations, length, algo) {\n return subtle.importKey(\n 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']\n ).then(function (key) {\n return subtle.deriveBits({\n name: 'PBKDF2',\n salt: salt,\n iterations: iterations,\n hash: {\n name: algo\n }\n }, key, length << 3)\n }).then(function (res) {\n return Buffer.from(res)\n })\n}\n\nfunction resolvePromise (promise, callback) {\n promise.then(function (out) {\n getNextTick()(function () {\n callback(null, out)\n })\n }, function (e) {\n getNextTick()(function () {\n callback(e)\n })\n })\n}\nmodule.exports = function (password, salt, iterations, keylen, digest, callback) {\n if (typeof digest === 'function') {\n callback = digest\n digest = undefined\n }\n\n digest = digest || 'sha1'\n var algo = toBrowser[digest.toLowerCase()]\n\n if (!algo || typeof __webpack_require__.g.Promise !== 'function') {\n getNextTick()(function () {\n var out\n try {\n out = sync(password, salt, iterations, keylen, digest)\n } catch (e) {\n return callback(e)\n }\n callback(null, out)\n })\n return\n }\n\n checkParameters(iterations, keylen)\n password = toBuffer(password, defaultEncoding, 'Password')\n salt = toBuffer(salt, defaultEncoding, 'Salt')\n if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')\n\n resolvePromise(checkNative(algo).then(function (resp) {\n if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)\n\n return sync(password, salt, iterations, keylen, digest)\n }), callback)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/lib/async.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/lib/default-encoding.js": +/*!*****************************************************!*\ + !*** ./node_modules/pbkdf2/lib/default-encoding.js ***! + \*****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\nvar defaultEncoding\n/* istanbul ignore next */\nif (__webpack_require__.g.process && __webpack_require__.g.process.browser) {\n defaultEncoding = 'utf-8'\n} else if (__webpack_require__.g.process && __webpack_require__.g.process.version) {\n var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)\n\n defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'\n} else {\n defaultEncoding = 'utf-8'\n}\nmodule.exports = defaultEncoding\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/lib/default-encoding.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/lib/precondition.js": +/*!*************************************************!*\ + !*** ./node_modules/pbkdf2/lib/precondition.js ***! + \*************************************************/ +/***/ ((module) => { + +eval("var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs\n\nmodule.exports = function (iterations, keylen) {\n if (typeof iterations !== 'number') {\n throw new TypeError('Iterations not a number')\n }\n\n if (iterations < 0) {\n throw new TypeError('Bad iterations')\n }\n\n if (typeof keylen !== 'number') {\n throw new TypeError('Key length not a number')\n }\n\n if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */\n throw new TypeError('Bad key length')\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/lib/precondition.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/lib/sync-browser.js": +/*!*************************************************!*\ + !*** ./node_modules/pbkdf2/lib/sync-browser.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var md5 = __webpack_require__(/*! create-hash/md5 */ \"./node_modules/create-hash/md5.js\")\nvar RIPEMD160 = __webpack_require__(/*! ripemd160 */ \"./node_modules/ripemd160/index.js\")\nvar sha = __webpack_require__(/*! sha.js */ \"./node_modules/sha.js/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar checkParameters = __webpack_require__(/*! ./precondition */ \"./node_modules/pbkdf2/lib/precondition.js\")\nvar defaultEncoding = __webpack_require__(/*! ./default-encoding */ \"./node_modules/pbkdf2/lib/default-encoding.js\")\nvar toBuffer = __webpack_require__(/*! ./to-buffer */ \"./node_modules/pbkdf2/lib/to-buffer.js\")\n\nvar ZEROS = Buffer.alloc(128)\nvar sizes = {\n md5: 16,\n sha1: 20,\n sha224: 28,\n sha256: 32,\n sha384: 48,\n sha512: 64,\n rmd160: 20,\n ripemd160: 20\n}\n\nfunction Hmac (alg, key, saltLen) {\n var hash = getDigest(alg)\n var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64\n\n if (key.length > blocksize) {\n key = hash(key)\n } else if (key.length < blocksize) {\n key = Buffer.concat([key, ZEROS], blocksize)\n }\n\n var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])\n var opad = Buffer.allocUnsafe(blocksize + sizes[alg])\n for (var i = 0; i < blocksize; i++) {\n ipad[i] = key[i] ^ 0x36\n opad[i] = key[i] ^ 0x5C\n }\n\n var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)\n ipad.copy(ipad1, 0, 0, blocksize)\n this.ipad1 = ipad1\n this.ipad2 = ipad\n this.opad = opad\n this.alg = alg\n this.blocksize = blocksize\n this.hash = hash\n this.size = sizes[alg]\n}\n\nHmac.prototype.run = function (data, ipad) {\n data.copy(ipad, this.blocksize)\n var h = this.hash(ipad)\n h.copy(this.opad, this.blocksize)\n return this.hash(this.opad)\n}\n\nfunction getDigest (alg) {\n function shaFunc (data) {\n return sha(alg).update(data).digest()\n }\n function rmd160Func (data) {\n return new RIPEMD160().update(data).digest()\n }\n\n if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func\n if (alg === 'md5') return md5\n return shaFunc\n}\n\nfunction pbkdf2 (password, salt, iterations, keylen, digest) {\n checkParameters(iterations, keylen)\n password = toBuffer(password, defaultEncoding, 'Password')\n salt = toBuffer(salt, defaultEncoding, 'Salt')\n\n digest = digest || 'sha1'\n\n var hmac = new Hmac(digest, password, salt.length)\n\n var DK = Buffer.allocUnsafe(keylen)\n var block1 = Buffer.allocUnsafe(salt.length + 4)\n salt.copy(block1, 0, 0, salt.length)\n\n var destPos = 0\n var hLen = sizes[digest]\n var l = Math.ceil(keylen / hLen)\n\n for (var i = 1; i <= l; i++) {\n block1.writeUInt32BE(i, salt.length)\n\n var T = hmac.run(block1, hmac.ipad1)\n var U = T\n\n for (var j = 1; j < iterations; j++) {\n U = hmac.run(U, hmac.ipad2)\n for (var k = 0; k < hLen; k++) T[k] ^= U[k]\n }\n\n T.copy(DK, destPos)\n destPos += hLen\n }\n\n return DK\n}\n\nmodule.exports = pbkdf2\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/lib/sync-browser.js?"); + +/***/ }), + +/***/ "./node_modules/pbkdf2/lib/to-buffer.js": +/*!**********************************************!*\ + !*** ./node_modules/pbkdf2/lib/to-buffer.js ***! + \**********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nmodule.exports = function (thing, encoding, name) {\n if (Buffer.isBuffer(thing)) {\n return thing\n } else if (typeof thing === 'string') {\n return Buffer.from(thing, encoding)\n } else if (ArrayBuffer.isView(thing)) {\n return Buffer.from(thing.buffer)\n } else {\n throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pbkdf2/lib/to-buffer.js?"); + +/***/ }), + +/***/ "./node_modules/process-nextick-args/index.js": +/*!****************************************************!*\ + !*** ./node_modules/process-nextick-args/index.js ***! + \****************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/process-nextick-args/index.js?"); + +/***/ }), + +/***/ "./node_modules/process/browser.js": +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/***/ ((module) => { + +eval("// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/process/browser.js?"); /***/ }), @@ -1925,7 +3344,7 @@ eval("\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionOb /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -eval("\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = __webpack_require__(/*! ./tokenize */ \"./node_modules/protobufjs/src/tokenize.js\"),\n Root = __webpack_require__(/*! ./root */ \"./node_modules/protobufjs/src/root.js\"),\n Type = __webpack_require__(/*! ./type */ \"./node_modules/protobufjs/src/type.js\"),\n Field = __webpack_require__(/*! ./field */ \"./node_modules/protobufjs/src/field.js\"),\n MapField = __webpack_require__(/*! ./mapfield */ \"./node_modules/protobufjs/src/mapfield.js\"),\n OneOf = __webpack_require__(/*! ./oneof */ \"./node_modules/protobufjs/src/oneof.js\"),\n Enum = __webpack_require__(/*! ./enum */ \"./node_modules/protobufjs/src/enum.js\"),\n Service = __webpack_require__(/*! ./service */ \"./node_modules/protobufjs/src/service.js\"),\n Method = __webpack_require__(/*! ./method */ \"./node_modules/protobufjs/src/method.js\"),\n types = __webpack_require__(/*! ./types */ \"./node_modules/protobufjs/src/types.js\"),\n util = __webpack_require__(/*! ./util */ \"./node_modules/protobufjs/src/util.js\");\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n skip(\";\");\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/protobufjs/src/parse.js?"); +eval("\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = __webpack_require__(/*! ./tokenize */ \"./node_modules/protobufjs/src/tokenize.js\"),\n Root = __webpack_require__(/*! ./root */ \"./node_modules/protobufjs/src/root.js\"),\n Type = __webpack_require__(/*! ./type */ \"./node_modules/protobufjs/src/type.js\"),\n Field = __webpack_require__(/*! ./field */ \"./node_modules/protobufjs/src/field.js\"),\n MapField = __webpack_require__(/*! ./mapfield */ \"./node_modules/protobufjs/src/mapfield.js\"),\n OneOf = __webpack_require__(/*! ./oneof */ \"./node_modules/protobufjs/src/oneof.js\"),\n Enum = __webpack_require__(/*! ./enum */ \"./node_modules/protobufjs/src/enum.js\"),\n Service = __webpack_require__(/*! ./service */ \"./node_modules/protobufjs/src/service.js\"),\n Method = __webpack_require__(/*! ./method */ \"./node_modules/protobufjs/src/method.js\"),\n types = __webpack_require__(/*! ./types */ \"./node_modules/protobufjs/src/types.js\"),\n util = __webpack_require__(/*! ./util */ \"./node_modules/protobufjs/src/util.js\");\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n // Syntax is needed to understand the meaning of the optional field rule\n // Otherwise the meaning is ambiguous between proto2 and proto3\n root.setOption(\"syntax\", syntax);\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/protobufjs/src/parse.js?"); /***/ }), @@ -2024,7 +3443,7 @@ eval("\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()< /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; -eval("\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = __webpack_require__(/*! ./namespace */ \"./node_modules/protobufjs/src/namespace.js\");\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = __webpack_require__(/*! ./enum */ \"./node_modules/protobufjs/src/enum.js\"),\n OneOf = __webpack_require__(/*! ./oneof */ \"./node_modules/protobufjs/src/oneof.js\"),\n Field = __webpack_require__(/*! ./field */ \"./node_modules/protobufjs/src/field.js\"),\n MapField = __webpack_require__(/*! ./mapfield */ \"./node_modules/protobufjs/src/mapfield.js\"),\n Service = __webpack_require__(/*! ./service */ \"./node_modules/protobufjs/src/service.js\"),\n Message = __webpack_require__(/*! ./message */ \"./node_modules/protobufjs/src/message.js\"),\n Reader = __webpack_require__(/*! ./reader */ \"./node_modules/protobufjs/src/reader.js\"),\n Writer = __webpack_require__(/*! ./writer */ \"./node_modules/protobufjs/src/writer.js\"),\n util = __webpack_require__(/*! ./util */ \"./node_modules/protobufjs/src/util.js\"),\n encoder = __webpack_require__(/*! ./encoder */ \"./node_modules/protobufjs/src/encoder.js\"),\n decoder = __webpack_require__(/*! ./decoder */ \"./node_modules/protobufjs/src/decoder.js\"),\n verifier = __webpack_require__(/*! ./verifier */ \"./node_modules/protobufjs/src/verifier.js\"),\n converter = __webpack_require__(/*! ./converter */ \"./node_modules/protobufjs/src/converter.js\"),\n wrappers = __webpack_require__(/*! ./wrappers */ \"./node_modules/protobufjs/src/wrappers.js\");\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {number[][]} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/protobufjs/src/type.js?"); +eval("\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = __webpack_require__(/*! ./namespace */ \"./node_modules/protobufjs/src/namespace.js\");\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = __webpack_require__(/*! ./enum */ \"./node_modules/protobufjs/src/enum.js\"),\n OneOf = __webpack_require__(/*! ./oneof */ \"./node_modules/protobufjs/src/oneof.js\"),\n Field = __webpack_require__(/*! ./field */ \"./node_modules/protobufjs/src/field.js\"),\n MapField = __webpack_require__(/*! ./mapfield */ \"./node_modules/protobufjs/src/mapfield.js\"),\n Service = __webpack_require__(/*! ./service */ \"./node_modules/protobufjs/src/service.js\"),\n Message = __webpack_require__(/*! ./message */ \"./node_modules/protobufjs/src/message.js\"),\n Reader = __webpack_require__(/*! ./reader */ \"./node_modules/protobufjs/src/reader.js\"),\n Writer = __webpack_require__(/*! ./writer */ \"./node_modules/protobufjs/src/writer.js\"),\n util = __webpack_require__(/*! ./util */ \"./node_modules/protobufjs/src/util.js\"),\n encoder = __webpack_require__(/*! ./encoder */ \"./node_modules/protobufjs/src/encoder.js\"),\n decoder = __webpack_require__(/*! ./decoder */ \"./node_modules/protobufjs/src/decoder.js\"),\n verifier = __webpack_require__(/*! ./verifier */ \"./node_modules/protobufjs/src/verifier.js\"),\n converter = __webpack_require__(/*! ./converter */ \"./node_modules/protobufjs/src/converter.js\"),\n wrappers = __webpack_require__(/*! ./wrappers */ \"./node_modules/protobufjs/src/wrappers.js\");\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {Array.} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/protobufjs/src/type.js?"); /***/ }), @@ -2116,14 +3535,84 @@ eval("\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = __webp /***/ }), +/***/ "./node_modules/public-encrypt/browser.js": +/*!************************************************!*\ + !*** ./node_modules/public-encrypt/browser.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +eval("exports.publicEncrypt = __webpack_require__(/*! ./publicEncrypt */ \"./node_modules/public-encrypt/publicEncrypt.js\")\nexports.privateDecrypt = __webpack_require__(/*! ./privateDecrypt */ \"./node_modules/public-encrypt/privateDecrypt.js\")\n\nexports.privateEncrypt = function privateEncrypt (key, buf) {\n return exports.publicEncrypt(key, buf, true)\n}\n\nexports.publicDecrypt = function publicDecrypt (key, buf) {\n return exports.privateDecrypt(key, buf, true)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/browser.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/mgf.js": +/*!********************************************!*\ + !*** ./node_modules/public-encrypt/mgf.js ***! + \********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var createHash = __webpack_require__(/*! create-hash */ \"./node_modules/create-hash/browser.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nmodule.exports = function (seed, len) {\n var t = Buffer.alloc(0)\n var i = 0\n var c\n while (t.length < len) {\n c = i2ops(i++)\n t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])\n }\n return t.slice(0, len)\n}\n\nfunction i2ops (c) {\n var out = Buffer.allocUnsafe(4)\n out.writeUInt32BE(c, 0)\n return out\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/mgf.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js": +/*!******************************************************************!*\ + !*** ./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js ***! + \******************************************************************/ +/***/ (function(module, __unused_webpack_exports, __webpack_require__) { + +eval("/* module decorator */ module = __webpack_require__.nmd(module);\n(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {\n Buffer = window.Buffer;\n } else {\n Buffer = (__webpack_require__(/*! buffer */ \"?fbf1\").Buffer);\n }\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n this.negative = 1;\n }\n\n if (start < number.length) {\n if (base === 16) {\n this._parseHex(number, start, endian);\n } else {\n this._parseBase(number, base, start);\n if (endian === 'le') {\n this._initArray(this.toArray(), base, endian);\n }\n }\n }\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex4Bits (string, index) {\n var c = string.charCodeAt(index);\n // 'A' - 'F'\n if (c >= 65 && c <= 70) {\n return c - 55;\n // 'a' - 'f'\n } else if (c >= 97 && c <= 102) {\n return c - 87;\n // '0' - '9'\n } else {\n return (c - 48) & 0xf;\n }\n }\n\n function parseHexByte (string, lowerBound, index) {\n var r = parseHex4Bits(string, index);\n if (index - 1 >= lowerBound) {\n r |= parseHex4Bits(string, index - 1) << 4;\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start, endian) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n // 24-bits chunks\n var off = 0;\n var j = 0;\n\n var w;\n if (endian === 'be') {\n for (i = number.length - 1; i >= start; i -= 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n } else {\n var parseLength = number.length - start;\n for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {\n w = parseHexByte(number, start, i) << off;\n this.words[j] |= w & 0x3ffffff;\n if (off >= 18) {\n off -= 18;\n j += 1;\n this.words[j] |= w >>> 26;\n } else {\n off += 8;\n }\n }\n }\n\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n this.strip();\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})( false || module, this);\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/privateDecrypt.js": +/*!*******************************************************!*\ + !*** ./node_modules/public-encrypt/privateDecrypt.js ***! + \*******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var parseKeys = __webpack_require__(/*! parse-asn1 */ \"./node_modules/parse-asn1/index.js\")\nvar mgf = __webpack_require__(/*! ./mgf */ \"./node_modules/public-encrypt/mgf.js\")\nvar xor = __webpack_require__(/*! ./xor */ \"./node_modules/public-encrypt/xor.js\")\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js\")\nvar crt = __webpack_require__(/*! browserify-rsa */ \"./node_modules/browserify-rsa/index.js\")\nvar createHash = __webpack_require__(/*! create-hash */ \"./node_modules/create-hash/browser.js\")\nvar withPublic = __webpack_require__(/*! ./withPublic */ \"./node_modules/public-encrypt/withPublic.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nmodule.exports = function privateDecrypt (privateKey, enc, reverse) {\n var padding\n if (privateKey.padding) {\n padding = privateKey.padding\n } else if (reverse) {\n padding = 1\n } else {\n padding = 4\n }\n\n var key = parseKeys(privateKey)\n var k = key.modulus.byteLength()\n if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {\n throw new Error('decryption error')\n }\n var msg\n if (reverse) {\n msg = withPublic(new BN(enc), key)\n } else {\n msg = crt(enc, key)\n }\n var zBuffer = Buffer.alloc(k - msg.length)\n msg = Buffer.concat([zBuffer, msg], k)\n if (padding === 4) {\n return oaep(key, msg)\n } else if (padding === 1) {\n return pkcs1(key, msg, reverse)\n } else if (padding === 3) {\n return msg\n } else {\n throw new Error('unknown padding')\n }\n}\n\nfunction oaep (key, msg) {\n var k = key.modulus.byteLength()\n var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()\n var hLen = iHash.length\n if (msg[0] !== 0) {\n throw new Error('decryption error')\n }\n var maskedSeed = msg.slice(1, hLen + 1)\n var maskedDb = msg.slice(hLen + 1)\n var seed = xor(maskedSeed, mgf(maskedDb, hLen))\n var db = xor(maskedDb, mgf(seed, k - hLen - 1))\n if (compare(iHash, db.slice(0, hLen))) {\n throw new Error('decryption error')\n }\n var i = hLen\n while (db[i] === 0) {\n i++\n }\n if (db[i++] !== 1) {\n throw new Error('decryption error')\n }\n return db.slice(i)\n}\n\nfunction pkcs1 (key, msg, reverse) {\n var p1 = msg.slice(0, 2)\n var i = 2\n var status = 0\n while (msg[i++] !== 0) {\n if (i >= msg.length) {\n status++\n break\n }\n }\n var ps = msg.slice(2, i - 1)\n\n if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {\n status++\n }\n if (ps.length < 8) {\n status++\n }\n if (status) {\n throw new Error('decryption error')\n }\n return msg.slice(i)\n}\nfunction compare (a, b) {\n a = Buffer.from(a)\n b = Buffer.from(b)\n var dif = 0\n var len = a.length\n if (a.length !== b.length) {\n dif++\n len = Math.min(a.length, b.length)\n }\n var i = -1\n while (++i < len) {\n dif += (a[i] ^ b[i])\n }\n return dif\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/privateDecrypt.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/publicEncrypt.js": +/*!******************************************************!*\ + !*** ./node_modules/public-encrypt/publicEncrypt.js ***! + \******************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var parseKeys = __webpack_require__(/*! parse-asn1 */ \"./node_modules/parse-asn1/index.js\")\nvar randomBytes = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\")\nvar createHash = __webpack_require__(/*! create-hash */ \"./node_modules/create-hash/browser.js\")\nvar mgf = __webpack_require__(/*! ./mgf */ \"./node_modules/public-encrypt/mgf.js\")\nvar xor = __webpack_require__(/*! ./xor */ \"./node_modules/public-encrypt/xor.js\")\nvar BN = __webpack_require__(/*! bn.js */ \"./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js\")\nvar withPublic = __webpack_require__(/*! ./withPublic */ \"./node_modules/public-encrypt/withPublic.js\")\nvar crt = __webpack_require__(/*! browserify-rsa */ \"./node_modules/browserify-rsa/index.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nmodule.exports = function publicEncrypt (publicKey, msg, reverse) {\n var padding\n if (publicKey.padding) {\n padding = publicKey.padding\n } else if (reverse) {\n padding = 1\n } else {\n padding = 4\n }\n var key = parseKeys(publicKey)\n var paddedMsg\n if (padding === 4) {\n paddedMsg = oaep(key, msg)\n } else if (padding === 1) {\n paddedMsg = pkcs1(key, msg, reverse)\n } else if (padding === 3) {\n paddedMsg = new BN(msg)\n if (paddedMsg.cmp(key.modulus) >= 0) {\n throw new Error('data too long for modulus')\n }\n } else {\n throw new Error('unknown padding')\n }\n if (reverse) {\n return crt(paddedMsg, key)\n } else {\n return withPublic(paddedMsg, key)\n }\n}\n\nfunction oaep (key, msg) {\n var k = key.modulus.byteLength()\n var mLen = msg.length\n var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()\n var hLen = iHash.length\n var hLen2 = 2 * hLen\n if (mLen > k - hLen2 - 2) {\n throw new Error('message too long')\n }\n var ps = Buffer.alloc(k - mLen - hLen2 - 2)\n var dblen = k - hLen - 1\n var seed = randomBytes(hLen)\n var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))\n var maskedSeed = xor(seed, mgf(maskedDb, hLen))\n return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))\n}\nfunction pkcs1 (key, msg, reverse) {\n var mLen = msg.length\n var k = key.modulus.byteLength()\n if (mLen > k - 11) {\n throw new Error('message too long')\n }\n var ps\n if (reverse) {\n ps = Buffer.alloc(k - mLen - 3, 0xff)\n } else {\n ps = nonZero(k - mLen - 3)\n }\n return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))\n}\nfunction nonZero (len) {\n var out = Buffer.allocUnsafe(len)\n var i = 0\n var cache = randomBytes(len * 2)\n var cur = 0\n var num\n while (i < len) {\n if (cur === cache.length) {\n cache = randomBytes(len * 2)\n cur = 0\n }\n num = cache[cur++]\n if (num) {\n out[i++] = num\n }\n }\n return out\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/publicEncrypt.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/withPublic.js": +/*!***************************************************!*\ + !*** ./node_modules/public-encrypt/withPublic.js ***! + \***************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var BN = __webpack_require__(/*! bn.js */ \"./node_modules/public-encrypt/node_modules/bn.js/lib/bn.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nfunction withPublic (paddedMsg, key) {\n return Buffer.from(paddedMsg\n .toRed(BN.mont(key.modulus))\n .redPow(new BN(key.publicExponent))\n .fromRed()\n .toArray())\n}\n\nmodule.exports = withPublic\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/withPublic.js?"); + +/***/ }), + +/***/ "./node_modules/public-encrypt/xor.js": +/*!********************************************!*\ + !*** ./node_modules/public-encrypt/xor.js ***! + \********************************************/ +/***/ ((module) => { + +eval("module.exports = function xor (a, b) {\n var len = a.length\n var i = -1\n while (++i < len) {\n a[i] ^= b[i]\n }\n return a\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/public-encrypt/xor.js?"); + +/***/ }), + /***/ "./node_modules/pvtsutils/build/index.js": /*!***********************************************!*\ !*** ./node_modules/pvtsutils/build/index.js ***! \***********************************************/ -/***/ ((__unused_webpack_module, exports) => { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -eval("/*!\n * MIT License\n * \n * Copyright (c) 2017-2022 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pvtsutils/build/index.js?"); +eval("/* provided dependency */ var Buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")[\"Buffer\"];\n/*!\n * MIT License\n * \n * Copyright (c) 2017-2024 Peculiar Ventures, LLC\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * \n */\n\n\n\nconst ARRAY_BUFFER_NAME = \"[object ArrayBuffer]\";\nclass BufferSourceConverter {\n static isArrayBuffer(data) {\n return Object.prototype.toString.call(data) === ARRAY_BUFFER_NAME;\n }\n static toArrayBuffer(data) {\n if (this.isArrayBuffer(data)) {\n return data;\n }\n if (data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {\n return data.buffer;\n }\n return this.toUint8Array(data.buffer)\n .slice(data.byteOffset, data.byteOffset + data.byteLength)\n .buffer;\n }\n static toUint8Array(data) {\n return this.toView(data, Uint8Array);\n }\n static toView(data, type) {\n if (data.constructor === type) {\n return data;\n }\n if (this.isArrayBuffer(data)) {\n return new type(data);\n }\n if (this.isArrayBufferView(data)) {\n return new type(data.buffer, data.byteOffset, data.byteLength);\n }\n throw new TypeError(\"The provided value is not of type '(ArrayBuffer or ArrayBufferView)'\");\n }\n static isBufferSource(data) {\n return this.isArrayBufferView(data)\n || this.isArrayBuffer(data);\n }\n static isArrayBufferView(data) {\n return ArrayBuffer.isView(data)\n || (data && this.isArrayBuffer(data.buffer));\n }\n static isEqual(a, b) {\n const aView = BufferSourceConverter.toUint8Array(a);\n const bView = BufferSourceConverter.toUint8Array(b);\n if (aView.length !== bView.byteLength) {\n return false;\n }\n for (let i = 0; i < aView.length; i++) {\n if (aView[i] !== bView[i]) {\n return false;\n }\n }\n return true;\n }\n static concat(...args) {\n let buffers;\n if (Array.isArray(args[0]) && !(args[1] instanceof Function)) {\n buffers = args[0];\n }\n else if (Array.isArray(args[0]) && args[1] instanceof Function) {\n buffers = args[0];\n }\n else {\n if (args[args.length - 1] instanceof Function) {\n buffers = args.slice(0, args.length - 1);\n }\n else {\n buffers = args;\n }\n }\n let size = 0;\n for (const buffer of buffers) {\n size += buffer.byteLength;\n }\n const res = new Uint8Array(size);\n let offset = 0;\n for (const buffer of buffers) {\n const view = this.toUint8Array(buffer);\n res.set(view, offset);\n offset += view.length;\n }\n if (args[args.length - 1] instanceof Function) {\n return this.toView(res, args[args.length - 1]);\n }\n return res.buffer;\n }\n}\n\nconst STRING_TYPE = \"string\";\nconst HEX_REGEX = /^[0-9a-f\\s]+$/i;\nconst BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\nconst BASE64URL_REGEX = /^[a-zA-Z0-9-_]+$/;\nclass Utf8Converter {\n static fromString(text) {\n const s = unescape(encodeURIComponent(text));\n const uintArray = new Uint8Array(s.length);\n for (let i = 0; i < s.length; i++) {\n uintArray[i] = s.charCodeAt(i);\n }\n return uintArray.buffer;\n }\n static toString(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let encodedString = \"\";\n for (let i = 0; i < buf.length; i++) {\n encodedString += String.fromCharCode(buf[i]);\n }\n const decodedString = decodeURIComponent(escape(encodedString));\n return decodedString;\n }\n}\nclass Utf16Converter {\n static toString(buffer, littleEndian = false) {\n const arrayBuffer = BufferSourceConverter.toArrayBuffer(buffer);\n const dataView = new DataView(arrayBuffer);\n let res = \"\";\n for (let i = 0; i < arrayBuffer.byteLength; i += 2) {\n const code = dataView.getUint16(i, littleEndian);\n res += String.fromCharCode(code);\n }\n return res;\n }\n static fromString(text, littleEndian = false) {\n const res = new ArrayBuffer(text.length * 2);\n const dataView = new DataView(res);\n for (let i = 0; i < text.length; i++) {\n dataView.setUint16(i * 2, text.charCodeAt(i), littleEndian);\n }\n return res;\n }\n}\nclass Convert {\n static isHex(data) {\n return typeof data === STRING_TYPE\n && HEX_REGEX.test(data);\n }\n static isBase64(data) {\n return typeof data === STRING_TYPE\n && BASE64_REGEX.test(data);\n }\n static isBase64Url(data) {\n return typeof data === STRING_TYPE\n && BASE64URL_REGEX.test(data);\n }\n static ToString(buffer, enc = \"utf8\") {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.ToUtf8String(buf);\n case \"binary\":\n return this.ToBinary(buf);\n case \"hex\":\n return this.ToHex(buf);\n case \"base64\":\n return this.ToBase64(buf);\n case \"base64url\":\n return this.ToBase64Url(buf);\n case \"utf16le\":\n return Utf16Converter.toString(buf, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buf);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static FromString(str, enc = \"utf8\") {\n if (!str) {\n return new ArrayBuffer(0);\n }\n switch (enc.toLowerCase()) {\n case \"utf8\":\n return this.FromUtf8String(str);\n case \"binary\":\n return this.FromBinary(str);\n case \"hex\":\n return this.FromHex(str);\n case \"base64\":\n return this.FromBase64(str);\n case \"base64url\":\n return this.FromBase64Url(str);\n case \"utf16le\":\n return Utf16Converter.fromString(str, true);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(str);\n default:\n throw new Error(`Unknown type of encoding '${enc}'`);\n }\n }\n static ToBase64(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n if (typeof btoa !== \"undefined\") {\n const binary = this.ToString(buf, \"binary\");\n return btoa(binary);\n }\n else {\n return Buffer.from(buf).toString(\"base64\");\n }\n }\n static FromBase64(base64) {\n const formatted = this.formatString(base64);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64(formatted)) {\n throw new TypeError(\"Argument 'base64Text' is not Base64 encoded\");\n }\n if (typeof atob !== \"undefined\") {\n return this.FromBinary(atob(formatted));\n }\n else {\n return new Uint8Array(Buffer.from(formatted, \"base64\")).buffer;\n }\n }\n static FromBase64Url(base64url) {\n const formatted = this.formatString(base64url);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isBase64Url(formatted)) {\n throw new TypeError(\"Argument 'base64url' is not Base64Url encoded\");\n }\n return this.FromBase64(this.Base64Padding(formatted.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\")));\n }\n static ToBase64Url(data) {\n return this.ToBase64(data).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/\\=/g, \"\");\n }\n static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.FromBinary(text);\n case \"utf8\":\n return Utf8Converter.fromString(text);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.fromString(text);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.fromString(text, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {\n switch (encoding) {\n case \"ascii\":\n return this.ToBinary(buffer);\n case \"utf8\":\n return Utf8Converter.toString(buffer);\n case \"utf16\":\n case \"utf16be\":\n return Utf16Converter.toString(buffer);\n case \"utf16le\":\n case \"usc2\":\n return Utf16Converter.toString(buffer, true);\n default:\n throw new Error(`Unknown type of encoding '${encoding}'`);\n }\n }\n static FromBinary(text) {\n const stringLength = text.length;\n const resultView = new Uint8Array(stringLength);\n for (let i = 0; i < stringLength; i++) {\n resultView[i] = text.charCodeAt(i);\n }\n return resultView.buffer;\n }\n static ToBinary(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let res = \"\";\n for (let i = 0; i < buf.length; i++) {\n res += String.fromCharCode(buf[i]);\n }\n return res;\n }\n static ToHex(buffer) {\n const buf = BufferSourceConverter.toUint8Array(buffer);\n let result = \"\";\n const len = buf.length;\n for (let i = 0; i < len; i++) {\n const byte = buf[i];\n if (byte < 16) {\n result += \"0\";\n }\n result += byte.toString(16);\n }\n return result;\n }\n static FromHex(hexString) {\n let formatted = this.formatString(hexString);\n if (!formatted) {\n return new ArrayBuffer(0);\n }\n if (!Convert.isHex(formatted)) {\n throw new TypeError(\"Argument 'hexString' is not HEX encoded\");\n }\n if (formatted.length % 2) {\n formatted = `0${formatted}`;\n }\n const res = new Uint8Array(formatted.length / 2);\n for (let i = 0; i < formatted.length; i = i + 2) {\n const c = formatted.slice(i, i + 2);\n res[i / 2] = parseInt(c, 16);\n }\n return res.buffer;\n }\n static ToUtf16String(buffer, littleEndian = false) {\n return Utf16Converter.toString(buffer, littleEndian);\n }\n static FromUtf16String(text, littleEndian = false) {\n return Utf16Converter.fromString(text, littleEndian);\n }\n static Base64Padding(base64) {\n const padCount = 4 - (base64.length % 4);\n if (padCount < 4) {\n for (let i = 0; i < padCount; i++) {\n base64 += \"=\";\n }\n }\n return base64;\n }\n static formatString(data) {\n return (data === null || data === void 0 ? void 0 : data.replace(/[\\n\\r\\t ]/g, \"\")) || \"\";\n }\n}\nConvert.DEFAULT_UTF8_ENCODING = \"utf8\";\n\nfunction assign(target, ...sources) {\n const res = arguments[0];\n for (let i = 1; i < arguments.length; i++) {\n const obj = arguments[i];\n for (const prop in obj) {\n res[prop] = obj[prop];\n }\n }\n return res;\n}\nfunction combine(...buf) {\n const totalByteLength = buf.map((item) => item.byteLength).reduce((prev, cur) => prev + cur);\n const res = new Uint8Array(totalByteLength);\n let currentPos = 0;\n buf.map((item) => new Uint8Array(item)).forEach((arr) => {\n for (const item2 of arr) {\n res[currentPos++] = item2;\n }\n });\n return res.buffer;\n}\nfunction isEqual(bytes1, bytes2) {\n if (!(bytes1 && bytes2)) {\n return false;\n }\n if (bytes1.byteLength !== bytes2.byteLength) {\n return false;\n }\n const b1 = new Uint8Array(bytes1);\n const b2 = new Uint8Array(bytes2);\n for (let i = 0; i < bytes1.byteLength; i++) {\n if (b1[i] !== b2[i]) {\n return false;\n }\n }\n return true;\n}\n\nexports.BufferSourceConverter = BufferSourceConverter;\nexports.Convert = Convert;\nexports.assign = assign;\nexports.combine = combine;\nexports.isEqual = isEqual;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/pvtsutils/build/index.js?"); /***/ }), @@ -2138,6 +3627,367 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/randombytes/browser.js": +/*!*********************************************!*\ + !*** ./node_modules/randombytes/browser.js ***! + \*********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\n\n// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nvar MAX_BYTES = 65536\n\n// Node supports requesting up to this number of bytes\n// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48\nvar MAX_UINT32 = 4294967295\n\nfunction oldBrowser () {\n throw new Error('Secure random number generation is not supported by this browser.\\nUse Chrome, Firefox or Internet Explorer 11')\n}\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\nvar crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto\n\nif (crypto && crypto.getRandomValues) {\n module.exports = randomBytes\n} else {\n module.exports = oldBrowser\n}\n\nfunction randomBytes (size, cb) {\n // phantomjs needs to throw\n if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')\n\n var bytes = Buffer.allocUnsafe(size)\n\n if (size > 0) { // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues\n // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues\n for (var generated = 0; generated < size; generated += MAX_BYTES) {\n // buffer.slice automatically checks if the end is past the end of\n // the buffer so we don't have to here\n crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n\n if (typeof cb === 'function') {\n return process.nextTick(function () {\n cb(null, bytes)\n })\n }\n\n return bytes\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/randombytes/browser.js?"); + +/***/ }), + +/***/ "./node_modules/randomfill/browser.js": +/*!********************************************!*\ + !*** ./node_modules/randomfill/browser.js ***! + \********************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\n\nfunction oldBrowser () {\n throw new Error('secure random number generation not supported by this browser\\nuse chrome, FireFox or Internet Explorer 11')\n}\nvar safeBuffer = __webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\")\nvar randombytes = __webpack_require__(/*! randombytes */ \"./node_modules/randombytes/browser.js\")\nvar Buffer = safeBuffer.Buffer\nvar kBufferMaxLength = safeBuffer.kMaxLength\nvar crypto = __webpack_require__.g.crypto || __webpack_require__.g.msCrypto\nvar kMaxUint32 = Math.pow(2, 32) - 1\nfunction assertOffset (offset, length) {\n if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare\n throw new TypeError('offset must be a number')\n }\n\n if (offset > kMaxUint32 || offset < 0) {\n throw new TypeError('offset must be a uint32')\n }\n\n if (offset > kBufferMaxLength || offset > length) {\n throw new RangeError('offset out of range')\n }\n}\n\nfunction assertSize (size, offset, length) {\n if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare\n throw new TypeError('size must be a number')\n }\n\n if (size > kMaxUint32 || size < 0) {\n throw new TypeError('size must be a uint32')\n }\n\n if (size + offset > length || size > kBufferMaxLength) {\n throw new RangeError('buffer too small')\n }\n}\nif ((crypto && crypto.getRandomValues) || !process.browser) {\n exports.randomFill = randomFill\n exports.randomFillSync = randomFillSync\n} else {\n exports.randomFill = oldBrowser\n exports.randomFillSync = oldBrowser\n}\nfunction randomFill (buf, offset, size, cb) {\n if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) {\n throw new TypeError('\"buf\" argument must be a Buffer or Uint8Array')\n }\n\n if (typeof offset === 'function') {\n cb = offset\n offset = 0\n size = buf.length\n } else if (typeof size === 'function') {\n cb = size\n size = buf.length - offset\n } else if (typeof cb !== 'function') {\n throw new TypeError('\"cb\" argument must be a function')\n }\n assertOffset(offset, buf.length)\n assertSize(size, offset, buf.length)\n return actualFill(buf, offset, size, cb)\n}\n\nfunction actualFill (buf, offset, size, cb) {\n if (process.browser) {\n var ourBuf = buf.buffer\n var uint = new Uint8Array(ourBuf, offset, size)\n crypto.getRandomValues(uint)\n if (cb) {\n process.nextTick(function () {\n cb(null, buf)\n })\n return\n }\n return buf\n }\n if (cb) {\n randombytes(size, function (err, bytes) {\n if (err) {\n return cb(err)\n }\n bytes.copy(buf, offset)\n cb(null, buf)\n })\n return\n }\n var bytes = randombytes(size)\n bytes.copy(buf, offset)\n return buf\n}\nfunction randomFillSync (buf, offset, size) {\n if (typeof offset === 'undefined') {\n offset = 0\n }\n if (!Buffer.isBuffer(buf) && !(buf instanceof __webpack_require__.g.Uint8Array)) {\n throw new TypeError('\"buf\" argument must be a Buffer or Uint8Array')\n }\n\n assertOffset(offset, buf.length)\n\n if (size === undefined) size = buf.length - offset\n\n assertSize(size, offset, buf.length)\n\n return actualFill(buf, offset, size)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/randomfill/browser.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/errors-browser.js": +/*!********************************************************!*\ + !*** ./node_modules/readable-stream/errors-browser.js ***! + \********************************************************/ +/***/ ((module) => { + +"use strict"; +eval("\n\nfunction _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }\n\nvar codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inheritsLoose(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;\n }\n\n return NodeError;\n }(Base);\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"';\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n }\n\n msg += \". Received type \".concat(typeof actual);\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented';\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\nmodule.exports.codes = codes;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/errors-browser.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_duplex.js": +/*!************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_duplex.js ***! + \************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) keys.push(key);\n return keys;\n};\n/**/\n\nmodule.exports = Duplex;\nvar Readable = __webpack_require__(/*! ./_stream_readable */ \"./node_modules/readable-stream/lib/_stream_readable.js\");\nvar Writable = __webpack_require__(/*! ./_stream_writable */ \"./node_modules/readable-stream/lib/_stream_writable.js\");\n__webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")(Duplex, Readable);\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n process.nextTick(onEndNT, this);\n}\nfunction onEndNT(self) {\n self.end();\n}\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/_stream_duplex.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_passthrough.js": +/*!*****************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_passthrough.js ***! + \*****************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n\n\nmodule.exports = PassThrough;\nvar Transform = __webpack_require__(/*! ./_stream_transform */ \"./node_modules/readable-stream/lib/_stream_transform.js\");\n__webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")(PassThrough, Transform);\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n Transform.call(this, options);\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/_stream_passthrough.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_readable.js": +/*!**************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_readable.js ***! + \**************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\nmodule.exports = Readable;\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/**/\n\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer);\nvar OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\nvar debugUtil = __webpack_require__(/*! util */ \"?d17e\");\nvar debug;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\nvar BufferList = __webpack_require__(/*! ./internal/streams/buffer_list */ \"./node_modules/readable-stream/lib/internal/streams/buffer_list.js\");\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar _require = __webpack_require__(/*! ./internal/streams/state */ \"./node_modules/readable-stream/lib/internal/streams/state.js\"),\n getHighWaterMark = _require.getHighWaterMark;\nvar _require$codes = (__webpack_require__(/*! ../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes),\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;\n\n// Lazy loaded to improve the startup performance.\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n__webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")(Readable, Stream);\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true;\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = options.emitClose !== false;\n\n // Should .destroy() be called after 'end' (and potentially 'finish')\n this.autoDestroy = !!options.autoDestroy;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = (__webpack_require__(/*! string_decoder/ */ \"./node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\nfunction Readable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n if (!(this instanceof Readable)) return new Readable(options);\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex);\n\n // legacy\n this.readable = true;\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n Stream.call(this);\n}\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n }\n\n // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n return er;\n}\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = (__webpack_require__(/*! string_decoder/ */ \"./node_modules/string_decoder/lib/string_decoder.js\").StringDecoder);\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder;\n // If setEncoding(null), decoder.encoding equals utf8\n this._readableState.encoding = this._readableState.decoder.encoding;\n\n // Iterate over current buffer to convert already stored Buffers:\n var p = this._readableState.buffer.head;\n var content = '';\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n this._readableState.buffer.clear();\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n};\n\n// Don't raise the hwm > 1GB\nvar MAX_HWM = 0x40000000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n }\n\n // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n return dest;\n};\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0;\n\n // Try start flowing on next tick if stream isn't explicitly paused\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n return res;\n};\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n return res;\n};\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true;\n\n // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n state.paused = false;\n return this;\n};\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n if (!state.reading) {\n stream.read(0);\n }\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n this._readableState.paused = true;\n return this;\n};\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null);\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n return this;\n};\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = __webpack_require__(/*! ./internal/streams/async_iterator */ \"./node_modules/readable-stream/lib/internal/streams/async_iterator.js\");\n }\n return createReadableStreamAsyncIterator(this);\n };\n}\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n});\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length);\n\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = __webpack_require__(/*! ./internal/streams/from */ \"./node_modules/readable-stream/lib/internal/streams/from-browser.js\");\n }\n return from(Readable, iterable, opts);\n };\n}\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/_stream_readable.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_transform.js": +/*!***************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_transform.js ***! + \***************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\n\nmodule.exports = Transform;\nvar _require$codes = (__webpack_require__(/*! ../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes),\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\nvar Duplex = __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n__webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")(Transform, Duplex);\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null)\n // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\nfunction prefinish() {\n var _this = this;\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null)\n // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/_stream_transform.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/_stream_writable.js": +/*!**************************************************************!*\ + !*** ./node_modules/readable-stream/lib/_stream_writable.js ***! + \**************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar internalUtil = {\n deprecate: __webpack_require__(/*! util-deprecate */ \"./node_modules/util-deprecate/browser.js\")\n};\n/**/\n\n/**/\nvar Stream = __webpack_require__(/*! ./internal/streams/stream */ \"./node_modules/readable-stream/lib/internal/streams/stream-browser.js\");\n/**/\n\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer);\nvar OurUint8Array = (typeof __webpack_require__.g !== 'undefined' ? __webpack_require__.g : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\nvar destroyImpl = __webpack_require__(/*! ./internal/streams/destroy */ \"./node_modules/readable-stream/lib/internal/streams/destroy.js\");\nvar _require = __webpack_require__(/*! ./internal/streams/state */ \"./node_modules/readable-stream/lib/internal/streams/state.js\"),\n getHighWaterMark = _require.getHighWaterMark;\nvar _require$codes = (__webpack_require__(/*! ../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes),\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n__webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")(Writable, Stream);\nfunction nop() {}\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = options.emitClose !== false;\n\n // Should .destroy() be called after 'finish' (and potentially 'end')\n this.autoDestroy = !!options.autoDestroy;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\nfunction Writable(options) {\n Duplex = Duplex || __webpack_require__(/*! ./_stream_duplex */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex);\n\n // legacy.\n this.writable = true;\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END();\n // TODO: defer error events consistently everywhere, not just the cb\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n return true;\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n return ret;\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n if (entry === null) state.lastBufferedRequest = null;\n }\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\nWritable.prototype._writev = null;\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n errorOrDestroy(stream, err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n return need;\n}\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/_stream_writable.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/async_iterator.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/async_iterator.js ***! + \*****************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\n\nvar _Object$setPrototypeO;\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar finished = __webpack_require__(/*! ./end-of-stream */ \"./node_modules/readable-stream/lib/internal/streams/end-of-stream.js\");\nvar kLastResolve = Symbol('lastResolve');\nvar kLastReject = Symbol('lastReject');\nvar kError = Symbol('error');\nvar kEnded = Symbol('ended');\nvar kLastPromise = Symbol('lastPromise');\nvar kHandlePromise = Symbol('handlePromise');\nvar kStream = Symbol('stream');\nfunction createIterResult(value, done) {\n return {\n value: value,\n done: done\n };\n}\nfunction readAndResolve(iter) {\n var resolve = iter[kLastResolve];\n if (resolve !== null) {\n var data = iter[kStream].read();\n // we defer if data is null\n // we can be expecting either 'end' or\n // 'error'\n if (data !== null) {\n iter[kLastPromise] = null;\n iter[kLastResolve] = null;\n iter[kLastReject] = null;\n resolve(createIterResult(data, false));\n }\n }\n}\nfunction onReadable(iter) {\n // we wait for the next tick, because it might\n // emit an error with process.nextTick\n process.nextTick(readAndResolve, iter);\n}\nfunction wrapForNext(lastPromise, iter) {\n return function (resolve, reject) {\n lastPromise.then(function () {\n if (iter[kEnded]) {\n resolve(createIterResult(undefined, true));\n return;\n }\n iter[kHandlePromise](resolve, reject);\n }, reject);\n };\n}\nvar AsyncIteratorPrototype = Object.getPrototypeOf(function () {});\nvar ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {\n get stream() {\n return this[kStream];\n },\n next: function next() {\n var _this = this;\n // if we have detected an error in the meanwhile\n // reject straight away\n var error = this[kError];\n if (error !== null) {\n return Promise.reject(error);\n }\n if (this[kEnded]) {\n return Promise.resolve(createIterResult(undefined, true));\n }\n if (this[kStream].destroyed) {\n // We need to defer via nextTick because if .destroy(err) is\n // called, the error will be emitted via nextTick, and\n // we cannot guarantee that there is no error lingering around\n // waiting to be emitted.\n return new Promise(function (resolve, reject) {\n process.nextTick(function () {\n if (_this[kError]) {\n reject(_this[kError]);\n } else {\n resolve(createIterResult(undefined, true));\n }\n });\n });\n }\n\n // if we have multiple next() calls\n // we will wait for the previous Promise to finish\n // this logic is optimized to support for await loops,\n // where next() is only called once at a time\n var lastPromise = this[kLastPromise];\n var promise;\n if (lastPromise) {\n promise = new Promise(wrapForNext(lastPromise, this));\n } else {\n // fast path needed to support multiple this.push()\n // without triggering the next() queue\n var data = this[kStream].read();\n if (data !== null) {\n return Promise.resolve(createIterResult(data, false));\n }\n promise = new Promise(this[kHandlePromise]);\n }\n this[kLastPromise] = promise;\n return promise;\n }\n}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {\n return this;\n}), _defineProperty(_Object$setPrototypeO, \"return\", function _return() {\n var _this2 = this;\n // destroy(err, cb) is a private API\n // we can guarantee we have that here, because we control the\n // Readable class this is attached to\n return new Promise(function (resolve, reject) {\n _this2[kStream].destroy(null, function (err) {\n if (err) {\n reject(err);\n return;\n }\n resolve(createIterResult(undefined, true));\n });\n });\n}), _Object$setPrototypeO), AsyncIteratorPrototype);\nvar createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {\n var _Object$create;\n var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {\n value: stream,\n writable: true\n }), _defineProperty(_Object$create, kLastResolve, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kLastReject, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kError, {\n value: null,\n writable: true\n }), _defineProperty(_Object$create, kEnded, {\n value: stream._readableState.endEmitted,\n writable: true\n }), _defineProperty(_Object$create, kHandlePromise, {\n value: function value(resolve, reject) {\n var data = iterator[kStream].read();\n if (data) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(data, false));\n } else {\n iterator[kLastResolve] = resolve;\n iterator[kLastReject] = reject;\n }\n },\n writable: true\n }), _Object$create));\n iterator[kLastPromise] = null;\n finished(stream, function (err) {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n var reject = iterator[kLastReject];\n // reject if we are waiting for data in the Promise\n // returned by next() and store the error\n if (reject !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n reject(err);\n }\n iterator[kError] = err;\n return;\n }\n var resolve = iterator[kLastResolve];\n if (resolve !== null) {\n iterator[kLastPromise] = null;\n iterator[kLastResolve] = null;\n iterator[kLastReject] = null;\n resolve(createIterResult(undefined, true));\n }\n iterator[kEnded] = true;\n });\n stream.on('readable', onReadable.bind(null, iterator));\n return iterator;\n};\nmodule.exports = createReadableStreamAsyncIterator;\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/async_iterator.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/buffer_list.js": +/*!**************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/buffer_list.js ***! + \**************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar _require = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\"),\n Buffer = _require.Buffer;\nvar _require2 = __webpack_require__(/*! util */ \"?ed1b\"),\n inspect = _require2.inspect;\nvar custom = inspect && inspect.custom || 'inspect';\nfunction copyBuffer(src, target, offset) {\n Buffer.prototype.copy.call(src, target, offset);\n}\nmodule.exports = /*#__PURE__*/function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n _createClass(BufferList, [{\n key: \"push\",\n value: function push(v) {\n var entry = {\n data: v,\n next: null\n };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n }\n }, {\n key: \"unshift\",\n value: function unshift(v) {\n var entry = {\n data: v,\n next: this.head\n };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n }\n }, {\n key: \"shift\",\n value: function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n }\n }, {\n key: \"clear\",\n value: function clear() {\n this.head = this.tail = null;\n this.length = 0;\n }\n }, {\n key: \"join\",\n value: function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) ret += s + p.data;\n return ret;\n }\n }, {\n key: \"concat\",\n value: function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n }\n\n // Consumes a specified amount of bytes or characters from the buffered data.\n }, {\n key: \"consume\",\n value: function consume(n, hasStrings) {\n var ret;\n if (n < this.head.data.length) {\n // `slice` is the same for buffers and strings.\n ret = this.head.data.slice(0, n);\n this.head.data = this.head.data.slice(n);\n } else if (n === this.head.data.length) {\n // First chunk is a perfect match.\n ret = this.shift();\n } else {\n // Result spans more than one buffer.\n ret = hasStrings ? this._getString(n) : this._getBuffer(n);\n }\n return ret;\n }\n }, {\n key: \"first\",\n value: function first() {\n return this.head.data;\n }\n\n // Consumes a specified amount of characters from the buffered data.\n }, {\n key: \"_getString\",\n value: function _getString(n) {\n var p = this.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n this.length -= c;\n return ret;\n }\n\n // Consumes a specified amount of bytes from the buffered data.\n }, {\n key: \"_getBuffer\",\n value: function _getBuffer(n) {\n var ret = Buffer.allocUnsafe(n);\n var p = this.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) this.head = p.next;else this.head = this.tail = null;\n } else {\n this.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n this.length -= c;\n return ret;\n }\n\n // Make sure the linked list only shows the minimal necessary information.\n }, {\n key: custom,\n value: function value(_, options) {\n return inspect(this, _objectSpread(_objectSpread({}, options), {}, {\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n }));\n }\n }]);\n return BufferList;\n}();\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/buffer_list.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/destroy.js": +/*!**********************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/destroy.js ***! + \**********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("/* provided dependency */ var process = __webpack_require__(/*! process/browser */ \"./node_modules/process/browser.js\");\n\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n return this;\n}\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/destroy.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/end-of-stream.js": +/*!****************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/end-of-stream.js ***! + \****************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n\n\nvar ERR_STREAM_PREMATURE_CLOSE = (__webpack_require__(/*! ../../../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes).ERR_STREAM_PREMATURE_CLOSE;\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n callback.apply(this, args);\n };\n}\nfunction noop() {}\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n var writableEnded = stream._writableState && stream._writableState.finished;\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n var onclose = function onclose() {\n var err;\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\nmodule.exports = eos;\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/end-of-stream.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/from-browser.js": +/*!***************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/from-browser.js ***! + \***************************************************************************/ +/***/ ((module) => { + +eval("module.exports = function () {\n throw new Error('Readable.from is not available in the browser')\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/from-browser.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/pipeline.js": +/*!***********************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/pipeline.js ***! + \***********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n\n\nvar eos;\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n callback.apply(void 0, arguments);\n };\n}\nvar _require$codes = (__webpack_require__(/*! ../../../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes),\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;\nfunction noop(err) {\n // Rethrow the error if it exists to avoid swallowing it\n if (err) throw err;\n}\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\nfunction destroyer(stream, reading, writing, callback) {\n callback = once(callback);\n var closed = false;\n stream.on('close', function () {\n closed = true;\n });\n if (eos === undefined) eos = __webpack_require__(/*! ./end-of-stream */ \"./node_modules/readable-stream/lib/internal/streams/end-of-stream.js\");\n eos(stream, {\n readable: reading,\n writable: writing\n }, function (err) {\n if (err) return callback(err);\n closed = true;\n callback();\n });\n var destroyed = false;\n return function (err) {\n if (closed) return;\n if (destroyed) return;\n destroyed = true;\n\n // request.destroy just do .end - .abort is what we want\n if (isRequest(stream)) return stream.abort();\n if (typeof stream.destroy === 'function') return stream.destroy();\n callback(err || new ERR_STREAM_DESTROYED('pipe'));\n };\n}\nfunction call(fn) {\n fn();\n}\nfunction pipe(from, to) {\n return from.pipe(to);\n}\nfunction popCallback(streams) {\n if (!streams.length) return noop;\n if (typeof streams[streams.length - 1] !== 'function') return noop;\n return streams.pop();\n}\nfunction pipeline() {\n for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {\n streams[_key] = arguments[_key];\n }\n var callback = popCallback(streams);\n if (Array.isArray(streams[0])) streams = streams[0];\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams');\n }\n var error;\n var destroys = streams.map(function (stream, i) {\n var reading = i < streams.length - 1;\n var writing = i > 0;\n return destroyer(stream, reading, writing, function (err) {\n if (!error) error = err;\n if (err) destroys.forEach(call);\n if (reading) return;\n destroys.forEach(call);\n callback(error);\n });\n });\n return streams.reduce(pipe);\n}\nmodule.exports = pipeline;\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/pipeline.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/state.js": +/*!********************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/state.js ***! + \********************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\n\nvar ERR_INVALID_OPT_VALUE = (__webpack_require__(/*! ../../../errors */ \"./node_modules/readable-stream/errors-browser.js\").codes).ERR_INVALID_OPT_VALUE;\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n return Math.floor(hwm);\n }\n\n // Default value\n return state.objectMode ? 16 : 16 * 1024;\n}\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/state.js?"); + +/***/ }), + +/***/ "./node_modules/readable-stream/lib/internal/streams/stream-browser.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/readable-stream/lib/internal/streams/stream-browser.js ***! + \*****************************************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("module.exports = __webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter;\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/readable-stream/lib/internal/streams/stream-browser.js?"); + +/***/ }), + +/***/ "./node_modules/ripemd160/index.js": +/*!*****************************************!*\ + !*** ./node_modules/ripemd160/index.js ***! + \*****************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +"use strict"; +eval("\nvar Buffer = (__webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\").Buffer)\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar HashBase = __webpack_require__(/*! hash-base */ \"./node_modules/hash-base/index.js\")\n\nvar ARRAY16 = new Array(16)\n\nvar zl = [\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,\n 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,\n 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13\n]\n\nvar zr = [\n 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,\n 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,\n 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,\n 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,\n 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11\n]\n\nvar sl = [\n 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,\n 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,\n 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,\n 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,\n 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6\n]\n\nvar sr = [\n 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,\n 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,\n 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,\n 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,\n 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11\n]\n\nvar hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]\nvar hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]\n\nfunction RIPEMD160 () {\n HashBase.call(this, 64)\n\n // state\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n}\n\ninherits(RIPEMD160, HashBase)\n\nRIPEMD160.prototype._update = function () {\n var words = ARRAY16\n for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)\n\n var al = this._a | 0\n var bl = this._b | 0\n var cl = this._c | 0\n var dl = this._d | 0\n var el = this._e | 0\n\n var ar = this._a | 0\n var br = this._b | 0\n var cr = this._c | 0\n var dr = this._d | 0\n var er = this._e | 0\n\n // computation\n for (var i = 0; i < 80; i += 1) {\n var tl\n var tr\n if (i < 16) {\n tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])\n tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])\n } else if (i < 32) {\n tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])\n tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])\n } else if (i < 48) {\n tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])\n tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])\n } else if (i < 64) {\n tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])\n tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])\n } else { // if (i<80) {\n tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])\n tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])\n }\n\n al = el\n el = dl\n dl = rotl(cl, 10)\n cl = bl\n bl = tl\n\n ar = er\n er = dr\n dr = rotl(cr, 10)\n cr = br\n br = tr\n }\n\n // update state\n var t = (this._b + cl + dr) | 0\n this._b = (this._c + dl + er) | 0\n this._c = (this._d + el + ar) | 0\n this._d = (this._e + al + br) | 0\n this._e = (this._a + bl + cr) | 0\n this._a = t\n}\n\nRIPEMD160.prototype._digest = function () {\n // create padding and handle blocks\n this._block[this._blockOffset++] = 0x80\n if (this._blockOffset > 56) {\n this._block.fill(0, this._blockOffset, 64)\n this._update()\n this._blockOffset = 0\n }\n\n this._block.fill(0, this._blockOffset, 56)\n this._block.writeUInt32LE(this._length[0], 56)\n this._block.writeUInt32LE(this._length[1], 60)\n this._update()\n\n // produce result\n var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)\n buffer.writeInt32LE(this._a, 0)\n buffer.writeInt32LE(this._b, 4)\n buffer.writeInt32LE(this._c, 8)\n buffer.writeInt32LE(this._d, 12)\n buffer.writeInt32LE(this._e, 16)\n return buffer\n}\n\nfunction rotl (x, n) {\n return (x << n) | (x >>> (32 - n))\n}\n\nfunction fn1 (a, b, c, d, e, m, k, s) {\n return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn2 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn3 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn4 (a, b, c, d, e, m, k, s) {\n return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0\n}\n\nfunction fn5 (a, b, c, d, e, m, k, s) {\n return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0\n}\n\nmodule.exports = RIPEMD160\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/ripemd160/index.js?"); + +/***/ }), + +/***/ "./node_modules/safe-buffer/index.js": +/*!*******************************************!*\ + !*** ./node_modules/safe-buffer/index.js ***! + \*******************************************/ +/***/ ((module, exports, __webpack_require__) => { + +eval("/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\")\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/safe-buffer/index.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/hash.js": +/*!*************************************!*\ + !*** ./node_modules/sha.js/hash.js ***! + \*************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\n// prototype class for hash functions\nfunction Hash (blockSize, finalSize) {\n this._block = Buffer.alloc(blockSize)\n this._finalSize = finalSize\n this._blockSize = blockSize\n this._len = 0\n}\n\nHash.prototype.update = function (data, enc) {\n if (typeof data === 'string') {\n enc = enc || 'utf8'\n data = Buffer.from(data, enc)\n }\n\n var block = this._block\n var blockSize = this._blockSize\n var length = data.length\n var accum = this._len\n\n for (var offset = 0; offset < length;) {\n var assigned = accum % blockSize\n var remainder = Math.min(length - offset, blockSize - assigned)\n\n for (var i = 0; i < remainder; i++) {\n block[assigned + i] = data[offset + i]\n }\n\n accum += remainder\n offset += remainder\n\n if ((accum % blockSize) === 0) {\n this._update(block)\n }\n }\n\n this._len += length\n return this\n}\n\nHash.prototype.digest = function (enc) {\n var rem = this._len % this._blockSize\n\n this._block[rem] = 0x80\n\n // zero (rem + 1) trailing bits, where (rem + 1) is the smallest\n // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize\n this._block.fill(0, rem + 1)\n\n if (rem >= this._finalSize) {\n this._update(this._block)\n this._block.fill(0)\n }\n\n var bits = this._len * 8\n\n // uint32\n if (bits <= 0xffffffff) {\n this._block.writeUInt32BE(bits, this._blockSize - 4)\n\n // uint64\n } else {\n var lowBits = (bits & 0xffffffff) >>> 0\n var highBits = (bits - lowBits) / 0x100000000\n\n this._block.writeUInt32BE(highBits, this._blockSize - 8)\n this._block.writeUInt32BE(lowBits, this._blockSize - 4)\n }\n\n this._update(this._block)\n var hash = this._hash()\n\n return enc ? hash.toString(enc) : hash\n}\n\nHash.prototype._update = function () {\n throw new Error('_update must be implemented by subclass')\n}\n\nmodule.exports = Hash\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/hash.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/index.js": +/*!**************************************!*\ + !*** ./node_modules/sha.js/index.js ***! + \**************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var exports = module.exports = function SHA (algorithm) {\n algorithm = algorithm.toLowerCase()\n\n var Algorithm = exports[algorithm]\n if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')\n\n return new Algorithm()\n}\n\nexports.sha = __webpack_require__(/*! ./sha */ \"./node_modules/sha.js/sha.js\")\nexports.sha1 = __webpack_require__(/*! ./sha1 */ \"./node_modules/sha.js/sha1.js\")\nexports.sha224 = __webpack_require__(/*! ./sha224 */ \"./node_modules/sha.js/sha224.js\")\nexports.sha256 = __webpack_require__(/*! ./sha256 */ \"./node_modules/sha.js/sha256.js\")\nexports.sha384 = __webpack_require__(/*! ./sha384 */ \"./node_modules/sha.js/sha384.js\")\nexports.sha512 = __webpack_require__(/*! ./sha512 */ \"./node_modules/sha.js/sha512.js\")\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/index.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha.js": +/*!************************************!*\ + !*** ./node_modules/sha.js/sha.js ***! + \************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/*\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined\n * in FIPS PUB 180-1\n * This source code is derived from sha1.js of the same repository.\n * The difference between SHA-0 and SHA-1 is just a bitwise rotate left\n * operation was added.\n */\n\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar K = [\n 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0\n]\n\nvar W = new Array(80)\n\nfunction Sha () {\n this.init()\n this._w = W\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha, Hash)\n\nSha.prototype.init = function () {\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n\n return this\n}\n\nfunction rotl5 (num) {\n return (num << 5) | (num >>> 27)\n}\n\nfunction rotl30 (num) {\n return (num << 30) | (num >>> 2)\n}\n\nfunction ft (s, b, c, d) {\n if (s === 0) return (b & c) | ((~b) & d)\n if (s === 2) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\nSha.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]\n\n for (var j = 0; j < 80; ++j) {\n var s = ~~(j / 20)\n var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0\n\n e = d\n d = c\n c = rotl30(b)\n b = a\n a = t\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n}\n\nSha.prototype._hash = function () {\n var H = Buffer.allocUnsafe(20)\n\n H.writeInt32BE(this._a | 0, 0)\n H.writeInt32BE(this._b | 0, 4)\n H.writeInt32BE(this._c | 0, 8)\n H.writeInt32BE(this._d | 0, 12)\n H.writeInt32BE(this._e | 0, 16)\n\n return H\n}\n\nmodule.exports = Sha\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha1.js": +/*!*************************************!*\ + !*** ./node_modules/sha.js/sha1.js ***! + \*************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/*\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined\n * in FIPS PUB 180-1\n * Version 2.1a Copyright Paul Johnston 2000 - 2002.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for details.\n */\n\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar K = [\n 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0\n]\n\nvar W = new Array(80)\n\nfunction Sha1 () {\n this.init()\n this._w = W\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha1, Hash)\n\nSha1.prototype.init = function () {\n this._a = 0x67452301\n this._b = 0xefcdab89\n this._c = 0x98badcfe\n this._d = 0x10325476\n this._e = 0xc3d2e1f0\n\n return this\n}\n\nfunction rotl1 (num) {\n return (num << 1) | (num >>> 31)\n}\n\nfunction rotl5 (num) {\n return (num << 5) | (num >>> 27)\n}\n\nfunction rotl30 (num) {\n return (num << 30) | (num >>> 2)\n}\n\nfunction ft (s, b, c, d) {\n if (s === 0) return (b & c) | ((~b) & d)\n if (s === 2) return (b & c) | (b & d) | (c & d)\n return b ^ c ^ d\n}\n\nSha1.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])\n\n for (var j = 0; j < 80; ++j) {\n var s = ~~(j / 20)\n var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0\n\n e = d\n d = c\n c = rotl30(b)\n b = a\n a = t\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n}\n\nSha1.prototype._hash = function () {\n var H = Buffer.allocUnsafe(20)\n\n H.writeInt32BE(this._a | 0, 0)\n H.writeInt32BE(this._b | 0, 4)\n H.writeInt32BE(this._c | 0, 8)\n H.writeInt32BE(this._d | 0, 12)\n H.writeInt32BE(this._e | 0, 16)\n\n return H\n}\n\nmodule.exports = Sha1\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha1.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha224.js": +/*!***************************************!*\ + !*** ./node_modules/sha.js/sha224.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/**\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined\n * in FIPS 180-2\n * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n *\n */\n\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Sha256 = __webpack_require__(/*! ./sha256 */ \"./node_modules/sha.js/sha256.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar W = new Array(64)\n\nfunction Sha224 () {\n this.init()\n\n this._w = W // new Array(64)\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha224, Sha256)\n\nSha224.prototype.init = function () {\n this._a = 0xc1059ed8\n this._b = 0x367cd507\n this._c = 0x3070dd17\n this._d = 0xf70e5939\n this._e = 0xffc00b31\n this._f = 0x68581511\n this._g = 0x64f98fa7\n this._h = 0xbefa4fa4\n\n return this\n}\n\nSha224.prototype._hash = function () {\n var H = Buffer.allocUnsafe(28)\n\n H.writeInt32BE(this._a, 0)\n H.writeInt32BE(this._b, 4)\n H.writeInt32BE(this._c, 8)\n H.writeInt32BE(this._d, 12)\n H.writeInt32BE(this._e, 16)\n H.writeInt32BE(this._f, 20)\n H.writeInt32BE(this._g, 24)\n\n return H\n}\n\nmodule.exports = Sha224\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha224.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha256.js": +/*!***************************************!*\ + !*** ./node_modules/sha.js/sha256.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("/**\n * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined\n * in FIPS 180-2\n * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n *\n */\n\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar K = [\n 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,\n 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,\n 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,\n 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,\n 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,\n 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,\n 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,\n 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,\n 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,\n 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,\n 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,\n 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,\n 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,\n 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,\n 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,\n 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2\n]\n\nvar W = new Array(64)\n\nfunction Sha256 () {\n this.init()\n\n this._w = W // new Array(64)\n\n Hash.call(this, 64, 56)\n}\n\ninherits(Sha256, Hash)\n\nSha256.prototype.init = function () {\n this._a = 0x6a09e667\n this._b = 0xbb67ae85\n this._c = 0x3c6ef372\n this._d = 0xa54ff53a\n this._e = 0x510e527f\n this._f = 0x9b05688c\n this._g = 0x1f83d9ab\n this._h = 0x5be0cd19\n\n return this\n}\n\nfunction ch (x, y, z) {\n return z ^ (x & (y ^ z))\n}\n\nfunction maj (x, y, z) {\n return (x & y) | (z & (x | y))\n}\n\nfunction sigma0 (x) {\n return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)\n}\n\nfunction sigma1 (x) {\n return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)\n}\n\nfunction gamma0 (x) {\n return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)\n}\n\nfunction gamma1 (x) {\n return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)\n}\n\nSha256.prototype._update = function (M) {\n var W = this._w\n\n var a = this._a | 0\n var b = this._b | 0\n var c = this._c | 0\n var d = this._d | 0\n var e = this._e | 0\n var f = this._f | 0\n var g = this._g | 0\n var h = this._h | 0\n\n for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)\n for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0\n\n for (var j = 0; j < 64; ++j) {\n var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0\n var T2 = (sigma0(a) + maj(a, b, c)) | 0\n\n h = g\n g = f\n f = e\n e = (d + T1) | 0\n d = c\n c = b\n b = a\n a = (T1 + T2) | 0\n }\n\n this._a = (a + this._a) | 0\n this._b = (b + this._b) | 0\n this._c = (c + this._c) | 0\n this._d = (d + this._d) | 0\n this._e = (e + this._e) | 0\n this._f = (f + this._f) | 0\n this._g = (g + this._g) | 0\n this._h = (h + this._h) | 0\n}\n\nSha256.prototype._hash = function () {\n var H = Buffer.allocUnsafe(32)\n\n H.writeInt32BE(this._a, 0)\n H.writeInt32BE(this._b, 4)\n H.writeInt32BE(this._c, 8)\n H.writeInt32BE(this._d, 12)\n H.writeInt32BE(this._e, 16)\n H.writeInt32BE(this._f, 20)\n H.writeInt32BE(this._g, 24)\n H.writeInt32BE(this._h, 28)\n\n return H\n}\n\nmodule.exports = Sha256\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha256.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha384.js": +/*!***************************************!*\ + !*** ./node_modules/sha.js/sha384.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar SHA512 = __webpack_require__(/*! ./sha512 */ \"./node_modules/sha.js/sha512.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar W = new Array(160)\n\nfunction Sha384 () {\n this.init()\n this._w = W\n\n Hash.call(this, 128, 112)\n}\n\ninherits(Sha384, SHA512)\n\nSha384.prototype.init = function () {\n this._ah = 0xcbbb9d5d\n this._bh = 0x629a292a\n this._ch = 0x9159015a\n this._dh = 0x152fecd8\n this._eh = 0x67332667\n this._fh = 0x8eb44a87\n this._gh = 0xdb0c2e0d\n this._hh = 0x47b5481d\n\n this._al = 0xc1059ed8\n this._bl = 0x367cd507\n this._cl = 0x3070dd17\n this._dl = 0xf70e5939\n this._el = 0xffc00b31\n this._fl = 0x68581511\n this._gl = 0x64f98fa7\n this._hl = 0xbefa4fa4\n\n return this\n}\n\nSha384.prototype._hash = function () {\n var H = Buffer.allocUnsafe(48)\n\n function writeInt64BE (h, l, offset) {\n H.writeInt32BE(h, offset)\n H.writeInt32BE(l, offset + 4)\n }\n\n writeInt64BE(this._ah, this._al, 0)\n writeInt64BE(this._bh, this._bl, 8)\n writeInt64BE(this._ch, this._cl, 16)\n writeInt64BE(this._dh, this._dl, 24)\n writeInt64BE(this._eh, this._el, 32)\n writeInt64BE(this._fh, this._fl, 40)\n\n return H\n}\n\nmodule.exports = Sha384\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha384.js?"); + +/***/ }), + +/***/ "./node_modules/sha.js/sha512.js": +/*!***************************************!*\ + !*** ./node_modules/sha.js/sha512.js ***! + \***************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("var inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\")\nvar Hash = __webpack_require__(/*! ./hash */ \"./node_modules/sha.js/hash.js\")\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer)\n\nvar K = [\n 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,\n 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,\n 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,\n 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,\n 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,\n 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,\n 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,\n 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,\n 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,\n 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,\n 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,\n 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,\n 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,\n 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,\n 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,\n 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,\n 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,\n 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,\n 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,\n 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,\n 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,\n 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,\n 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,\n 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,\n 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,\n 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,\n 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,\n 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,\n 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,\n 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,\n 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,\n 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,\n 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,\n 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,\n 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,\n 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,\n 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,\n 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,\n 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,\n 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817\n]\n\nvar W = new Array(160)\n\nfunction Sha512 () {\n this.init()\n this._w = W\n\n Hash.call(this, 128, 112)\n}\n\ninherits(Sha512, Hash)\n\nSha512.prototype.init = function () {\n this._ah = 0x6a09e667\n this._bh = 0xbb67ae85\n this._ch = 0x3c6ef372\n this._dh = 0xa54ff53a\n this._eh = 0x510e527f\n this._fh = 0x9b05688c\n this._gh = 0x1f83d9ab\n this._hh = 0x5be0cd19\n\n this._al = 0xf3bcc908\n this._bl = 0x84caa73b\n this._cl = 0xfe94f82b\n this._dl = 0x5f1d36f1\n this._el = 0xade682d1\n this._fl = 0x2b3e6c1f\n this._gl = 0xfb41bd6b\n this._hl = 0x137e2179\n\n return this\n}\n\nfunction Ch (x, y, z) {\n return z ^ (x & (y ^ z))\n}\n\nfunction maj (x, y, z) {\n return (x & y) | (z & (x | y))\n}\n\nfunction sigma0 (x, xl) {\n return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)\n}\n\nfunction sigma1 (x, xl) {\n return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)\n}\n\nfunction Gamma0 (x, xl) {\n return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)\n}\n\nfunction Gamma0l (x, xl) {\n return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)\n}\n\nfunction Gamma1 (x, xl) {\n return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)\n}\n\nfunction Gamma1l (x, xl) {\n return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)\n}\n\nfunction getCarry (a, b) {\n return (a >>> 0) < (b >>> 0) ? 1 : 0\n}\n\nSha512.prototype._update = function (M) {\n var W = this._w\n\n var ah = this._ah | 0\n var bh = this._bh | 0\n var ch = this._ch | 0\n var dh = this._dh | 0\n var eh = this._eh | 0\n var fh = this._fh | 0\n var gh = this._gh | 0\n var hh = this._hh | 0\n\n var al = this._al | 0\n var bl = this._bl | 0\n var cl = this._cl | 0\n var dl = this._dl | 0\n var el = this._el | 0\n var fl = this._fl | 0\n var gl = this._gl | 0\n var hl = this._hl | 0\n\n for (var i = 0; i < 32; i += 2) {\n W[i] = M.readInt32BE(i * 4)\n W[i + 1] = M.readInt32BE(i * 4 + 4)\n }\n for (; i < 160; i += 2) {\n var xh = W[i - 15 * 2]\n var xl = W[i - 15 * 2 + 1]\n var gamma0 = Gamma0(xh, xl)\n var gamma0l = Gamma0l(xl, xh)\n\n xh = W[i - 2 * 2]\n xl = W[i - 2 * 2 + 1]\n var gamma1 = Gamma1(xh, xl)\n var gamma1l = Gamma1l(xl, xh)\n\n // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]\n var Wi7h = W[i - 7 * 2]\n var Wi7l = W[i - 7 * 2 + 1]\n\n var Wi16h = W[i - 16 * 2]\n var Wi16l = W[i - 16 * 2 + 1]\n\n var Wil = (gamma0l + Wi7l) | 0\n var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0\n Wil = (Wil + gamma1l) | 0\n Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0\n Wil = (Wil + Wi16l) | 0\n Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0\n\n W[i] = Wih\n W[i + 1] = Wil\n }\n\n for (var j = 0; j < 160; j += 2) {\n Wih = W[j]\n Wil = W[j + 1]\n\n var majh = maj(ah, bh, ch)\n var majl = maj(al, bl, cl)\n\n var sigma0h = sigma0(ah, al)\n var sigma0l = sigma0(al, ah)\n var sigma1h = sigma1(eh, el)\n var sigma1l = sigma1(el, eh)\n\n // t1 = h + sigma1 + ch + K[j] + W[j]\n var Kih = K[j]\n var Kil = K[j + 1]\n\n var chh = Ch(eh, fh, gh)\n var chl = Ch(el, fl, gl)\n\n var t1l = (hl + sigma1l) | 0\n var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0\n t1l = (t1l + chl) | 0\n t1h = (t1h + chh + getCarry(t1l, chl)) | 0\n t1l = (t1l + Kil) | 0\n t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0\n t1l = (t1l + Wil) | 0\n t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0\n\n // t2 = sigma0 + maj\n var t2l = (sigma0l + majl) | 0\n var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0\n\n hh = gh\n hl = gl\n gh = fh\n gl = fl\n fh = eh\n fl = el\n el = (dl + t1l) | 0\n eh = (dh + t1h + getCarry(el, dl)) | 0\n dh = ch\n dl = cl\n ch = bh\n cl = bl\n bh = ah\n bl = al\n al = (t1l + t2l) | 0\n ah = (t1h + t2h + getCarry(al, t1l)) | 0\n }\n\n this._al = (this._al + al) | 0\n this._bl = (this._bl + bl) | 0\n this._cl = (this._cl + cl) | 0\n this._dl = (this._dl + dl) | 0\n this._el = (this._el + el) | 0\n this._fl = (this._fl + fl) | 0\n this._gl = (this._gl + gl) | 0\n this._hl = (this._hl + hl) | 0\n\n this._ah = (this._ah + ah + getCarry(this._al, al)) | 0\n this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0\n this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0\n this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0\n this._eh = (this._eh + eh + getCarry(this._el, el)) | 0\n this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0\n this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0\n this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0\n}\n\nSha512.prototype._hash = function () {\n var H = Buffer.allocUnsafe(64)\n\n function writeInt64BE (h, l, offset) {\n H.writeInt32BE(h, offset)\n H.writeInt32BE(l, offset + 4)\n }\n\n writeInt64BE(this._ah, this._al, 0)\n writeInt64BE(this._bh, this._bl, 8)\n writeInt64BE(this._ch, this._cl, 16)\n writeInt64BE(this._dh, this._dl, 24)\n writeInt64BE(this._eh, this._el, 32)\n writeInt64BE(this._fh, this._fl, 40)\n writeInt64BE(this._gh, this._gl, 48)\n writeInt64BE(this._hh, this._hl, 56)\n\n return H\n}\n\nmodule.exports = Sha512\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/sha.js/sha512.js?"); + +/***/ }), + +/***/ "./node_modules/stream-browserify/index.js": +/*!*************************************************!*\ + !*** ./node_modules/stream-browserify/index.js ***! + \*************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nmodule.exports = Stream;\n\nvar EE = (__webpack_require__(/*! events */ \"./node_modules/events/events.js\").EventEmitter);\nvar inherits = __webpack_require__(/*! inherits */ \"./node_modules/inherits/inherits_browser.js\");\n\ninherits(Stream, EE);\nStream.Readable = __webpack_require__(/*! readable-stream/lib/_stream_readable.js */ \"./node_modules/readable-stream/lib/_stream_readable.js\");\nStream.Writable = __webpack_require__(/*! readable-stream/lib/_stream_writable.js */ \"./node_modules/readable-stream/lib/_stream_writable.js\");\nStream.Duplex = __webpack_require__(/*! readable-stream/lib/_stream_duplex.js */ \"./node_modules/readable-stream/lib/_stream_duplex.js\");\nStream.Transform = __webpack_require__(/*! readable-stream/lib/_stream_transform.js */ \"./node_modules/readable-stream/lib/_stream_transform.js\");\nStream.PassThrough = __webpack_require__(/*! readable-stream/lib/_stream_passthrough.js */ \"./node_modules/readable-stream/lib/_stream_passthrough.js\");\nStream.finished = __webpack_require__(/*! readable-stream/lib/internal/streams/end-of-stream.js */ \"./node_modules/readable-stream/lib/internal/streams/end-of-stream.js\")\nStream.pipeline = __webpack_require__(/*! readable-stream/lib/internal/streams/pipeline.js */ \"./node_modules/readable-stream/lib/internal/streams/pipeline.js\")\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/stream-browserify/index.js?"); + +/***/ }), + +/***/ "./node_modules/string_decoder/lib/string_decoder.js": +/*!***********************************************************!*\ + !*** ./node_modules/string_decoder/lib/string_decoder.js ***! + \***********************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; +eval("// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\n/**/\n\nvar Buffer = (__webpack_require__(/*! safe-buffer */ \"./node_modules/safe-buffer/index.js\").Buffer);\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}\n\n//# sourceURL=webpack://rln-chat/./node_modules/string_decoder/lib/string_decoder.js?"); + +/***/ }), + +/***/ "./src/const.ts": +/*!**********************!*\ + !*** ./src/const.ts ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CONTENT_TOPIC: () => (/* binding */ CONTENT_TOPIC),\n/* harmony export */ KEYSTORE: () => (/* binding */ KEYSTORE),\n/* harmony export */ MEMBERSHIP_HASH: () => (/* binding */ MEMBERSHIP_HASH),\n/* harmony export */ MEMBERSHIP_PASSWORD: () => (/* binding */ MEMBERSHIP_PASSWORD),\n/* harmony export */ ProtoChatMessage: () => (/* binding */ ProtoChatMessage)\n/* harmony export */ });\n/* harmony import */ var protobufjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protobufjs */ \"./node_modules/protobufjs/index.js\");\n/* harmony import */ var protobufjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(protobufjs__WEBPACK_IMPORTED_MODULE_0__);\n\nconst KEYSTORE = `{\n \"application\": \"waku-rln-relay\",\n \"appIdentifier\": \"0.2\",\n \"version\": \"01234567890abcdef\",\n \"credentials\": {\n \"740AF0B31F2DCC5C09264019BE6910FFB9C3CA575A25CC9E378BF67965AF48B4\": {\n \"crypto\": {\n \"cipher\": \"aes-128-ctr\",\n \"cipherparams\": {\n \"iv\": \"2089221b325414adcbbc926cc8cec6dc\"\n },\n \"ciphertext\": \"b3acbe5dc51dc2d67e7e08852577d1d538d5967f632ef097e9887852ea5aac541b4755ed5d4945f61e45437c3f9006836bb4e44d8580524cfb363775c250cb4509f15a0665b16874c9e66fe4a12fd2678002d4bf881806946dd31e510edae962e21a4bc15284442460aa843c630127b9fb46309f403f2480160c56ab9f024e394ba22c5de668e14c2500556a35f8e152d78c18a13faf1dc0542f0ff673f659daf7e8c863339f69e412b22cc83358fea684b61f1c5184ead0004854014f9dbe70b555d91d37b18b12b65ae5860ad67f81dc259f781077b18e226470ce6ae40370db0a32f9d245587dc741212ff636ddbe9fcf0bc68e8c5a9e02bbf35b359b5f5a315cb5a699283121bdde8b2093512aa8d7cef82803a7f2d84d250cb218d34c8a077c566ff7628be42e2ab50d5c115984f54640db0a861917fdaf7391b386c7ff27b48740ce90ede2f025a90fef8f1cf6b02f7c791f83950c53aced5909fef64de2e4c5160880a49b797092abad45acb58986051258628a4c994fe69282aad949d287c4d8efe4cd1ad5863edd71779dffc57ea27b817e8610730223e2b382d3f80f8d51dcb04226a1df0b344de55ff71780b750a0ab58af4360bcbc3b885bb49eb7fa2300464c97d7fda26795f853facdace48251ff6bfdb318747920499c88a68a0a00bb04d39b4357bd543778cf083c1ba38ad43d4c2fb54ee75f8707a02d5fd5b9b36a2298d999d4f008e2b2ae4fc58775d4fb0f7e8db58a6a7cb1feecdda458518916e5c359f953e71a172981efb6dd7ab81aa1b6bb87ebbb81513f19af25525214c15112728e0dd7786459c7c4d9c0ea1df62cd7be42253ab484cc9c8b2b7bfaae4216b26b53b86eb691a4dc91615fcf804f95c50ee8b88ab2ccada1e3633d13cea753258e225e98c3ffbe86ee2327bcf6b540730047da79ffa3661a8783f590470d058454be5d261a77d966105cd8f1560d64635b5ec9882733502a46044d9eabb909acee18a60ade210d26af8eb6007142471174d30b8410df90d667089a28c1ef487dcfe58f14132580fd1a3f771f0e10d19f110c8a54ee5936e395227dcb5d4b895f5d6f9b04118c07671dda3942a9c6836339011e297ef2ca034d0bdc1f44693ea7ee621c532ec3893626f92addafb8518a284873c42a17274da519592a967bf8ad2f646650f39c3e4d4d014f3ff54e4088012b01244cf1dfcd2396d4c36d4f210805f167ec7533254d3a3cdefad7e9d531d6d67fbc497ba0c38036263402489b64d766ea11f4df4b3fe1f4e70b8e8fc708de6fb976fe1fbfae81b1ccb3bc3dc65f61d0b92e8bf39189f5bf2fc727777e3728963cc6163169fc8a0ed72723b506d659f9b2c3048261e295876a88db139c8c15429d9a1e2bb1d3587379e2c504ae384d7563d26dab99fc12069211d6f037e513eb749ad48de58bceb95dcc860abcb0f4c1336e8025a402197434b620d1ec5c8f23230a1d75fff8353259cefc1c837faa335e48be1a49db5a7da89d490cff5f6fbf80c00ecc497ba59cbb69d4ebb57a922e646e66184b41286ceed34ec76be8326f48d66fc79c21512dc847f8b01e0253a469b351beb1288f157348da319856b892448d0b269dafd84c14e1436938e7f322f084207d421d8f5587284c021ac0607524bc29d52be2ce7f3263a237f9b319d5a26349069cf588f8f17e05021bc9bdd6edf90722bf91fb57cc67f9125aa39d09563278bea7acff25bad4968d731501f2ae62a3529d223b88aae57f2670\",\n \"kdf\": \"pbkdf2\",\n \"kdfparams\": {\n \"dklen\": 32,\n \"c\": 262144,\n \"prf\": \"hmac-sha256\",\n \"salt\": \"ff41c018bae51f6cd20e96739a46b4724c854dc6f7d4e741526b2be71f8dc572\"\n },\n \"mac\": \"4b98784366b4dd610e5bc0f672bd91c9410c3d271cd1bd48ca7db2ffe889d9eb\"\n }\n }\n }\n}`;\nconst MEMBERSHIP_HASH = \"740AF0B31F2DCC5C09264019BE6910FFB9C3CA575A25CC9E378BF67965AF48B4\";\nconst MEMBERSHIP_PASSWORD = \"qweqwe\";\nconst CONTENT_TOPIC = \"/toy-chat/2/luzhou/proto\";\nconst ProtoChatMessage = new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Type)(\"ChatMessage\")\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"timestamp\", 1, \"uint64\"))\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"nick\", 2, \"string\"))\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"text\", 3, \"string\"));\n\n\n//# sourceURL=webpack://rln-chat/./src/const.ts?"); + +/***/ }), + +/***/ "./src/index.ts": +/*!**********************!*\ + !*** ./src/index.ts ***! + \**********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ui */ \"./src/ui.ts\");\n/* harmony import */ var _rln__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rln */ \"./src/rln.ts\");\n/* harmony import */ var _waku__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./waku */ \"./src/waku.ts\");\n\n\n\nasync function run() {\n const { onStatusChange, registerEvents } = (0,_ui__WEBPACK_IMPORTED_MODULE_0__.initUI)();\n const { rln, connectWallet } = await (0,_rln__WEBPACK_IMPORTED_MODULE_1__.initRLN)(onStatusChange);\n const { onSend, onSubscribe, onInitWaku } = await (0,_waku__WEBPACK_IMPORTED_MODULE_2__.initWaku)({\n rln,\n onStatusChange,\n });\n registerEvents({ onSend, onSubscribe, connectWallet, onInitWaku });\n}\nrun();\n\n\n//# sourceURL=webpack://rln-chat/./src/index.ts?"); + +/***/ }), + +/***/ "./src/rln.ts": +/*!********************!*\ + !*** ./src/rln.ts ***! + \********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initRLN: () => (/* binding */ initRLN)\n/* harmony export */ });\n/* harmony import */ var _waku_rln__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/rln */ \"./node_modules/@waku/rln/dist/index.js\");\n\nasync function initRLN(onStatusChange) {\n onStatusChange({\n newStatus: \"Initializing RLN...\"\n });\n let rln;\n try {\n console.time(\"createRLN\");\n rln = await (0,_waku_rln__WEBPACK_IMPORTED_MODULE_0__.createRLN)();\n console.timeEnd(\"createRLN\");\n }\n catch (err) {\n onStatusChange({\n newStatus: `Failed to initialize RLN: ${err}`,\n className: \"error\"\n });\n throw err;\n }\n onStatusChange({\n newStatus: \"RLN initialized\",\n className: \"success\"\n });\n const connectWallet = async () => {\n let signer;\n try {\n onStatusChange({\n newStatus: \"Connecting to wallet...\"\n });\n signer = await (0,_waku_rln__WEBPACK_IMPORTED_MODULE_0__.extractMetaMaskSigner)();\n console.log(\"done\");\n }\n catch (err) {\n onStatusChange({\n newStatus: `Failed to access MetaMask: ${err}`,\n className: \"error\"\n });\n throw err;\n }\n try {\n onStatusChange({\n newStatus: \"Connecting to Ethereum...\"\n });\n await rln.start({ signer });\n }\n catch (err) {\n onStatusChange({\n newStatus: `Failed to connect to Ethereum: ${err}`,\n className: \"error\"\n });\n throw err;\n }\n onStatusChange({\n newStatus: \"RLN started\",\n className: \"success\"\n });\n };\n return {\n rln,\n connectWallet,\n };\n}\n\n\n//# sourceURL=webpack://rln-chat/./src/rln.ts?"); + +/***/ }), + +/***/ "./src/ui.ts": +/*!*******************!*\ + !*** ./src/ui.ts ***! + \*******************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initUI: () => (/* binding */ initUI)\n/* harmony export */ });\nconst status = document.getElementById(\"status\");\nconst chat = document.getElementById(\"chat-area\");\nconst messages = document.getElementById(\"messages\");\nconst nickInput = document.getElementById(\"nick\");\nconst textInput = document.getElementById(\"text\");\nconst sendButton = document.getElementById(\"send\");\nconst connectWalletButton = document.getElementById(\"connect\");\nconst initUI = () => {\n const onStatusChange = ({ newStatus, className }) => {\n if (!status) {\n console.log(\"Status element not found.\");\n return;\n }\n status.innerText = newStatus;\n status.className = className || \"progress\";\n };\n const onLoaded = () => {\n if (!chat) {\n console.log(\"Chat element not found.\");\n return;\n }\n chat.style.display = \"block\";\n };\n const _renderMessage = (nick, text, timestamp, proofStatus) => {\n if (!messages) {\n console.log(\"Messages element not found.\");\n return;\n }\n messages.innerHTML += `\n
  • \n (${nick})(${proofStatus})\n ${text}\n [${new Date(timestamp).toISOString()}]\n
  • \n `;\n };\n const registerEvents = (events) => {\n if (!connectWalletButton) {\n console.log(\"Connect wallet button not found.\");\n return;\n }\n if (!sendButton) {\n console.log(\"Send button not found.\");\n return;\n }\n connectWalletButton.addEventListener(\"click\", async () => {\n await events.connectWallet();\n await events.onInitWaku();\n onLoaded();\n events.onSubscribe((nick, text, timestamp, proofStatus) => {\n _renderMessage(nick, text, timestamp, proofStatus);\n });\n sendButton.addEventListener(\"click\", async () => {\n if (!nickInput || !textInput) {\n console.log(\"Nick or text input not found.\");\n return;\n }\n if (!events.onSend) {\n console.log(\"onSend event not found.\");\n return;\n }\n const nick = nickInput.value;\n const text = textInput.value;\n if (!nick || !text) {\n console.log(\"Not sending message: missing nick or text.\");\n return;\n }\n await events.onSend(nick, text);\n textInput.value = \"\";\n });\n });\n };\n return {\n registerEvents,\n onStatusChange,\n };\n};\n\n\n//# sourceURL=webpack://rln-chat/./src/ui.ts?"); + +/***/ }), + +/***/ "./src/waku.ts": +/*!*********************!*\ + !*** ./src/waku.ts ***! + \*********************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initWaku: () => (/* binding */ initWaku)\n/* harmony export */ });\n/* harmony import */ var _waku_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/sdk */ \"./node_modules/@waku/sdk/dist/index.js\");\n/* harmony import */ var _const__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./const */ \"./src/const.ts\");\n\n\nasync function initWaku({ rln, onStatusChange }) {\n let node;\n let encoder, decoder;\n let subscription;\n const onInitWaku = async () => {\n encoder = await rln.createEncoder({\n ephemeral: false,\n contentTopic: _const__WEBPACK_IMPORTED_MODULE_1__.CONTENT_TOPIC,\n credentials: {\n keystore: _const__WEBPACK_IMPORTED_MODULE_1__.KEYSTORE,\n id: _const__WEBPACK_IMPORTED_MODULE_1__.MEMBERSHIP_HASH,\n password: _const__WEBPACK_IMPORTED_MODULE_1__.MEMBERSHIP_PASSWORD,\n },\n });\n decoder = rln.createDecoder(_const__WEBPACK_IMPORTED_MODULE_1__.CONTENT_TOPIC);\n onStatusChange({\n newStatus: \"Initializing Waku...\"\n });\n node = await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createLightNode)({\n defaultBootstrap: true,\n });\n onStatusChange({\n newStatus: \"Waiting for peers\"\n });\n await node.start();\n await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.waitForRemotePeer)(node);\n };\n const onSend = async (nick, text) => {\n const timestamp = new Date();\n const msg = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.create({\n text,\n nick,\n timestamp: Math.floor(timestamp.valueOf() / 1000),\n });\n const payload = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.encode(msg).finish();\n console.log(\"Sending message with proof...\");\n const res = await node.lightPush.send(encoder, { payload, timestamp });\n console.log(\"Message sent:\", res);\n };\n const onSubscribe = async (cb) => {\n onStatusChange({\n newStatus: \"Subscribing to content topic...\"\n });\n subscription = await node.filter.createSubscription();\n await subscription.subscribe(decoder, (message) => {\n try {\n const { timestamp, nick, text } = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.decode(message.payload);\n let proofStatus = \"no proof\";\n if (message.rateLimitProof) {\n console.log(\"Proof received: \", message.rateLimitProof);\n try {\n if (!rln.contract) {\n throw new Error(\"RLN contract not initialized\");\n }\n console.time(\"Proof verification took:\");\n const res = message.verify(rln.contract.roots());\n console.timeEnd(\"Proof verification took:\");\n proofStatus = res ? \"verified\" : \"not verified\";\n }\n catch (error) {\n proofStatus = \"invalid\";\n console.error(\"Failed to verify proof: \", error);\n }\n }\n console.log({\n nick,\n text,\n proofStatus,\n time: new Date(timestamp).toDateString(),\n });\n cb(nick, text, timestamp, proofStatus);\n }\n catch (error) {\n console.error(\"Failed in subscription listener: \", error);\n }\n });\n onStatusChange({\n newStatus: \"Waku initialized\",\n className: \"success\"\n });\n };\n return {\n onSend,\n onSubscribe,\n onInitWaku,\n };\n}\n\n\n//# sourceURL=webpack://rln-chat/./src/waku.ts?"); + +/***/ }), + +/***/ "./node_modules/util-deprecate/browser.js": +/*!************************************************!*\ + !*** ./node_modules/util-deprecate/browser.js ***! + \************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +eval("\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!__webpack_require__.g.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = __webpack_require__.g.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/util-deprecate/browser.js?"); + +/***/ }), + /***/ "./node_modules/uuid/dist/commonjs-browser/index.js": /*!**********************************************************!*\ !*** ./node_modules/uuid/dist/commonjs-browser/index.js ***! @@ -2380,58 +4230,13 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./src/const.js": -/*!**********************!*\ - !*** ./src/const.js ***! - \**********************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./node_modules/vm-browserify/index.js": +/*!*********************************************!*\ + !*** ./node_modules/vm-browserify/index.js ***! + \*********************************************/ +/***/ ((__unused_webpack_module, exports) => { -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CONTENT_TOPIC: () => (/* binding */ CONTENT_TOPIC),\n/* harmony export */ KEYSTORE: () => (/* binding */ KEYSTORE),\n/* harmony export */ MEMBERSHIP_HASH: () => (/* binding */ MEMBERSHIP_HASH),\n/* harmony export */ MEMBERSHIP_PASSWORD: () => (/* binding */ MEMBERSHIP_PASSWORD),\n/* harmony export */ ProtoChatMessage: () => (/* binding */ ProtoChatMessage)\n/* harmony export */ });\n/* harmony import */ var protobufjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protobufjs */ \"./node_modules/protobufjs/index.js\");\n/* harmony import */ var protobufjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(protobufjs__WEBPACK_IMPORTED_MODULE_0__);\n\n\nconst KEYSTORE = `{\n \"application\": \"waku-rln-relay\",\n \"appIdentifier\": \"0.2\",\n \"version\": \"01234567890abcdef\",\n \"credentials\": {\n \"740AF0B31F2DCC5C09264019BE6910FFB9C3CA575A25CC9E378BF67965AF48B4\": {\n \"crypto\": {\n \"cipher\": \"aes-128-ctr\",\n \"cipherparams\": {\n \"iv\": \"2089221b325414adcbbc926cc8cec6dc\"\n },\n \"ciphertext\": \"b3acbe5dc51dc2d67e7e08852577d1d538d5967f632ef097e9887852ea5aac541b4755ed5d4945f61e45437c3f9006836bb4e44d8580524cfb363775c250cb4509f15a0665b16874c9e66fe4a12fd2678002d4bf881806946dd31e510edae962e21a4bc15284442460aa843c630127b9fb46309f403f2480160c56ab9f024e394ba22c5de668e14c2500556a35f8e152d78c18a13faf1dc0542f0ff673f659daf7e8c863339f69e412b22cc83358fea684b61f1c5184ead0004854014f9dbe70b555d91d37b18b12b65ae5860ad67f81dc259f781077b18e226470ce6ae40370db0a32f9d245587dc741212ff636ddbe9fcf0bc68e8c5a9e02bbf35b359b5f5a315cb5a699283121bdde8b2093512aa8d7cef82803a7f2d84d250cb218d34c8a077c566ff7628be42e2ab50d5c115984f54640db0a861917fdaf7391b386c7ff27b48740ce90ede2f025a90fef8f1cf6b02f7c791f83950c53aced5909fef64de2e4c5160880a49b797092abad45acb58986051258628a4c994fe69282aad949d287c4d8efe4cd1ad5863edd71779dffc57ea27b817e8610730223e2b382d3f80f8d51dcb04226a1df0b344de55ff71780b750a0ab58af4360bcbc3b885bb49eb7fa2300464c97d7fda26795f853facdace48251ff6bfdb318747920499c88a68a0a00bb04d39b4357bd543778cf083c1ba38ad43d4c2fb54ee75f8707a02d5fd5b9b36a2298d999d4f008e2b2ae4fc58775d4fb0f7e8db58a6a7cb1feecdda458518916e5c359f953e71a172981efb6dd7ab81aa1b6bb87ebbb81513f19af25525214c15112728e0dd7786459c7c4d9c0ea1df62cd7be42253ab484cc9c8b2b7bfaae4216b26b53b86eb691a4dc91615fcf804f95c50ee8b88ab2ccada1e3633d13cea753258e225e98c3ffbe86ee2327bcf6b540730047da79ffa3661a8783f590470d058454be5d261a77d966105cd8f1560d64635b5ec9882733502a46044d9eabb909acee18a60ade210d26af8eb6007142471174d30b8410df90d667089a28c1ef487dcfe58f14132580fd1a3f771f0e10d19f110c8a54ee5936e395227dcb5d4b895f5d6f9b04118c07671dda3942a9c6836339011e297ef2ca034d0bdc1f44693ea7ee621c532ec3893626f92addafb8518a284873c42a17274da519592a967bf8ad2f646650f39c3e4d4d014f3ff54e4088012b01244cf1dfcd2396d4c36d4f210805f167ec7533254d3a3cdefad7e9d531d6d67fbc497ba0c38036263402489b64d766ea11f4df4b3fe1f4e70b8e8fc708de6fb976fe1fbfae81b1ccb3bc3dc65f61d0b92e8bf39189f5bf2fc727777e3728963cc6163169fc8a0ed72723b506d659f9b2c3048261e295876a88db139c8c15429d9a1e2bb1d3587379e2c504ae384d7563d26dab99fc12069211d6f037e513eb749ad48de58bceb95dcc860abcb0f4c1336e8025a402197434b620d1ec5c8f23230a1d75fff8353259cefc1c837faa335e48be1a49db5a7da89d490cff5f6fbf80c00ecc497ba59cbb69d4ebb57a922e646e66184b41286ceed34ec76be8326f48d66fc79c21512dc847f8b01e0253a469b351beb1288f157348da319856b892448d0b269dafd84c14e1436938e7f322f084207d421d8f5587284c021ac0607524bc29d52be2ce7f3263a237f9b319d5a26349069cf588f8f17e05021bc9bdd6edf90722bf91fb57cc67f9125aa39d09563278bea7acff25bad4968d731501f2ae62a3529d223b88aae57f2670\",\n \"kdf\": \"pbkdf2\",\n \"kdfparams\": {\n \"dklen\": 32,\n \"c\": 262144,\n \"prf\": \"hmac-sha256\",\n \"salt\": \"ff41c018bae51f6cd20e96739a46b4724c854dc6f7d4e741526b2be71f8dc572\"\n },\n \"mac\": \"4b98784366b4dd610e5bc0f672bd91c9410c3d271cd1bd48ca7db2ffe889d9eb\"\n }\n }\n }\n}`;\nconst MEMBERSHIP_HASH =\n \"740AF0B31F2DCC5C09264019BE6910FFB9C3CA575A25CC9E378BF67965AF48B4\";\nconst MEMBERSHIP_PASSWORD = \"qweqwe\";\n\nconst CONTENT_TOPIC = \"/toy-chat/2/luzhou/proto\";\nconst ProtoChatMessage = new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Type)(\"ChatMessage\")\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"timestamp\", 1, \"uint64\"))\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"nick\", 2, \"string\"))\n .add(new (protobufjs__WEBPACK_IMPORTED_MODULE_0___default().Field)(\"text\", 3, \"string\"));\n\n\n//# sourceURL=webpack://rln-chat/./src/const.js?"); - -/***/ }), - -/***/ "./src/index.js": -/*!**********************!*\ - !*** ./src/index.js ***! - \**********************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _ui__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ui */ \"./src/ui.js\");\n/* harmony import */ var _rln__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rln */ \"./src/rln.js\");\n/* harmony import */ var _waku__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./waku */ \"./src/waku.js\");\n\n\n\n\nasync function run() {\n const { onStatusChange, registerEvents } = (0,_ui__WEBPACK_IMPORTED_MODULE_0__.initUI)();\n const { rln, connectWallet } = await (0,_rln__WEBPACK_IMPORTED_MODULE_1__.initRLN)(onStatusChange);\n const { onSend, onSubscribe, onInitWaku } = await (0,_waku__WEBPACK_IMPORTED_MODULE_2__.initWaku)({\n rln,\n onStatusChange,\n });\n\n registerEvents({ onSend, onSubscribe, connectWallet, onInitWaku });\n}\n\nrun();\n\n\n//# sourceURL=webpack://rln-chat/./src/index.js?"); - -/***/ }), - -/***/ "./src/rln.js": -/*!********************!*\ - !*** ./src/rln.js ***! - \********************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initRLN: () => (/* binding */ initRLN)\n/* harmony export */ });\n/* harmony import */ var _waku_rln__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/rln */ \"./node_modules/@waku/rln/dist/index.js\");\n\n\nasync function initRLN(onStatusChange) {\n onStatusChange(\"Initializing RLN...\");\n\n let rln;\n try {\n rln = await (0,_waku_rln__WEBPACK_IMPORTED_MODULE_0__.createRLN)();\n } catch (err) {\n onStatusChange(`Failed to initialize RLN: ${err}`, \"error\");\n throw Error(err);\n }\n\n onStatusChange(\"RLN initialized\", \"success\");\n\n const connectWallet = async () => {\n let signer;\n try {\n onStatusChange(\"Connecting to wallet...\");\n signer = await (0,_waku_rln__WEBPACK_IMPORTED_MODULE_0__.extractMetaMaskSigner)();\n } catch (err) {\n onStatusChange(`Failed to access MetaMask: ${err}`, \"error\");\n throw Error(err);\n }\n\n try {\n onStatusChange(\"Connecting to Ethereum...\");\n await rln.start({ signer });\n } catch (err) {\n onStatusChange(`Failed to connect to Ethereum: ${err}`, \"error\");\n throw Error(err);\n }\n\n onStatusChange(\"RLN started\", \"success\");\n };\n\n return {\n rln,\n connectWallet,\n };\n}\n\n\n//# sourceURL=webpack://rln-chat/./src/rln.js?"); - -/***/ }), - -/***/ "./src/ui.js": -/*!*******************!*\ - !*** ./src/ui.js ***! - \*******************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initUI: () => (/* binding */ initUI)\n/* harmony export */ });\nconst status = document.getElementById(\"status\");\nconst chat = document.getElementById(\"chat-area\");\nconst messages = document.getElementById(\"messages\");\n\nconst nickInput = document.getElementById(\"nick\");\nconst textInput = document.getElementById(\"text\");\nconst sendButton = document.getElementById(\"send\");\n\nconst connectWalletButton = document.getElementById(\"connect\");\n\nconst initUI = () => {\n const onStatusChange = (newStatus, className) => {\n status.innerText = newStatus;\n status.className = className || \"progress\";\n };\n\n const onLoaded = () => {\n chat.style.display = \"block\";\n };\n\n const _renderMessage = (nick, text, time, validation) => {\n messages.innerHTML += `\n
  • \n (${nick})(${validation})\n ${text}\n [${new Date(time).toISOString()}]\n
  • \n `;\n };\n\n const registerEvents = (events) => {\n connectWalletButton.addEventListener(\"click\", async () => {\n await events.connectWallet();\n await events.onInitWaku();\n\n onLoaded();\n\n events.onSubscribe((nick, text, time, validation) => {\n _renderMessage(nick, text, time, validation);\n });\n \n sendButton.addEventListener(\"click\", async () => {\n const nick = nickInput.value;\n const text = textInput.value;\n \n if (!nick || !text) {\n console.log(\"Not sending message: missing nick or text.\");\n return;\n }\n \n await events.onSend(nick, text);\n textInput.value = \"\";\n });\n });\n };\n\n return {\n registerEvents,\n onStatusChange,\n };\n};\n\n\n//# sourceURL=webpack://rln-chat/./src/ui.js?"); - -/***/ }), - -/***/ "./src/waku.js": -/*!*********************!*\ - !*** ./src/waku.js ***! - \*********************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ initWaku: () => (/* binding */ initWaku)\n/* harmony export */ });\n/* harmony import */ var _waku_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/sdk */ \"./node_modules/@waku/sdk/dist/index.js\");\n/* harmony import */ var _const__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./const */ \"./src/const.js\");\n\n\n\n\nasync function initWaku({ rln, onStatusChange }) {\n let node;\n let encoder, decoder;\n let subscription;\n\n const onInitWaku = async () => {\n encoder = await rln.createEncoder({\n ephemeral: false,\n contentTopic: _const__WEBPACK_IMPORTED_MODULE_1__.CONTENT_TOPIC,\n credentials: {\n keystore: _const__WEBPACK_IMPORTED_MODULE_1__.KEYSTORE,\n id: _const__WEBPACK_IMPORTED_MODULE_1__.MEMBERSHIP_HASH,\n password: _const__WEBPACK_IMPORTED_MODULE_1__.MEMBERSHIP_PASSWORD,\n },\n });\n decoder = rln.createDecoder(_const__WEBPACK_IMPORTED_MODULE_1__.CONTENT_TOPIC);\n \n onStatusChange(\"Initializing Waku...\");\n node = await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.createLightNode)({\n defaultBootstrap: true,\n });\n onStatusChange(\"Waiting for peers\");\n await node.start();\n await (0,_waku_sdk__WEBPACK_IMPORTED_MODULE_0__.waitForRemotePeer)(node);\n };\n\n const onSend = async (nick, text) => {\n const timestamp = new Date();\n const msg = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.create({\n text,\n nick,\n timestamp: Math.floor(timestamp.valueOf() / 1000),\n });\n const payload = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.encode(msg).finish();\n console.log(\"Sending message with proof...\");\n\n const res = await node.lightPush.send(encoder, { payload, timestamp });\n console.log(\"Message sent:\", res);\n };\n\n const onSubscribe = async (cb) => {\n onStatusChange(\"Subscribing to content topic...\");\n subscription = await node.filter.createSubscription();\n\n await subscription.subscribe(decoder, (message) => {\n try {\n const { timestamp, nick, text } = _const__WEBPACK_IMPORTED_MODULE_1__.ProtoChatMessage.decode(\n message.payload\n );\n\n let proofStatus = \"no proof\";\n if (message.rateLimitProof) {\n console.log(\"Proof received: \", message.rateLimitProof);\n\n try {\n console.time(\"Proof verification took:\");\n const res = message.verify(rln.contract.roots());\n console.timeEnd(\"Proof verification took:\");\n proofStatus = res ? \"verified\" : \"not verified\";\n } catch (error) {\n proofStatus = \"invalid\";\n console.error(\"Failed to verify proof: \", error);\n }\n }\n\n console.log({\n nick,\n text,\n proofStatus,\n time: new Date(timestamp).toDateString(),\n });\n cb(nick, text, timestamp, proofStatus);\n } catch (error) {\n console.error(\"Failed in subscription listener: \", error);\n }\n });\n\n onStatusChange(\"Waku initialized\", \"success\");\n };\n\n return {\n onSend,\n onSubscribe,\n onInitWaku,\n };\n}\n\n\n//# sourceURL=webpack://rln-chat/./src/waku.js?"); +eval("var indexOf = function (xs, item) {\n if (xs.indexOf) return xs.indexOf(item);\n else for (var i = 0; i < xs.length; i++) {\n if (xs[i] === item) return i;\n }\n return -1;\n};\nvar Object_keys = function (obj) {\n if (Object.keys) return Object.keys(obj)\n else {\n var res = [];\n for (var key in obj) res.push(key)\n return res;\n }\n};\n\nvar forEach = function (xs, fn) {\n if (xs.forEach) return xs.forEach(fn)\n else for (var i = 0; i < xs.length; i++) {\n fn(xs[i], i, xs);\n }\n};\n\nvar defineProp = (function() {\n try {\n Object.defineProperty({}, '_', {});\n return function(obj, name, value) {\n Object.defineProperty(obj, name, {\n writable: true,\n enumerable: false,\n configurable: true,\n value: value\n })\n };\n } catch(e) {\n return function(obj, name, value) {\n obj[name] = value;\n };\n }\n}());\n\nvar globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',\n'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',\n'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',\n'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',\n'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];\n\nfunction Context() {}\nContext.prototype = {};\n\nvar Script = exports.Script = function NodeScript (code) {\n if (!(this instanceof Script)) return new Script(code);\n this.code = code;\n};\n\nScript.prototype.runInContext = function (context) {\n if (!(context instanceof Context)) {\n throw new TypeError(\"needs a 'context' argument.\");\n }\n \n var iframe = document.createElement('iframe');\n if (!iframe.style) iframe.style = {};\n iframe.style.display = 'none';\n \n document.body.appendChild(iframe);\n \n var win = iframe.contentWindow;\n var wEval = win.eval, wExecScript = win.execScript;\n\n if (!wEval && wExecScript) {\n // win.eval() magically appears when this is called in IE:\n wExecScript.call(win, 'null');\n wEval = win.eval;\n }\n \n forEach(Object_keys(context), function (key) {\n win[key] = context[key];\n });\n forEach(globals, function (key) {\n if (context[key]) {\n win[key] = context[key];\n }\n });\n \n var winKeys = Object_keys(win);\n\n var res = wEval.call(win, this.code);\n \n forEach(Object_keys(win), function (key) {\n // Avoid copying circular objects like `top` and `window` by only\n // updating existing context properties or new properties in the `win`\n // that was only introduced after the eval.\n if (key in context || indexOf(winKeys, key) === -1) {\n context[key] = win[key];\n }\n });\n\n forEach(globals, function (key) {\n if (!(key in context)) {\n defineProp(context, key, win[key]);\n }\n });\n \n document.body.removeChild(iframe);\n \n return res;\n};\n\nScript.prototype.runInThisContext = function () {\n return eval(this.code); // maybe...\n};\n\nScript.prototype.runInNewContext = function (context) {\n var ctx = Script.createContext(context);\n var res = this.runInContext(ctx);\n\n if (context) {\n forEach(Object_keys(ctx), function (key) {\n context[key] = ctx[key];\n });\n }\n\n return res;\n};\n\nforEach(Object_keys(Script.prototype), function (name) {\n exports[name] = Script[name] = function (code) {\n var s = Script(code);\n return s[name].apply(s, [].slice.call(arguments, 1));\n };\n});\n\nexports.isContext = function (context) {\n return context instanceof Context;\n};\n\nexports.createScript = function (code) {\n return exports.Script(code);\n};\n\nexports.createContext = Script.createContext = function (context) {\n var copy = new Context();\n if(typeof context === 'object') {\n forEach(Object_keys(context), function (key) {\n copy[key] = context[key];\n });\n }\n return copy;\n};\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/vm-browserify/index.js?"); /***/ }), @@ -2488,6 +4293,16 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/crypto_(ignored)?"); /***/ }), +/***/ "?d546": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + /***/ "?8131": /*!************************!*\ !*** buffer (ignored) ***! @@ -2498,6 +4313,96 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); /***/ }), +/***/ "?3fc0": +/*!************************!*\ + !*** crypto (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/crypto_(ignored)?"); + +/***/ }), + +/***/ "?8bcc": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?cad2": +/*!**********************!*\ + !*** util (ignored) ***! + \**********************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/util_(ignored)?"); + +/***/ }), + +/***/ "?593c": +/*!**********************!*\ + !*** util (ignored) ***! + \**********************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/util_(ignored)?"); + +/***/ }), + +/***/ "?4068": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?e7e4": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?7bec": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?0aec": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?7d1a": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + /***/ "?b254": /*!************************!*\ !*** crypto (ignored) ***! @@ -2508,6 +4413,36 @@ eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/crypto_(ignored)?"); /***/ }), +/***/ "?fbf1": +/*!************************!*\ + !*** buffer (ignored) ***! + \************************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/buffer_(ignored)?"); + +/***/ }), + +/***/ "?ed1b": +/*!**********************!*\ + !*** util (ignored) ***! + \**********************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/util_(ignored)?"); + +/***/ }), + +/***/ "?d17e": +/*!**********************!*\ + !*** util (ignored) ***! + \**********************/ +/***/ (() => { + +eval("/* (ignored) */\n\n//# sourceURL=webpack://rln-chat/util_(ignored)?"); + +/***/ }), + /***/ "./node_modules/@chainsafe/is-ip/lib/is-ip.js": /*!****************************************************!*\ !*** ./node_modules/@chainsafe/is-ip/lib/is-ip.js ***! @@ -2592,7 +4527,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RPC: () => (/* binding */ RPC)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar RPC;\n(function (RPC) {\n let SubOpts;\n (function (SubOpts) {\n let _codec;\n SubOpts.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscribe != null) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if (obj.topic != null) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n SubOpts.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, SubOpts.codec());\n };\n SubOpts.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, SubOpts.codec(), opts);\n };\n })(SubOpts = RPC.SubOpts || (RPC.SubOpts = {}));\n let Message;\n (function (Message) {\n let _codec;\n Message.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.from != null) {\n w.uint32(10);\n w.bytes(obj.from);\n }\n if (obj.data != null) {\n w.uint32(18);\n w.bytes(obj.data);\n }\n if (obj.seqno != null) {\n w.uint32(26);\n w.bytes(obj.seqno);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(34);\n w.string(obj.topic);\n }\n if (obj.signature != null) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (obj.key != null) {\n w.uint32(50);\n w.bytes(obj.key);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n topic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.from = reader.bytes();\n break;\n }\n case 2: {\n obj.data = reader.bytes();\n break;\n }\n case 3: {\n obj.seqno = reader.bytes();\n break;\n }\n case 4: {\n obj.topic = reader.string();\n break;\n }\n case 5: {\n obj.signature = reader.bytes();\n break;\n }\n case 6: {\n obj.key = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Message.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, Message.codec());\n };\n Message.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, Message.codec(), opts);\n };\n })(Message = RPC.Message || (RPC.Message = {}));\n let ControlMessage;\n (function (ControlMessage) {\n let _codec;\n ControlMessage.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.ihave != null) {\n for (const value of obj.ihave) {\n w.uint32(10);\n RPC.ControlIHave.codec().encode(value, w);\n }\n }\n if (obj.iwant != null) {\n for (const value of obj.iwant) {\n w.uint32(18);\n RPC.ControlIWant.codec().encode(value, w);\n }\n }\n if (obj.graft != null) {\n for (const value of obj.graft) {\n w.uint32(26);\n RPC.ControlGraft.codec().encode(value, w);\n }\n }\n if (obj.prune != null) {\n for (const value of obj.prune) {\n w.uint32(34);\n RPC.ControlPrune.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n ihave: [],\n iwant: [],\n graft: [],\n prune: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.ihave != null && obj.ihave.length === opts.limits.ihave) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"ihave\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.ihave.push(RPC.ControlIHave.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.iwant != null && obj.iwant.length === opts.limits.iwant) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"iwant\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.iwant.push(RPC.ControlIWant.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n if (opts.limits?.graft != null && obj.graft.length === opts.limits.graft) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"graft\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.graft.push(RPC.ControlGraft.codec().decode(reader, reader.uint32()));\n break;\n }\n case 4: {\n if (opts.limits?.prune != null && obj.prune.length === opts.limits.prune) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"prune\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.prune.push(RPC.ControlPrune.codec().decode(reader, reader.uint32()));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlMessage.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlMessage.codec());\n };\n ControlMessage.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlMessage.codec(), opts);\n };\n })(ControlMessage = RPC.ControlMessage || (RPC.ControlMessage = {}));\n let ControlIHave;\n (function (ControlIHave) {\n let _codec;\n ControlIHave.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIHave.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlIHave.codec());\n };\n ControlIHave.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlIHave.codec(), opts);\n };\n })(ControlIHave = RPC.ControlIHave || (RPC.ControlIHave = {}));\n let ControlIWant;\n (function (ControlIWant) {\n let _codec;\n ControlIWant.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIWant.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlIWant.codec());\n };\n ControlIWant.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlIWant.codec(), opts);\n };\n })(ControlIWant = RPC.ControlIWant || (RPC.ControlIWant = {}));\n let ControlGraft;\n (function (ControlGraft) {\n let _codec;\n ControlGraft.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlGraft.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlGraft.codec());\n };\n ControlGraft.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlGraft.codec(), opts);\n };\n })(ControlGraft = RPC.ControlGraft || (RPC.ControlGraft = {}));\n let ControlPrune;\n (function (ControlPrune) {\n let _codec;\n ControlPrune.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.peers != null) {\n for (const value of obj.peers) {\n w.uint32(18);\n RPC.PeerInfo.codec().encode(value, w);\n }\n }\n if (obj.backoff != null) {\n w.uint32(24);\n w.uint64Number(obj.backoff);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peers: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.peers != null && obj.peers.length === opts.limits.peers) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"peers\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.peers.push(RPC.PeerInfo.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.backoff = reader.uint64Number();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlPrune.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlPrune.codec());\n };\n ControlPrune.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlPrune.codec(), opts);\n };\n })(ControlPrune = RPC.ControlPrune || (RPC.ControlPrune = {}));\n let PeerInfo;\n (function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerID != null) {\n w.uint32(10);\n w.bytes(obj.peerID);\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(18);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.peerID = reader.bytes();\n break;\n }\n case 2: {\n obj.signedPeerRecord = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PeerInfo.codec(), opts);\n };\n })(PeerInfo = RPC.PeerInfo || (RPC.PeerInfo = {}));\n let _codec;\n RPC.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscriptions != null) {\n for (const value of obj.subscriptions) {\n w.uint32(10);\n RPC.SubOpts.codec().encode(value, w);\n }\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(18);\n RPC.Message.codec().encode(value, w);\n }\n }\n if (obj.control != null) {\n w.uint32(26);\n RPC.ControlMessage.codec().encode(obj.control, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscriptions: [],\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.subscriptions != null && obj.subscriptions.length === opts.limits.subscriptions) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"subscriptions\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.subscriptions.push(RPC.SubOpts.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messages.push(RPC.Message.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.control = RPC.ControlMessage.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RPC.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, RPC.codec());\n };\n RPC.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, RPC.codec(), opts);\n };\n})(RPC || (RPC = {}));\n//# sourceMappingURL=rpc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/dist/src/message/rpc.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RPC: () => (/* binding */ RPC)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar RPC;\n(function (RPC) {\n let SubOpts;\n (function (SubOpts) {\n let _codec;\n SubOpts.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscribe != null) {\n w.uint32(8);\n w.bool(obj.subscribe);\n }\n if (obj.topic != null) {\n w.uint32(18);\n w.string(obj.topic);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.subscribe = reader.bool();\n break;\n }\n case 2: {\n obj.topic = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n SubOpts.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, SubOpts.codec());\n };\n SubOpts.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, SubOpts.codec(), opts);\n };\n })(SubOpts = RPC.SubOpts || (RPC.SubOpts = {}));\n let Message;\n (function (Message) {\n let _codec;\n Message.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.from != null) {\n w.uint32(10);\n w.bytes(obj.from);\n }\n if (obj.data != null) {\n w.uint32(18);\n w.bytes(obj.data);\n }\n if (obj.seqno != null) {\n w.uint32(26);\n w.bytes(obj.seqno);\n }\n if ((obj.topic != null && obj.topic !== '')) {\n w.uint32(34);\n w.string(obj.topic);\n }\n if (obj.signature != null) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (obj.key != null) {\n w.uint32(50);\n w.bytes(obj.key);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n topic: ''\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.from = reader.bytes();\n break;\n }\n case 2: {\n obj.data = reader.bytes();\n break;\n }\n case 3: {\n obj.seqno = reader.bytes();\n break;\n }\n case 4: {\n obj.topic = reader.string();\n break;\n }\n case 5: {\n obj.signature = reader.bytes();\n break;\n }\n case 6: {\n obj.key = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Message.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, Message.codec());\n };\n Message.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, Message.codec(), opts);\n };\n })(Message = RPC.Message || (RPC.Message = {}));\n let ControlMessage;\n (function (ControlMessage) {\n let _codec;\n ControlMessage.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.ihave != null) {\n for (const value of obj.ihave) {\n w.uint32(10);\n RPC.ControlIHave.codec().encode(value, w);\n }\n }\n if (obj.iwant != null) {\n for (const value of obj.iwant) {\n w.uint32(18);\n RPC.ControlIWant.codec().encode(value, w);\n }\n }\n if (obj.graft != null) {\n for (const value of obj.graft) {\n w.uint32(26);\n RPC.ControlGraft.codec().encode(value, w);\n }\n }\n if (obj.prune != null) {\n for (const value of obj.prune) {\n w.uint32(34);\n RPC.ControlPrune.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n ihave: [],\n iwant: [],\n graft: [],\n prune: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.ihave != null && obj.ihave.length === opts.limits.ihave) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"ihave\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.ihave.push(RPC.ControlIHave.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.iwant != null && obj.iwant.length === opts.limits.iwant) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"iwant\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.iwant.push(RPC.ControlIWant.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n if (opts.limits?.graft != null && obj.graft.length === opts.limits.graft) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"graft\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.graft.push(RPC.ControlGraft.codec().decode(reader, reader.uint32()));\n break;\n }\n case 4: {\n if (opts.limits?.prune != null && obj.prune.length === opts.limits.prune) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"prune\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.prune.push(RPC.ControlPrune.codec().decode(reader, reader.uint32()));\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlMessage.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlMessage.codec());\n };\n ControlMessage.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlMessage.codec(), opts);\n };\n })(ControlMessage = RPC.ControlMessage || (RPC.ControlMessage = {}));\n let ControlIHave;\n (function (ControlIHave) {\n let _codec;\n ControlIHave.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(18);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIHave.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlIHave.codec());\n };\n ControlIHave.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlIHave.codec(), opts);\n };\n })(ControlIHave = RPC.ControlIHave || (RPC.ControlIHave = {}));\n let ControlIWant;\n (function (ControlIWant) {\n let _codec;\n ControlIWant.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.messageIDs != null) {\n for (const value of obj.messageIDs) {\n w.uint32(10);\n w.bytes(value);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n messageIDs: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.messageIDs != null && obj.messageIDs.length === opts.limits.messageIDs) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messageIDs\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messageIDs.push(reader.bytes());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlIWant.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlIWant.codec());\n };\n ControlIWant.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlIWant.codec(), opts);\n };\n })(ControlIWant = RPC.ControlIWant || (RPC.ControlIWant = {}));\n let ControlGraft;\n (function (ControlGraft) {\n let _codec;\n ControlGraft.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlGraft.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlGraft.codec());\n };\n ControlGraft.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlGraft.codec(), opts);\n };\n })(ControlGraft = RPC.ControlGraft || (RPC.ControlGraft = {}));\n let ControlPrune;\n (function (ControlPrune) {\n let _codec;\n ControlPrune.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.topicID != null) {\n w.uint32(10);\n w.string(obj.topicID);\n }\n if (obj.peers != null) {\n for (const value of obj.peers) {\n w.uint32(18);\n RPC.PeerInfo.codec().encode(value, w);\n }\n }\n if (obj.backoff != null) {\n w.uint32(24);\n w.uint64Number(obj.backoff);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n peers: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.topicID = reader.string();\n break;\n }\n case 2: {\n if (opts.limits?.peers != null && obj.peers.length === opts.limits.peers) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"peers\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.peers.push(RPC.PeerInfo.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.backoff = reader.uint64Number();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n ControlPrune.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, ControlPrune.codec());\n };\n ControlPrune.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, ControlPrune.codec(), opts);\n };\n })(ControlPrune = RPC.ControlPrune || (RPC.ControlPrune = {}));\n let PeerInfo;\n (function (PeerInfo) {\n let _codec;\n PeerInfo.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.peerID != null) {\n w.uint32(10);\n w.bytes(obj.peerID);\n }\n if (obj.signedPeerRecord != null) {\n w.uint32(18);\n w.bytes(obj.signedPeerRecord);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n obj.peerID = reader.bytes();\n break;\n }\n case 2: {\n obj.signedPeerRecord = reader.bytes();\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerInfo.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PeerInfo.codec());\n };\n PeerInfo.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PeerInfo.codec(), opts);\n };\n })(PeerInfo = RPC.PeerInfo || (RPC.PeerInfo = {}));\n let _codec;\n RPC.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.subscriptions != null) {\n for (const value of obj.subscriptions) {\n w.uint32(10);\n RPC.SubOpts.codec().encode(value, w);\n }\n }\n if (obj.messages != null) {\n for (const value of obj.messages) {\n w.uint32(18);\n RPC.Message.codec().encode(value, w);\n }\n }\n if (obj.control != null) {\n w.uint32(26);\n RPC.ControlMessage.codec().encode(obj.control, w);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length, opts = {}) => {\n const obj = {\n subscriptions: [],\n messages: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (opts.limits?.subscriptions != null && obj.subscriptions.length === opts.limits.subscriptions) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"subscriptions\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.subscriptions.push(RPC.SubOpts.codec().decode(reader, reader.uint32()));\n break;\n }\n case 2: {\n if (opts.limits?.messages != null && obj.messages.length === opts.limits.messages) {\n throw new protons_runtime__WEBPACK_IMPORTED_MODULE_0__.CodeError('decode error - map field \"messages\" had too many elements', 'ERR_MAX_LENGTH');\n }\n obj.messages.push(RPC.Message.codec().decode(reader, reader.uint32()));\n break;\n }\n case 3: {\n obj.control = RPC.ControlMessage.codec().decode(reader, reader.uint32());\n break;\n }\n default: {\n reader.skipType(tag & 7);\n break;\n }\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n RPC.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, RPC.codec());\n };\n RPC.decode = (buf, opts) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, RPC.codec(), opts);\n };\n})(RPC || (RPC = {}));\n//# sourceMappingURL=rpc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/dist/src/message/rpc.js?"); /***/ }), @@ -2922,7 +4857,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); /***/ }), @@ -2944,7 +4879,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KeyType: () => (/* binding */ KeyType),\n/* harmony export */ PrivateKey: () => (/* binding */ PrivateKey),\n/* harmony export */ PublicKey: () => (/* binding */ PublicKey)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.enumeration)(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nvar PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nvar PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/keys.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KeyType: () => (/* binding */ KeyType),\n/* harmony export */ PrivateKey: () => (/* binding */ PrivateKey),\n/* harmony export */ PublicKey: () => (/* binding */ PublicKey)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.enumeration)(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nvar PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nvar PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/keys/keys.js?"); /***/ }), @@ -3032,7 +4967,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); /***/ }), @@ -3054,7 +4989,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n detail;\n constructor(message, data) {\n super(message, data);\n // @ts-expect-error could be undefined\n this.detail = data?.detail;\n }\n}\nconst CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/event-target.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/event-target.js?"); /***/ }), @@ -3109,7 +5044,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/peer-id/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -3120,7 +5055,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -3164,7 +5099,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -3285,7 +5220,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -3329,7 +5264,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -3443,6 +5378,138 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codec.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codec.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CODEC_TYPES: () => (/* binding */ CODEC_TYPES),\n/* harmony export */ createCodec: () => (/* binding */ createCodec)\n/* harmony export */ });\n// https://developers.google.com/protocol-buffers/docs/encoding#structure\nvar CODEC_TYPES;\n(function (CODEC_TYPES) {\n CODEC_TYPES[CODEC_TYPES[\"VARINT\"] = 0] = \"VARINT\";\n CODEC_TYPES[CODEC_TYPES[\"BIT64\"] = 1] = \"BIT64\";\n CODEC_TYPES[CODEC_TYPES[\"LENGTH_DELIMITED\"] = 2] = \"LENGTH_DELIMITED\";\n CODEC_TYPES[CODEC_TYPES[\"START_GROUP\"] = 3] = \"START_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"END_GROUP\"] = 4] = \"END_GROUP\";\n CODEC_TYPES[CODEC_TYPES[\"BIT32\"] = 5] = \"BIT32\";\n})(CODEC_TYPES || (CODEC_TYPES = {}));\nfunction createCodec(name, type, encode, decode) {\n return {\n name,\n type,\n encode,\n decode\n };\n}\n//# sourceMappingURL=codec.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codec.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/enum.js": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/enum.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ enumeration: () => (/* binding */ enumeration)\n/* harmony export */ });\n/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../codec.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codec.js\");\n\nfunction enumeration(v) {\n function findValue(val) {\n // Use the reverse mapping to look up the enum key for the stored value\n // https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings\n if (v[val.toString()] == null) {\n throw new Error('Invalid enum value');\n }\n return v[val];\n }\n const encode = function enumEncode(val, writer) {\n const enumValue = findValue(val);\n writer.int32(enumValue);\n };\n const decode = function enumDecode(reader) {\n const val = reader.int32();\n return findValue(val);\n };\n // @ts-expect-error yeah yeah\n return (0,_codec_js__WEBPACK_IMPORTED_MODULE_0__.createCodec)('enum', _codec_js__WEBPACK_IMPORTED_MODULE_0__.CODEC_TYPES.VARINT, encode, decode);\n}\n//# sourceMappingURL=enum.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/enum.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/message.js": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/message.js ***! + \**********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ message: () => (/* binding */ message)\n/* harmony export */ });\n/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../codec.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codec.js\");\n\nfunction message(encode, decode) {\n return (0,_codec_js__WEBPACK_IMPORTED_MODULE_0__.createCodec)('message', _codec_js__WEBPACK_IMPORTED_MODULE_0__.CODEC_TYPES.LENGTH_DELIMITED, encode, decode);\n}\n//# sourceMappingURL=message.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/message.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/decode.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/decode.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decodeMessage: () => (/* binding */ decodeMessage)\n/* harmony export */ });\n/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/reader.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/reader.js\");\n\nfunction decodeMessage(buf, codec, opts) {\n const reader = (0,_utils_reader_js__WEBPACK_IMPORTED_MODULE_0__.createReader)(buf);\n return codec.decode(reader, undefined, opts);\n}\n//# sourceMappingURL=decode.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/decode.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/encode.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/encode.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ encodeMessage: () => (/* binding */ encodeMessage)\n/* harmony export */ });\n/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/writer.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/writer.js\");\n\nfunction encodeMessage(message, codec) {\n const w = (0,_utils_writer_js__WEBPACK_IMPORTED_MODULE_0__.createWriter)();\n codec.encode(message, w, {\n lengthDelimited: false\n });\n return w.finish();\n}\n//# sourceMappingURL=encode.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/encode.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/index.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/index.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ decodeMessage: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_0__.decodeMessage),\n/* harmony export */ encodeMessage: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_1__.encodeMessage),\n/* harmony export */ enumeration: () => (/* reexport safe */ _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__.enumeration),\n/* harmony export */ message: () => (/* reexport safe */ _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__.message),\n/* harmony export */ reader: () => (/* reexport safe */ _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__.createReader),\n/* harmony export */ writer: () => (/* reexport safe */ _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__.createWriter)\n/* harmony export */ });\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/decode.js\");\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/encode.js\");\n/* harmony import */ var _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/enum.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/enum.js\");\n/* harmony import */ var _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./codecs/message.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/codecs/message.js\");\n/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/reader.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/reader.js\");\n/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/writer.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/writer.js\");\n/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\n\n\n\n\n\nclass CodeError extends Error {\n code;\n constructor(message, code, options) {\n super(message, options);\n this.code = code;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/float.js": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/float.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ readDoubleBE: () => (/* binding */ readDoubleBE),\n/* harmony export */ readDoubleLE: () => (/* binding */ readDoubleLE),\n/* harmony export */ readFloatBE: () => (/* binding */ readFloatBE),\n/* harmony export */ readFloatLE: () => (/* binding */ readFloatLE),\n/* harmony export */ writeDoubleBE: () => (/* binding */ writeDoubleBE),\n/* harmony export */ writeDoubleLE: () => (/* binding */ writeDoubleLE),\n/* harmony export */ writeFloatBE: () => (/* binding */ writeFloatBE),\n/* harmony export */ writeFloatLE: () => (/* binding */ writeFloatLE)\n/* harmony export */ });\nconst f32 = new Float32Array([-0]);\nconst f8b = new Uint8Array(f32.buffer);\n/**\n * Writes a 32 bit float to a buffer using little endian byte order\n */\nfunction writeFloatLE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[0];\n buf[pos + 1] = f8b[1];\n buf[pos + 2] = f8b[2];\n buf[pos + 3] = f8b[3];\n}\n/**\n * Writes a 32 bit float to a buffer using big endian byte order\n */\nfunction writeFloatBE(val, buf, pos) {\n f32[0] = val;\n buf[pos] = f8b[3];\n buf[pos + 1] = f8b[2];\n buf[pos + 2] = f8b[1];\n buf[pos + 3] = f8b[0];\n}\n/**\n * Reads a 32 bit float from a buffer using little endian byte order\n */\nfunction readFloatLE(buf, pos) {\n f8b[0] = buf[pos];\n f8b[1] = buf[pos + 1];\n f8b[2] = buf[pos + 2];\n f8b[3] = buf[pos + 3];\n return f32[0];\n}\n/**\n * Reads a 32 bit float from a buffer using big endian byte order\n */\nfunction readFloatBE(buf, pos) {\n f8b[3] = buf[pos];\n f8b[2] = buf[pos + 1];\n f8b[1] = buf[pos + 2];\n f8b[0] = buf[pos + 3];\n return f32[0];\n}\nconst f64 = new Float64Array([-0]);\nconst d8b = new Uint8Array(f64.buffer);\n/**\n * Writes a 64 bit double to a buffer using little endian byte order\n */\nfunction writeDoubleLE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[0];\n buf[pos + 1] = d8b[1];\n buf[pos + 2] = d8b[2];\n buf[pos + 3] = d8b[3];\n buf[pos + 4] = d8b[4];\n buf[pos + 5] = d8b[5];\n buf[pos + 6] = d8b[6];\n buf[pos + 7] = d8b[7];\n}\n/**\n * Writes a 64 bit double to a buffer using big endian byte order\n */\nfunction writeDoubleBE(val, buf, pos) {\n f64[0] = val;\n buf[pos] = d8b[7];\n buf[pos + 1] = d8b[6];\n buf[pos + 2] = d8b[5];\n buf[pos + 3] = d8b[4];\n buf[pos + 4] = d8b[3];\n buf[pos + 5] = d8b[2];\n buf[pos + 6] = d8b[1];\n buf[pos + 7] = d8b[0];\n}\n/**\n * Reads a 64 bit double from a buffer using little endian byte order\n */\nfunction readDoubleLE(buf, pos) {\n d8b[0] = buf[pos];\n d8b[1] = buf[pos + 1];\n d8b[2] = buf[pos + 2];\n d8b[3] = buf[pos + 3];\n d8b[4] = buf[pos + 4];\n d8b[5] = buf[pos + 5];\n d8b[6] = buf[pos + 6];\n d8b[7] = buf[pos + 7];\n return f64[0];\n}\n/**\n * Reads a 64 bit double from a buffer using big endian byte order\n */\nfunction readDoubleBE(buf, pos) {\n d8b[7] = buf[pos];\n d8b[6] = buf[pos + 1];\n d8b[5] = buf[pos + 2];\n d8b[4] = buf[pos + 3];\n d8b[3] = buf[pos + 4];\n d8b[2] = buf[pos + 5];\n d8b[1] = buf[pos + 6];\n d8b[0] = buf[pos + 7];\n return f64[0];\n}\n//# sourceMappingURL=float.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/float.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/longbits.js": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/longbits.js ***! + \**********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ LongBits: () => (/* binding */ LongBits)\n/* harmony export */ });\n// the largest BigInt we can safely downcast to a Number\nconst MAX_SAFE_NUMBER_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);\nconst MIN_SAFE_NUMBER_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);\n/**\n * Constructs new long bits.\n *\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @function Object() { [native code] }\n * @param {number} lo - Low 32 bits, unsigned\n * @param {number} hi - High 32 bits, unsigned\n */\nclass LongBits {\n lo;\n hi;\n constructor(lo, hi) {\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n /**\n * Low bits\n */\n this.lo = lo | 0;\n /**\n * High bits\n */\n this.hi = hi | 0;\n }\n /**\n * Converts this long bits to a possibly unsafe JavaScript number\n */\n toNumber(unsigned = false) {\n if (!unsigned && (this.hi >>> 31) > 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n }\n /**\n * Converts this long bits to a bigint\n */\n toBigInt(unsigned = false) {\n if (unsigned) {\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n if ((this.hi >>> 31) !== 0) {\n const lo = ~this.lo + 1 >>> 0;\n let hi = ~this.hi >>> 0;\n if (lo === 0) {\n hi = hi + 1 >>> 0;\n }\n return -(BigInt(lo) + (BigInt(hi) << 32n));\n }\n return BigInt(this.lo >>> 0) + (BigInt(this.hi >>> 0) << 32n);\n }\n /**\n * Converts this long bits to a string\n */\n toString(unsigned = false) {\n return this.toBigInt(unsigned).toString();\n }\n /**\n * Zig-zag encodes this long bits\n */\n zzEncode() {\n const mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = (this.lo << 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Zig-zag decodes this long bits\n */\n zzDecode() {\n const mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = (this.hi >>> 1 ^ mask) >>> 0;\n return this;\n }\n /**\n * Calculates the length of this longbits when encoded as a varint.\n */\n length() {\n const part0 = this.lo;\n const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0;\n const part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromBigInt(value) {\n if (value === 0n) {\n return zero;\n }\n if (value < MAX_SAFE_NUMBER_INTEGER && value > MIN_SAFE_NUMBER_INTEGER) {\n return this.fromNumber(Number(value));\n }\n const negative = value < 0n;\n if (negative) {\n value = -value;\n }\n let hi = value >> 32n;\n let lo = value - (hi << 32n);\n if (negative) {\n hi = ~hi | 0n;\n lo = ~lo | 0n;\n if (++lo > TWO_32) {\n lo = 0n;\n if (++hi > TWO_32) {\n hi = 0n;\n }\n }\n }\n return new LongBits(Number(lo), Number(hi));\n }\n /**\n * Constructs new long bits from the specified number\n */\n static fromNumber(value) {\n if (value === 0) {\n return zero;\n }\n const sign = value < 0;\n if (sign) {\n value = -value;\n }\n let lo = value >>> 0;\n let hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295) {\n hi = 0;\n }\n }\n }\n return new LongBits(lo, hi);\n }\n /**\n * Constructs new long bits from a number, long or string\n */\n static from(value) {\n if (typeof value === 'number') {\n return LongBits.fromNumber(value);\n }\n if (typeof value === 'bigint') {\n return LongBits.fromBigInt(value);\n }\n if (typeof value === 'string') {\n return LongBits.fromBigInt(BigInt(value));\n }\n return value.low != null || value.high != null ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n }\n}\nconst zero = new LongBits(0, 0);\nzero.toBigInt = function () { return 0n; };\nzero.zzEncode = zero.zzDecode = function () { return this; };\nzero.length = function () { return 1; };\nconst TWO_32 = 4294967296n;\n//# sourceMappingURL=longbits.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/longbits.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/pool.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/pool.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ pool)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/alloc */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/alloc.js\");\n\n/**\n * A general purpose buffer pool\n */\nfunction pool(size) {\n const SIZE = size ?? 8192;\n const MAX = SIZE >>> 1;\n let slab;\n let offset = SIZE;\n return function poolAlloc(size) {\n if (size < 1 || size > MAX) {\n return (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(size);\n }\n if (offset + size > SIZE) {\n slab = (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(SIZE);\n offset = 0;\n }\n const buf = slab.subarray(offset, offset += size);\n if ((offset & 7) !== 0) {\n // align to 32 bit\n offset = (offset | 7) + 1;\n }\n return buf;\n };\n}\n//# sourceMappingURL=pool.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/pool.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/reader.js": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/reader.js ***! + \********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Uint8ArrayReader: () => (/* binding */ Uint8ArrayReader),\n/* harmony export */ createReader: () => (/* binding */ createReader)\n/* harmony export */ });\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var _float_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./float.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/float.js\");\n/* harmony import */ var _longbits_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./longbits.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/longbits.js\");\n/* harmony import */ var _utf8_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utf8.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/utf8.js\");\n\n\n\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(`index out of range: ${reader.pos} + ${writeLength ?? 1} > ${reader.len}`);\n}\nfunction readFixed32End(buf, end) {\n return (buf[end - 4] |\n buf[end - 3] << 8 |\n buf[end - 2] << 16 |\n buf[end - 1] << 24) >>> 0;\n}\n/**\n * Constructs a new reader instance using the specified buffer.\n */\nclass Uint8ArrayReader {\n buf;\n pos;\n len;\n _slice = Uint8Array.prototype.subarray;\n constructor(buffer) {\n /**\n * Read buffer\n */\n this.buf = buffer;\n /**\n * Read buffer position\n */\n this.pos = 0;\n /**\n * Read buffer length\n */\n this.len = buffer.length;\n }\n /**\n * Reads a varint as an unsigned 32 bit value\n */\n uint32() {\n let value = 4294967295;\n value = (this.buf[this.pos] & 127) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0;\n if (this.buf[this.pos++] < 128)\n return value;\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n }\n /**\n * Reads a varint as a signed 32 bit value\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Reads a zig-zag encoded varint as a signed 32 bit value\n */\n sint32() {\n const value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n }\n /**\n * Reads a varint as a boolean\n */\n bool() {\n return this.uint32() !== 0;\n }\n /**\n * Reads fixed 32 bits as an unsigned 32 bit integer\n */\n fixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4);\n return res;\n }\n /**\n * Reads fixed 32 bits as a signed 32 bit integer\n */\n sfixed32() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const res = readFixed32End(this.buf, this.pos += 4) | 0;\n return res;\n }\n /**\n * Reads a float (32 bit) as a number\n */\n float() {\n if (this.pos + 4 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = (0,_float_js__WEBPACK_IMPORTED_MODULE_1__.readFloatLE)(this.buf, this.pos);\n this.pos += 4;\n return value;\n }\n /**\n * Reads a double (64 bit float) as a number\n */\n double() {\n /* istanbul ignore if */\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 4);\n }\n const value = (0,_float_js__WEBPACK_IMPORTED_MODULE_1__.readDoubleLE)(this.buf, this.pos);\n this.pos += 8;\n return value;\n }\n /**\n * Reads a sequence of bytes preceded by its length as a varint\n */\n bytes() {\n const length = this.uint32();\n const start = this.pos;\n const end = this.pos + length;\n /* istanbul ignore if */\n if (end > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\n ? new Uint8Array(0)\n : this.buf.subarray(start, end);\n }\n /**\n * Reads a string preceded by its byte length as a varint\n */\n string() {\n const bytes = this.bytes();\n return _utf8_js__WEBPACK_IMPORTED_MODULE_3__.read(bytes, 0, bytes.length);\n }\n /**\n * Skips the specified number of bytes if specified, otherwise skips a varint\n */\n skip(length) {\n if (typeof length === 'number') {\n /* istanbul ignore if */\n if (this.pos + length > this.len) {\n throw indexOutOfRange(this, length);\n }\n this.pos += length;\n }\n else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n } while ((this.buf[this.pos++] & 128) !== 0);\n }\n return this;\n }\n /**\n * Skips the next element of the specified wire type\n */\n skipType(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n /* istanbul ignore next */\n default:\n throw Error(`invalid wire type ${wireType} at offset ${this.pos}`);\n }\n return this;\n }\n readLongVarint() {\n // tends to deopt with local vars for octet etc.\n const bits = new _longbits_js__WEBPACK_IMPORTED_MODULE_2__.LongBits(0, 0);\n let i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n i = 0;\n }\n else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n else {\n for (; i < 5; ++i) {\n if (this.pos >= this.len) {\n throw indexOutOfRange(this);\n }\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128) {\n return bits;\n }\n }\n }\n throw Error('invalid varint encoding');\n }\n readFixed64() {\n if (this.pos + 8 > this.len) {\n throw indexOutOfRange(this, 8);\n }\n const lo = readFixed32End(this.buf, this.pos += 4);\n const hi = readFixed32End(this.buf, this.pos += 4);\n return new _longbits_js__WEBPACK_IMPORTED_MODULE_2__.LongBits(lo, hi);\n }\n /**\n * Reads a varint as a signed 64 bit value\n */\n int64() {\n return this.readLongVarint().toBigInt();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n int64Number() {\n return this.readLongVarint().toNumber();\n }\n /**\n * Reads a varint as a signed 64 bit value returned as a string\n */\n int64String() {\n return this.readLongVarint().toString();\n }\n /**\n * Reads a varint as an unsigned 64 bit value\n */\n uint64() {\n return this.readLongVarint().toBigInt(true);\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a possibly unsafe\n * JavaScript number\n */\n uint64Number() {\n const value = (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.decodeUint8Array)(this.buf, this.pos);\n this.pos += (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodingLength)(value);\n return value;\n }\n /**\n * Reads a varint as an unsigned 64 bit value returned as a string\n */\n uint64String() {\n return this.readLongVarint().toString(true);\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value\n */\n sint64() {\n return this.readLongVarint().zzDecode().toBigInt();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * possibly unsafe JavaScript number\n */\n sint64Number() {\n return this.readLongVarint().zzDecode().toNumber();\n }\n /**\n * Reads a zig-zag encoded varint as a signed 64 bit value returned as a\n * string\n */\n sint64String() {\n return this.readLongVarint().zzDecode().toString();\n }\n /**\n * Reads fixed 64 bits\n */\n fixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads fixed 64 bits returned as a possibly unsafe JavaScript number\n */\n fixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads fixed 64 bits returned as a string\n */\n fixed64String() {\n return this.readFixed64().toString();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits\n */\n sfixed64() {\n return this.readFixed64().toBigInt();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a possibly unsafe\n * JavaScript number\n */\n sfixed64Number() {\n return this.readFixed64().toNumber();\n }\n /**\n * Reads zig-zag encoded fixed 64 bits returned as a string\n */\n sfixed64String() {\n return this.readFixed64().toString();\n }\n}\nfunction createReader(buf) {\n return new Uint8ArrayReader(buf instanceof Uint8Array ? buf : buf.subarray());\n}\n//# sourceMappingURL=reader.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/reader.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/utf8.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/utf8.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ length: () => (/* binding */ length),\n/* harmony export */ read: () => (/* binding */ read),\n/* harmony export */ write: () => (/* binding */ write)\n/* harmony export */ });\n/**\n * Calculates the UTF8 byte length of a string\n */\nfunction length(string) {\n let len = 0;\n let c = 0;\n for (let i = 0; i < string.length; ++i) {\n c = string.charCodeAt(i);\n if (c < 128) {\n len += 1;\n }\n else if (c < 2048) {\n len += 2;\n }\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\n ++i;\n len += 4;\n }\n else {\n len += 3;\n }\n }\n return len;\n}\n/**\n * Reads UTF8 bytes as a string\n */\nfunction read(buffer, start, end) {\n const len = end - start;\n if (len < 1) {\n return '';\n }\n let parts;\n const chunk = [];\n let i = 0; // char offset\n let t; // temporary\n while (start < end) {\n t = buffer[start++];\n if (t < 128) {\n chunk[i++] = t;\n }\n else if (t > 191 && t < 224) {\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\n }\n else if (t > 239 && t < 365) {\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\n chunk[i++] = 0xD800 + (t >> 10);\n chunk[i++] = 0xDC00 + (t & 1023);\n }\n else {\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\n }\n if (i > 8191) {\n (parts ?? (parts = [])).push(String.fromCharCode.apply(String, chunk));\n i = 0;\n }\n }\n if (parts != null) {\n if (i > 0) {\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\n }\n return parts.join('');\n }\n return String.fromCharCode.apply(String, chunk.slice(0, i));\n}\n/**\n * Writes a string as UTF8 bytes\n */\nfunction write(string, buffer, offset) {\n const start = offset;\n let c1; // character 1\n let c2; // character 2\n for (let i = 0; i < string.length; ++i) {\n c1 = string.charCodeAt(i);\n if (c1 < 128) {\n buffer[offset++] = c1;\n }\n else if (c1 < 2048) {\n buffer[offset++] = c1 >> 6 | 192;\n buffer[offset++] = c1 & 63 | 128;\n }\n else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\n ++i;\n buffer[offset++] = c1 >> 18 | 240;\n buffer[offset++] = c1 >> 12 & 63 | 128;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n else {\n buffer[offset++] = c1 >> 12 | 224;\n buffer[offset++] = c1 >> 6 & 63 | 128;\n buffer[offset++] = c1 & 63 | 128;\n }\n }\n return offset - start;\n}\n//# sourceMappingURL=utf8.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/utf8.js?"); + +/***/ }), + +/***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/writer.js": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/writer.js ***! + \********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createWriter: () => (/* binding */ createWriter)\n/* harmony export */ });\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/alloc */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _float_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./float.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/float.js\");\n/* harmony import */ var _longbits_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./longbits.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/longbits.js\");\n/* harmony import */ var _pool_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pool.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/pool.js\");\n/* harmony import */ var _utf8_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utf8.js */ \"./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/utf8.js\");\n\n\n\n\n\n\n\n/**\n * Constructs a new writer operation instance.\n *\n * @classdesc Scheduled writer operation\n */\nclass Op {\n /**\n * Function to call\n */\n fn;\n /**\n * Value byte length\n */\n len;\n /**\n * Next operation\n */\n next;\n /**\n * Value to write\n */\n val;\n constructor(fn, len, val) {\n this.fn = fn;\n this.len = len;\n this.next = undefined;\n this.val = val; // type varies\n }\n}\n/* istanbul ignore next */\nfunction noop() { } // eslint-disable-line no-empty-function\n/**\n * Constructs a new writer state instance\n */\nclass State {\n /**\n * Current head\n */\n head;\n /**\n * Current tail\n */\n tail;\n /**\n * Current buffer length\n */\n len;\n /**\n * Next state\n */\n next;\n constructor(writer) {\n this.head = writer.head;\n this.tail = writer.tail;\n this.len = writer.len;\n this.next = writer.states;\n }\n}\nconst bufferPool = (0,_pool_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"])();\n/**\n * Allocates a buffer of the specified size\n */\nfunction alloc(size) {\n if (globalThis.Buffer != null) {\n return (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(size);\n }\n return bufferPool(size);\n}\n/**\n * When a value is written, the writer calculates its byte length and puts it into a linked\n * list of operations to perform when finish() is called. This both allows us to allocate\n * buffers of the exact required size and reduces the amount of work we have to do compared\n * to first calculating over objects and then encoding over objects. In our case, the encoding\n * part is just a linked list walk calling operations with already prepared values.\n */\nclass Uint8ArrayWriter {\n /**\n * Current length\n */\n len;\n /**\n * Operations head\n */\n head;\n /**\n * Operations tail\n */\n tail;\n /**\n * Linked forked states\n */\n states;\n constructor() {\n this.len = 0;\n this.head = new Op(noop, 0, 0);\n this.tail = this.head;\n this.states = null;\n }\n /**\n * Pushes a new operation to the queue\n */\n _push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n }\n /**\n * Writes an unsigned 32 bit value as a varint\n */\n uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp((value = value >>> 0) <\n 128\n ? 1\n : value < 16384\n ? 2\n : value < 2097152\n ? 3\n : value < 268435456\n ? 4\n : 5, value)).len;\n return this;\n }\n /**\n * Writes a signed 32 bit value as a varint`\n */\n int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n }\n /**\n * Writes a 32 bit value as a varint, zig-zag encoded\n */\n sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64(value) {\n const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value);\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64Number(value) {\n return this._push(uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodeUint8Array, (0,uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodingLength)(value), value);\n }\n /**\n * Writes an unsigned 64 bit value as a varint\n */\n uint64String(value) {\n return this.uint64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64(value) {\n return this.uint64(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64Number(value) {\n return this.uint64Number(value);\n }\n /**\n * Writes a signed 64 bit value as a varint\n */\n int64String(value) {\n return this.uint64String(value);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64(value) {\n const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64Number(value) {\n const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n }\n /**\n * Writes a signed 64 bit value as a varint, zig-zag encoded\n */\n sint64String(value) {\n return this.sint64(BigInt(value));\n }\n /**\n * Writes a boolish value as a varint\n */\n bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n }\n /**\n * Writes an unsigned 32 bit value as fixed 32 bits\n */\n fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n }\n /**\n * Writes a signed 32 bit value as fixed 32 bits\n */\n sfixed32(value) {\n return this.fixed32(value);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64(value) {\n const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromBigInt(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64Number(value) {\n const bits = _longbits_js__WEBPACK_IMPORTED_MODULE_4__.LongBits.fromNumber(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n }\n /**\n * Writes an unsigned 64 bit value as fixed 64 bits\n */\n fixed64String(value) {\n return this.fixed64(BigInt(value));\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64(value) {\n return this.fixed64(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64Number(value) {\n return this.fixed64Number(value);\n }\n /**\n * Writes a signed 64 bit value as fixed 64 bits\n */\n sfixed64String(value) {\n return this.fixed64String(value);\n }\n /**\n * Writes a float (32 bit)\n */\n float(value) {\n return this._push(_float_js__WEBPACK_IMPORTED_MODULE_3__.writeFloatLE, 4, value);\n }\n /**\n * Writes a double (64 bit float).\n *\n * @function\n * @param {number} value - Value to write\n * @returns {Writer} `this`\n */\n double(value) {\n return this._push(_float_js__WEBPACK_IMPORTED_MODULE_3__.writeDoubleLE, 8, value);\n }\n /**\n * Writes a sequence of bytes\n */\n bytes(value) {\n const len = value.length >>> 0;\n if (len === 0) {\n return this._push(writeByte, 1, 0);\n }\n return this.uint32(len)._push(writeBytes, len, value);\n }\n /**\n * Writes a string\n */\n string(value) {\n const len = _utf8_js__WEBPACK_IMPORTED_MODULE_6__.length(value);\n return len !== 0\n ? this.uint32(len)._push(_utf8_js__WEBPACK_IMPORTED_MODULE_6__.write, len, value)\n : this._push(writeByte, 1, 0);\n }\n /**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n */\n fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n }\n /**\n * Resets this instance to the last state\n */\n reset() {\n if (this.states != null) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n }\n else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n }\n /**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n */\n ldelim() {\n const head = this.head;\n const tail = this.tail;\n const len = this.len;\n this.reset().uint32(len);\n if (len !== 0) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n }\n /**\n * Finishes the write operation\n */\n finish() {\n let head = this.head.next; // skip noop\n const buf = alloc(this.len);\n let pos = 0;\n while (head != null) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n }\n}\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n/**\n * Constructs a new varint writer operation instance.\n *\n * @classdesc Scheduled varint writer operation\n */\nclass VarintOp extends Op {\n next;\n constructor(len, val) {\n super(writeVarint32, len, val);\n this.next = undefined;\n }\n}\nfunction writeVarint64(val, buf, pos) {\n while (val.hi !== 0) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\nfunction writeFixed32(val, buf, pos) {\n buf[pos] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\nfunction writeBytes(val, buf, pos) {\n buf.set(val, pos);\n}\nif (globalThis.Buffer != null) {\n Uint8ArrayWriter.prototype.bytes = function (value) {\n const len = value.length >>> 0;\n this.uint32(len);\n if (len > 0) {\n this._push(writeBytesBuffer, len, value);\n }\n return this;\n };\n Uint8ArrayWriter.prototype.string = function (value) {\n const len = globalThis.Buffer.byteLength(value);\n this.uint32(len);\n if (len > 0) {\n this._push(writeStringBuffer, len, value);\n }\n return this;\n };\n}\nfunction writeBytesBuffer(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n}\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) {\n // plain js is faster for short strings (probably due to redundant assertions)\n _utf8_js__WEBPACK_IMPORTED_MODULE_6__.write(val, buf, pos);\n // @ts-expect-error buf isn't a Uint8Array?\n }\n else if (buf.utf8Write != null) {\n // @ts-expect-error buf isn't a Uint8Array?\n buf.utf8Write(val, pos);\n }\n else {\n buf.set((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_2__.fromString)(val), pos);\n }\n}\n/**\n * Creates a new writer\n */\nfunction createWriter() {\n return new Uint8ArrayWriter();\n}\n//# sourceMappingURL=writer.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-gossipsub/node_modules/protons-runtime/dist/src/utils/writer.js?"); + +/***/ }), + /***/ "./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/alloc.js": /*!*********************************************************************************************!*\ !*** ./node_modules/@chainsafe/libp2p-gossipsub/node_modules/uint8arrays/dist/src/alloc.js ***! @@ -3956,7 +6023,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/peer-id/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -3967,7 +6034,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -4011,7 +6078,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -4132,7 +6199,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -4176,7 +6243,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -4352,7 +6419,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compare: () => (/* reexport safe */ _compare__WEBPACK_IMPORTED_MODULE_2__.compare),\n/* harmony export */ concat: () => (/* reexport safe */ _concat__WEBPACK_IMPORTED_MODULE_3__.concat),\n/* harmony export */ equals: () => (/* reexport safe */ _equals_js__WEBPACK_IMPORTED_MODULE_0__.equals),\n/* harmony export */ fromString: () => (/* reexport safe */ _from_string__WEBPACK_IMPORTED_MODULE_4__.fromString),\n/* harmony export */ toString: () => (/* reexport safe */ _to_string__WEBPACK_IMPORTED_MODULE_5__.toString),\n/* harmony export */ xor: () => (/* reexport safe */ _xor_js__WEBPACK_IMPORTED_MODULE_1__.xor)\n/* harmony export */ });\n/* harmony import */ var _equals_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./equals.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _xor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xor.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/xor.js\");\n/* harmony import */ var _compare__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! #compare */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/compare.js\");\n/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! #concat */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var _from_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! #from-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _to_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! #to-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * `Uint8Array`s bring memory-efficient(ish) byte handling to browsers - they are similar to Node.js `Buffer`s but lack a lot of the utility methods present on that class.\n *\n * This module exports a number of function that let you do common operations - joining Uint8Arrays together, seeing if they have the same contents etc.\n *\n * Since Node.js `Buffer`s are also `Uint8Array`s, it falls back to `Buffer` internally where it makes sense for performance reasons.\n *\n * ## alloc(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * ### Example\n *\n * ```js\n * import { alloc } from 'uint8arrays/alloc'\n *\n * const buf = alloc(100)\n * ```\n *\n * ## allocUnsafe(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * On platforms that support it, memory referenced by the returned `Uint8Array` will not be initialized.\n *\n * ### Example\n *\n * ```js\n * import { allocUnsafe } from 'uint8arrays/alloc'\n *\n * const buf = allocUnsafe(100)\n * ```\n *\n * ## compare(a, b)\n *\n * Compare two `Uint8Arrays`\n *\n * ### Example\n *\n * ```js\n * import { compare } from 'uint8arrays/compare'\n *\n * const arrays = [\n * Uint8Array.from([3, 4, 5]),\n * Uint8Array.from([0, 1, 2])\n * ]\n *\n * const sorted = arrays.sort(compare)\n *\n * console.info(sorted)\n * // [\n * // Uint8Array[0, 1, 2]\n * // Uint8Array[3, 4, 5]\n * // ]\n * ```\n *\n * ## concat(arrays, \\[length])\n *\n * Concatenate one or more `Uint8Array`s and return a `Uint8Array` with their contents.\n *\n * If you know the length of the arrays, pass it as a second parameter, otherwise it will be calculated by traversing the list of arrays.\n *\n * ### Example\n *\n * ```js\n * import { concat } from 'uint8arrays/concat'\n *\n * const arrays = [\n * Uint8Array.from([0, 1, 2]),\n * Uint8Array.from([3, 4, 5])\n * ]\n *\n * const all = concat(arrays, 6)\n *\n * console.info(all)\n * // Uint8Array[0, 1, 2, 3, 4, 5]\n * ```\n *\n * ## equals(a, b)\n *\n * Returns true if the two arrays are the same array or if they have the same length and contents.\n *\n * ### Example\n *\n * ```js\n * import { equals } from 'uint8arrays/equals'\n *\n * const a = Uint8Array.from([0, 1, 2])\n * const b = Uint8Array.from([3, 4, 5])\n * const c = Uint8Array.from([0, 1, 2])\n *\n * console.info(equals(a, b)) // false\n * console.info(equals(a, c)) // true\n * console.info(equals(a, a)) // true\n * ```\n *\n * ## fromString(string, encoding = 'utf8')\n *\n * Returns a new `Uint8Array` created from the passed string and interpreted as the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { fromString } from 'uint8arrays/from-string'\n *\n * console.info(fromString('hello world')) // Uint8Array[104, 101 ...\n * console.info(fromString('00010203aabbcc', 'base16')) // Uint8Array[0, 1 ...\n * console.info(fromString('AAECA6q7zA', 'base64')) // Uint8Array[0, 1 ...\n * console.info(fromString('01234', 'ascii')) // Uint8Array[48, 49 ...\n * ```\n *\n * ## toString(array, encoding = 'utf8')\n *\n * Returns a string created from the passed `Uint8Array` in the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { toString } from 'uint8arrays/to-string'\n *\n * console.info(toString(Uint8Array.from([104, 101...]))) // 'hello world'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base16')) // '00010203aabbcc'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base64')) // 'AAECA6q7zA'\n * console.info(toString(Uint8Array.from([48, 49, 50...]), 'ascii')) // '01234'\n * ```\n *\n * ## xor(a, b)\n *\n * Returns a `Uint8Array` containing `a` and `b` xored together.\n *\n * ### Example\n *\n * ```js\n * import { xor } from 'uint8arrays/xor'\n *\n * console.info(xor(Uint8Array.from([1, 0]), Uint8Array.from([0, 1]))) // Uint8Array[1, 1]\n * ```\n */\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compare: () => (/* reexport safe */ _compare__WEBPACK_IMPORTED_MODULE_2__.compare),\n/* harmony export */ concat: () => (/* reexport safe */ _concat__WEBPACK_IMPORTED_MODULE_3__.concat),\n/* harmony export */ equals: () => (/* reexport safe */ _equals_js__WEBPACK_IMPORTED_MODULE_0__.equals),\n/* harmony export */ fromString: () => (/* reexport safe */ _from_string__WEBPACK_IMPORTED_MODULE_4__.fromString),\n/* harmony export */ toString: () => (/* reexport safe */ _to_string__WEBPACK_IMPORTED_MODULE_5__.toString),\n/* harmony export */ xor: () => (/* reexport safe */ _xor_js__WEBPACK_IMPORTED_MODULE_1__.xor)\n/* harmony export */ });\n/* harmony import */ var _equals_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./equals.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _xor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xor.js */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/xor.js\");\n/* harmony import */ var _compare__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! #compare */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/compare.js\");\n/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! #concat */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var _from_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! #from-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _to_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! #to-string */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * `Uint8Array`s bring memory-efficient(ish) byte handling to browsers - they are similar to Node.js `Buffer`s but lack a lot of the utility methods present on that class.\n *\n * This module exports a number of function that let you do common operations - joining Uint8Arrays together, seeing if they have the same contents etc.\n *\n * Since Node.js `Buffer`s are also `Uint8Array`s, it falls back to `Buffer` internally where it makes sense for performance reasons.\n *\n * ## alloc(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * ### Example\n *\n * ```js\n * import { alloc } from 'uint8arrays/alloc'\n *\n * const buf = alloc(100)\n * ```\n *\n * ## allocUnsafe(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * On platforms that support it, memory referenced by the returned `Uint8Array` will not be initialized.\n *\n * ### Example\n *\n * ```js\n * import { allocUnsafe } from 'uint8arrays/alloc'\n *\n * const buf = allocUnsafe(100)\n * ```\n *\n * ## compare(a, b)\n *\n * Compare two `Uint8Arrays`\n *\n * ### Example\n *\n * ```js\n * import { compare } from 'uint8arrays/compare'\n *\n * const arrays = [\n * Uint8Array.from([3, 4, 5]),\n * Uint8Array.from([0, 1, 2])\n * ]\n *\n * const sorted = arrays.sort(compare)\n *\n * console.info(sorted)\n * // [\n * // Uint8Array[0, 1, 2]\n * // Uint8Array[3, 4, 5]\n * // ]\n * ```\n *\n * ## concat(arrays, \\[length])\n *\n * Concatenate one or more `Uint8Array`s and return a `Uint8Array` with their contents.\n *\n * If you know the length of the arrays, pass it as a second parameter, otherwise it will be calculated by traversing the list of arrays.\n *\n * ### Example\n *\n * ```js\n * import { concat } from 'uint8arrays/concat'\n *\n * const arrays = [\n * Uint8Array.from([0, 1, 2]),\n * Uint8Array.from([3, 4, 5])\n * ]\n *\n * const all = concat(arrays, 6)\n *\n * console.info(all)\n * // Uint8Array[0, 1, 2, 3, 4, 5]\n * ```\n *\n * ## equals(a, b)\n *\n * Returns true if the two arrays are the same array or if they have the same length and contents.\n *\n * ### Example\n *\n * ```js\n * import { equals } from 'uint8arrays/equals'\n *\n * const a = Uint8Array.from([0, 1, 2])\n * const b = Uint8Array.from([3, 4, 5])\n * const c = Uint8Array.from([0, 1, 2])\n *\n * console.info(equals(a, b)) // false\n * console.info(equals(a, c)) // true\n * console.info(equals(a, a)) // true\n * ```\n *\n * ## fromString(string, encoding = 'utf8')\n *\n * Returns a new `Uint8Array` created from the passed string and interpreted as the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { fromString } from 'uint8arrays/from-string'\n *\n * console.info(fromString('hello world')) // Uint8Array[104, 101 ...\n * console.info(fromString('00010203aabbcc', 'base16')) // Uint8Array[0, 1 ...\n * console.info(fromString('AAECA6q7zA', 'base64')) // Uint8Array[0, 1 ...\n * console.info(fromString('01234', 'ascii')) // Uint8Array[48, 49 ...\n * ```\n *\n * ## toString(array, encoding = 'utf8')\n *\n * Returns a string created from the passed `Uint8Array` in the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { toString } from 'uint8arrays/to-string'\n *\n * console.info(toString(Uint8Array.from([104, 101...]))) // 'hello world'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base16')) // '00010203aabbcc'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base64')) // 'AAECA6q7zA'\n * console.info(toString(Uint8Array.from([48, 49, 50...]), 'ascii')) // '01234'\n * ```\n *\n * ## xor(a, b)\n *\n * Returns a `Uint8Array` containing `a` and `b` xored together.\n *\n * ### Example\n *\n * ```js\n * import { xor } from 'uint8arrays/xor'\n *\n * console.info(xor(Uint8Array.from([1, 0]), Uint8Array.from([0, 1]))) // Uint8Array[1, 1]\n * ```\n *\n * ## xorCompare(a, b)\n *\n * Compares the distances between two xor `Uint8Array`s.\n *\n * ### Example\n *\n * ```ts\n * import { xor } from 'uint8arrays/xor'\n * import { xorCompare } from 'uint8arrays/xor-compare'\n *\n * const target = Uint8Array.from([1, 1])\n * const val1 = Uint8Array.from([1, 0])\n * const xor1 = xor(target, val1)\n *\n * const val2 = Uint8Array.from([0, 1])\n * const xor2 = xor(target, val2)\n *\n * console.info(xorCompare(xor1, xor2)) // -1 or 0 or 1\n * ```\n */\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/index.js?"); /***/ }), @@ -4396,7 +6463,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ xor: () => (/* binding */ xor)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns the xor distance between two arrays\n */\nfunction xor(a, b) {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length');\n }\n const result = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(a.length);\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i];\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(result);\n}\n//# sourceMappingURL=xor.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/xor.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ xor: () => (/* binding */ xor)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns the xor distance between two Uint8Arrays\n */\nfunction xor(a, b) {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length');\n }\n const result = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(a.length);\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i];\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(result);\n}\n//# sourceMappingURL=xor.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@chainsafe/libp2p-noise/node_modules/uint8arrays/dist/src/xor.js?"); /***/ }), @@ -4561,7 +6628,29 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bootstrap: () => (/* binding */ bootstrap)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_mafmt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/mafmt */ \"./node_modules/@multiformats/mafmt/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\n\n\n\n\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap';\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nconst DEFAULT_BOOTSTRAP_TAG_TTL = 120000;\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000;\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.TypedEventEmitter {\n static tag = 'bootstrap';\n log;\n timer;\n list;\n timeout;\n components;\n _init;\n constructor(components, options = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses');\n }\n super();\n this.components = components;\n this.log = components.logger.forComponent('libp2p:bootstrap');\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT;\n this.list = [];\n for (const candidate of options.list) {\n if (!_multiformats_mafmt__WEBPACK_IMPORTED_MODULE_0__.P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr');\n continue;\n }\n const ma = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_1__.multiaddr)(candidate);\n const peerIdStr = ma.getPeerId();\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id');\n continue;\n }\n const peerData = {\n id: (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__.peerIdFromString)(peerIdStr),\n multiaddrs: [ma]\n };\n this.list.push(peerData);\n }\n this._init = options;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.peerDiscoverySymbol] = this;\n [Symbol.toStringTag] = '@libp2p/bootstrap';\n isStarted() {\n return Boolean(this.timer);\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted()) {\n return;\n }\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout);\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err);\n });\n }, this.timeout);\n }\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers() {\n if (this.timer == null) {\n return;\n }\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n }\n });\n // check we are still running\n if (this.timer == null) {\n return;\n }\n this.safeDispatchEvent('peer', { detail: peerData });\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n this.timer = undefined;\n }\n}\nfunction bootstrap(init) {\n return (components) => new Bootstrap(components, init);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bootstrap: () => (/* binding */ bootstrap)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_mafmt__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/mafmt */ \"./node_modules/@multiformats/mafmt/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * The configured bootstrap peers will be discovered after the configured timeout. This will ensure there are some peers in the peer store for the node to use to discover other peers.\n *\n * They will be tagged with a tag with the name `'bootstrap'` tag, the value `50` and it will expire after two minutes which means the nodes connections may be closed if the maximum number of connections is reached.\n *\n * Clients that need constant connections to bootstrap nodes (e.g. browsers) can set the TTL to `Infinity`.\n *\n * @example Configuring a list of bootstrap nodes\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { bootstrap } from '@libp2p/bootstrap'\n *\n * const libp2p = await createLibp2p({\n * peerDiscovery: [\n * bootstrap({\n * list: [\n * // a list of bootstrap peer multiaddrs to connect to on node startup\n * '/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN',\n * '/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa'\n * ]\n * })\n * ]\n * })\n *\n * libp2p.addEventListener('peer:discovery', (evt) => {\n * console.log('found peer: ', evt.detail.toString())\n * })\n * ```\n */\n\n\n\n\nconst DEFAULT_BOOTSTRAP_TAG_NAME = 'bootstrap';\nconst DEFAULT_BOOTSTRAP_TAG_VALUE = 50;\nconst DEFAULT_BOOTSTRAP_TAG_TTL = 120000;\nconst DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT = 1000;\n/**\n * Emits 'peer' events on a regular interval for each peer in the provided list.\n */\nclass Bootstrap extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.TypedEventEmitter {\n static tag = 'bootstrap';\n log;\n timer;\n list;\n timeout;\n components;\n _init;\n constructor(components, options = { list: [] }) {\n if (options.list == null || options.list.length === 0) {\n throw new Error('Bootstrap requires a list of peer addresses');\n }\n super();\n this.components = components;\n this.log = components.logger.forComponent('libp2p:bootstrap');\n this.timeout = options.timeout ?? DEFAULT_BOOTSTRAP_DISCOVERY_TIMEOUT;\n this.list = [];\n for (const candidate of options.list) {\n if (!_multiformats_mafmt__WEBPACK_IMPORTED_MODULE_0__.P2P.matches(candidate)) {\n this.log.error('Invalid multiaddr');\n continue;\n }\n const ma = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_1__.multiaddr)(candidate);\n const peerIdStr = ma.getPeerId();\n if (peerIdStr == null) {\n this.log.error('Invalid bootstrap multiaddr without peer id');\n continue;\n }\n const peerData = {\n id: (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__.peerIdFromString)(peerIdStr),\n multiaddrs: [ma]\n };\n this.list.push(peerData);\n }\n this._init = options;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.peerDiscoverySymbol] = this;\n [Symbol.toStringTag] = '@libp2p/bootstrap';\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.serviceCapabilities] = [\n '@libp2p/peer-discovery'\n ];\n isStarted() {\n return Boolean(this.timer);\n }\n /**\n * Start emitting events\n */\n start() {\n if (this.isStarted()) {\n return;\n }\n this.log('Starting bootstrap node discovery, discovering peers after %s ms', this.timeout);\n this.timer = setTimeout(() => {\n void this._discoverBootstrapPeers()\n .catch(err => {\n this.log.error(err);\n });\n }, this.timeout);\n }\n /**\n * Emit each address in the list as a PeerInfo\n */\n async _discoverBootstrapPeers() {\n if (this.timer == null) {\n return;\n }\n for (const peerData of this.list) {\n await this.components.peerStore.merge(peerData.id, {\n tags: {\n [this._init.tagName ?? DEFAULT_BOOTSTRAP_TAG_NAME]: {\n value: this._init.tagValue ?? DEFAULT_BOOTSTRAP_TAG_VALUE,\n ttl: this._init.tagTTL ?? DEFAULT_BOOTSTRAP_TAG_TTL\n }\n }\n });\n // check we are still running\n if (this.timer == null) {\n return;\n }\n this.safeDispatchEvent('peer', { detail: peerData });\n }\n }\n /**\n * Stop emitting events\n */\n stop() {\n if (this.timer != null) {\n clearTimeout(this.timer);\n }\n this.timer = undefined;\n }\n}\nfunction bootstrap(init) {\n return (components) => new Bootstrap(components, init);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/connection/index.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/connection/index.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ connectionSymbol: () => (/* binding */ connectionSymbol),\n/* harmony export */ isConnection: () => (/* binding */ isConnection)\n/* harmony export */ });\nconst connectionSymbol = Symbol.for('@libp2p/connection');\nfunction isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/connection/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/content-routing/index.js": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/content-routing/index.js ***! + \*********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ contentRoutingSymbol: () => (/* binding */ contentRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/content-routing/index.js?"); /***/ }), @@ -4583,7 +6672,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n detail;\n constructor(message, data) {\n super(message, data);\n // @ts-expect-error could be undefined\n this.detail = data?.detail;\n }\n}\nconst CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/event-target.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/event-target.js?"); /***/ }), @@ -4609,6 +6698,28 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/index.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/index.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AbortError),\n/* harmony export */ AggregateCodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AggregateCodeError),\n/* harmony export */ CodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.CodeError),\n/* harmony export */ CustomEvent: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.CustomEvent),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_TIMEOUT),\n/* harmony export */ Ed25519: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.Ed25519),\n/* harmony export */ FaultTolerance: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.FaultTolerance),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoTransmissionError),\n/* harmony export */ KEEP_ALIVE: () => (/* reexport safe */ _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__.KEEP_ALIVE),\n/* harmony export */ RSA: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.RSA),\n/* harmony export */ StrictNoSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictNoSign),\n/* harmony export */ StrictSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.TopicValidatorResult),\n/* harmony export */ TypedEventEmitter: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.TypedEventEmitter),\n/* harmony export */ UnexpectedPeerError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.UnexpectedPeerError),\n/* harmony export */ connectionSymbol: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.connectionSymbol),\n/* harmony export */ contentRoutingSymbol: () => (/* reexport safe */ _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__.contentRoutingSymbol),\n/* harmony export */ isConnection: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.isConnection),\n/* harmony export */ isPeerId: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.isPeerId),\n/* harmony export */ isStartable: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.isStartable),\n/* harmony export */ isTransport: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.isTransport),\n/* harmony export */ peerDiscoverySymbol: () => (/* reexport safe */ _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__.peerDiscoverySymbol),\n/* harmony export */ peerIdSymbol: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.peerIdSymbol),\n/* harmony export */ peerRoutingSymbol: () => (/* reexport safe */ _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__.peerRoutingSymbol),\n/* harmony export */ secp256k1: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.secp256k1),\n/* harmony export */ serviceCapabilities: () => (/* binding */ serviceCapabilities),\n/* harmony export */ serviceDependencies: () => (/* binding */ serviceDependencies),\n/* harmony export */ setMaxListeners: () => (/* reexport safe */ _events_js__WEBPACK_IMPORTED_MODULE_11__.setMaxListeners),\n/* harmony export */ start: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.start),\n/* harmony export */ stop: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.stop),\n/* harmony export */ transportSymbol: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.transportSymbol)\n/* harmony export */ });\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/connection/index.js\");\n/* harmony import */ var _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./content-routing/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _keys_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/keys/index.js\");\n/* harmony import */ var _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peer-discovery/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./peer-id/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./peer-routing/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./peer-store/tags.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./pubsub/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/pubsub/index.js\");\n/* harmony import */ var _transport_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./transport/index.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _event_target_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./event-target.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _startable_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./startable.js */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/startable.js\");\n/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nconst serviceDependencies = Symbol.for('@libp2p/service-dependencies');\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/keys/index.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/keys/index.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519: () => (/* binding */ Ed25519),\n/* harmony export */ RSA: () => (/* binding */ RSA),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\nconst Ed25519 = 'Ed25519';\nconst RSA = 'RSA';\nconst secp256k1 = 'secp256k1';\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/keys/index.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js": /*!********************************************************************************************************!*\ !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js ***! @@ -4631,6 +6742,61 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-routing/index.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-routing/index.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ peerRoutingSymbol: () => (/* binding */ peerRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-routing/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-store/tags.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-store/tags.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KEEP_ALIVE: () => (/* binding */ KEEP_ALIVE)\n/* harmony export */ });\nconst KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-store/tags.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/pubsub/index.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/pubsub/index.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ StrictNoSign: () => (/* binding */ StrictNoSign),\n/* harmony export */ StrictSign: () => (/* binding */ StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* binding */ TopicValidatorResult)\n/* harmony export */ });\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nconst StrictSign = 'StrictSign';\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nconst StrictNoSign = 'StrictNoSign';\nvar TopicValidatorResult;\n(function (TopicValidatorResult) {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n TopicValidatorResult[\"Accept\"] = \"accept\";\n /**\n * The message is neither delivered nor forwarded to the network\n */\n TopicValidatorResult[\"Ignore\"] = \"ignore\";\n /**\n * The message is considered invalid, and it should be rejected\n */\n TopicValidatorResult[\"Reject\"] = \"reject\";\n})(TopicValidatorResult || (TopicValidatorResult = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/pubsub/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/startable.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/startable.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isStartable: () => (/* binding */ isStartable),\n/* harmony export */ start: () => (/* binding */ start),\n/* harmony export */ stop: () => (/* binding */ stop)\n/* harmony export */ });\nfunction isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nasync function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nasync function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/startable.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/transport/index.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/transport/index.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FaultTolerance: () => (/* binding */ FaultTolerance),\n/* harmony export */ isTransport: () => (/* binding */ isTransport),\n/* harmony export */ transportSymbol: () => (/* binding */ transportSymbol)\n/* harmony export */ });\nconst transportSymbol = Symbol.for('@libp2p/transport');\nfunction isTransport(other) {\n return other != null && Boolean(other[transportSymbol]);\n}\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nvar FaultTolerance;\n(function (FaultTolerance) {\n /**\n * should be used for failing in any listen circumstance\n */\n FaultTolerance[FaultTolerance[\"FATAL_ALL\"] = 0] = \"FATAL_ALL\";\n /**\n * should be used for not failing when not listening\n */\n FaultTolerance[FaultTolerance[\"NO_FATAL\"] = 1] = \"NO_FATAL\";\n})(FaultTolerance || (FaultTolerance = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/transport/index.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js": /*!***************************************************************************************!*\ !*** ./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js ***! @@ -4638,7 +6804,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/bootstrap/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -4649,7 +6815,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -4693,7 +6859,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -4814,7 +6980,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -4858,7 +7024,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -4972,6 +7138,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/alloc.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/alloc.js ***! + \***********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ alloc: () => (/* binding */ alloc),\n/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)\n/* harmony export */ });\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nfunction alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nfunction allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/alloc.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/equals.js": /*!************************************************************************************!*\ !*** ./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/equals.js ***! @@ -4983,6 +7160,39 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/from-string.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/from-string.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fromString: () => (/* binding */ fromString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction fromString(string, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/from-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/to-string.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/to-string.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction toString(array, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/to-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/util/bases.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/util/bases.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/bootstrap/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/alloc.js\");\n\n\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);\n//# sourceMappingURL=bases.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/bootstrap/node_modules/uint8arrays/dist/src/util/bases.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js": /*!*************************************************************************!*\ !*** ./node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js ***! @@ -5232,7 +7442,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Identify: () => (/* binding */ Identify)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr-matcher */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js\");\n/* harmony import */ var it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! it-protobuf-stream */ \"./node_modules/it-protobuf-stream/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var wherearewe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! wherearewe */ \"./node_modules/wherearewe/src/index.js\");\n/* harmony import */ var _consts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./consts.js */ \"./node_modules/@libp2p/identify/dist/src/consts.js\");\n/* harmony import */ var _pb_message_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pb/message.js */ \"./node_modules/@libp2p/identify/dist/src/pb/message.js\");\n/* eslint-disable complexity */\n\n\n\n\n\n\n\n\n\n\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8;\nconst defaultValues = {\n protocolPrefix: 'ipfs',\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1,\n maxObservedAddresses: 10,\n maxIdentifyMessageSize: 8192,\n runOnConnectionOpen: true,\n runOnTransientConnection: true\n};\nclass Identify {\n identifyProtocolStr;\n identifyPushProtocolStr;\n host;\n started;\n timeout;\n peerId;\n peerStore;\n registrar;\n connectionManager;\n addressManager;\n maxInboundStreams;\n maxOutboundStreams;\n maxPushIncomingStreams;\n maxPushOutgoingStreams;\n maxIdentifyMessageSize;\n maxObservedAddresses;\n events;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.started = false;\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.registrar = components.registrar;\n this.addressManager = components.addressManager;\n this.connectionManager = components.connectionManager;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:identify');\n this.identifyProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`;\n this.identifyPushProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? defaultValues.timeout;\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams;\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams;\n this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? defaultValues.maxPushIncomingStreams;\n this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? defaultValues.maxPushOutgoingStreams;\n this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? defaultValues.maxIdentifyMessageSize;\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses;\n this.runOnTransientConnection = init.runOnTransientConnection ?? defaultValues.runOnTransientConnection;\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: init.agentVersion ?? `${components.nodeInfo.name}/${components.nodeInfo.version}`\n };\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail;\n this.identify(connection).catch(err => { this.log.error('error during identify trigged by connection:open', err); });\n });\n }\n // When self peer record changes, trigger identify-push\n components.events.addEventListener('self:peer:update', (evt) => {\n void this.push().catch(err => { this.log.error(err); });\n });\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (this.host.agentVersion === `${components.nodeInfo.name}/${components.nodeInfo.version}`) {\n if (wherearewe__WEBPACK_IMPORTED_MODULE_5__.isNode || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isElectronMain) {\n this.host.agentVersion += ` UserAgent=${globalThis.process.version}`;\n }\n else if (wherearewe__WEBPACK_IMPORTED_MODULE_5__.isBrowser || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isWebWorker || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isElectronRenderer || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isReactNative) {\n this.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`;\n }\n }\n }\n isStarted() {\n return this.started;\n }\n async start() {\n if (this.started) {\n return;\n }\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.agentVersion),\n ProtocolVersion: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.protocolVersion)\n }\n });\n await this.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n await this.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxPushIncomingStreams,\n maxOutboundStreams: this.maxPushOutgoingStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.registrar.unhandle(this.identifyProtocolStr);\n await this.registrar.unhandle(this.identifyPushProtocolStr);\n this.started = false;\n }\n /**\n * Send an Identify Push update to the list of connections\n */\n async pushToConnections(connections) {\n const listenAddresses = this.addressManager.getAddresses().map(ma => ma.decapsulateCode((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('p2p').code));\n const peerRecord = new _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord({\n peerId: this.peerId,\n multiaddrs: listenAddresses\n });\n const signedPeerRecord = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.seal(peerRecord, this.peerId);\n const supportedProtocols = this.registrar.getProtocols();\n const peer = await this.peerStore.get(this.peerId);\n const agentVersion = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__.toString)(peer.metadata.get('AgentVersion') ?? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.agentVersion));\n const protocolVersion = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__.toString)(peer.metadata.get('ProtocolVersion') ?? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.protocolVersion));\n const pushes = connections.map(async (connection) => {\n let stream;\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n try {\n stream = await connection.newStream(this.identifyPushProtocolStr, {\n signal,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n await pb.write({\n listenAddrs: listenAddresses.map(ma => ma.bytes),\n signedPeerRecord: signedPeerRecord.marshal(),\n protocols: supportedProtocols,\n agentVersion,\n protocolVersion\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n // Just log errors\n this.log.error('could not push identify update to peer', err);\n stream?.abort(err);\n }\n });\n await Promise.all(pushes);\n }\n /**\n * Calls `push` on all peer connections\n */\n async push() {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return;\n }\n const connections = [];\n await Promise.all(this.connectionManager.getConnections().map(async (conn) => {\n try {\n const peer = await this.peerStore.get(conn.remotePeer);\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n return;\n }\n connections.push(conn);\n }\n catch (err) {\n if (err.code !== _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }));\n await this.pushToConnections(connections);\n }\n async _identify(connection, options = {}) {\n let stream;\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.identifyProtocolStr, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n const message = await pb.read(options);\n await stream.close(options);\n return message;\n }\n catch (err) {\n this.log.error('error while reading identify message', err);\n stream?.abort(err);\n throw err;\n }\n }\n async identify(connection, options = {}) {\n const message = await this._identify(connection, options);\n const { publicKey, protocols, observedAddr } = message;\n if (publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('public key was missing from identify message', 'ERR_MISSING_PUBLIC_KEY');\n }\n const id = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__.peerIdFromKeys)(publicKey);\n if (!connection.remotePeer.equals(id)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('identified peer does not match the expected peer', 'ERR_INVALID_PEER');\n }\n if (this.peerId.equals(id)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('identified peer is our own peer id?', 'ERR_INVALID_PEER');\n }\n // Get the observedAddr if there is one\n const cleanObservedAddr = getCleanMultiaddr(observedAddr);\n this.log('identify completed for peer %p and protocols %o', id, protocols);\n this.log('our observed address is %a', cleanObservedAddr);\n if (cleanObservedAddr != null &&\n this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {\n this.log('storing our observed address %a', cleanObservedAddr);\n this.addressManager.addObservedAddr(cleanObservedAddr);\n }\n return this.#consumeIdentifyMessage(connection, message);\n }\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify(data) {\n const { connection, stream } = data;\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n try {\n const publicKey = this.peerId.publicKey ?? new Uint8Array(0);\n const peerData = await this.peerStore.get(this.peerId);\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('p2p').code));\n let signedPeerRecord = peerData.peerRecordEnvelope;\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord({\n peerId: this.peerId,\n multiaddrs\n });\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.seal(peerRecord, this.peerId);\n signedPeerRecord = envelope.marshal().subarray();\n }\n let observedAddr = connection.remoteAddr.bytes;\n if (!_multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_1__.IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined;\n }\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n this.log.error('could not respond to identify request', err);\n stream.abort(err);\n }\n }\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush(data) {\n const { connection, stream } = data;\n try {\n if (this.peerId.equals(connection.remotePeer)) {\n throw new Error('received push from ourselves?');\n }\n const options = {\n signal: AbortSignal.timeout(this.timeout)\n };\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n const message = await pb.read(options);\n await stream.close(options);\n await this.#consumeIdentifyMessage(connection, message);\n }\n catch (err) {\n this.log.error('received invalid message', err);\n stream.abort(err);\n return;\n }\n this.log('handled push from %p', connection.remotePeer);\n }\n async #consumeIdentifyMessage(connection, message) {\n this.log('received identify from %p', connection.remotePeer);\n if (message == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('message was null or undefined', 'ERR_INVALID_MESSAGE');\n }\n const peer = {};\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(buf)\n }));\n }\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols;\n }\n if (message.publicKey != null) {\n peer.publicKey = message.publicKey;\n const peerId = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__.peerIdFromKeys)(message.publicKey);\n if (!peerId.equals(connection.remotePeer)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('public key did not match remote PeerId', 'ERR_INVALID_PUBLIC_KEY');\n }\n }\n let output;\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n this.log('received signedPeerRecord from %p', connection.remotePeer);\n let peerRecordEnvelope = message.signedPeerRecord;\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.openAndCertify(peerRecordEnvelope, _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.DOMAIN);\n let peerRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.createFromProtobuf(envelope.payload);\n // Verify peerId\n if (!peerRecord.peerId.equals(envelope.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('signing key does not match PeerId in the PeerRecord', 'ERR_INVALID_SIGNING_KEY');\n }\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('signing key does not match remote PeerId', 'ERR_INVALID_PEER_RECORD_KEY');\n }\n let existingPeer;\n try {\n existingPeer = await this.peerStore.get(peerRecord.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata;\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope);\n const storedRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.createFromProtobuf(storedEnvelope.payload);\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n peerRecord = storedRecord;\n peerRecordEnvelope = existingPeer.peerRecordEnvelope;\n }\n }\n }\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope;\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }));\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n };\n }\n else {\n this.log('%p did not send a signed peer record', connection.remotePeer);\n }\n this.log('patching %p with', connection.remotePeer, peer);\n await this.peerStore.patch(connection.remotePeer, peer);\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata = {};\n if (message.agentVersion != null) {\n metadata.AgentVersion = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(message.agentVersion);\n }\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(message.protocolVersion);\n }\n this.log('merging %p metadata', connection.remotePeer, metadata);\n await this.peerStore.merge(connection.remotePeer, {\n metadata\n });\n }\n const result = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(buf)),\n observedAddr: message.observedAddr == null ? undefined : (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n };\n this.events.safeDispatchEvent('peer:identify', { detail: result });\n return result;\n }\n}\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nfunction getCleanMultiaddr(addr) {\n if (addr != null && addr.length > 0) {\n try {\n return (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(addr);\n }\n catch {\n }\n }\n}\n//# sourceMappingURL=identify.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/dist/src/identify.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Identify: () => (/* binding */ Identify)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/peer-record/dist/src/envelope/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr-matcher */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js\");\n/* harmony import */ var it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! it-protobuf-stream */ \"./node_modules/it-protobuf-stream/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var wherearewe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! wherearewe */ \"./node_modules/wherearewe/src/index.js\");\n/* harmony import */ var _consts_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./consts.js */ \"./node_modules/@libp2p/identify/dist/src/consts.js\");\n/* harmony import */ var _pb_message_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pb/message.js */ \"./node_modules/@libp2p/identify/dist/src/pb/message.js\");\n/* eslint-disable complexity */\n\n\n\n\n\n\n\n\n\n\n\n// https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L52\nconst MAX_IDENTIFY_MESSAGE_SIZE = 1024 * 8;\nconst defaultValues = {\n protocolPrefix: 'ipfs',\n // https://github.com/libp2p/go-libp2p/blob/8d2e54e1637041d5cf4fac1e531287560bd1f4ac/p2p/protocol/identify/id.go#L48\n timeout: 60000,\n maxInboundStreams: 1,\n maxOutboundStreams: 1,\n maxPushIncomingStreams: 1,\n maxPushOutgoingStreams: 1,\n maxObservedAddresses: 10,\n maxIdentifyMessageSize: 8192,\n runOnConnectionOpen: true,\n runOnTransientConnection: true\n};\nclass Identify {\n identifyProtocolStr;\n identifyPushProtocolStr;\n host;\n started;\n timeout;\n peerId;\n peerStore;\n registrar;\n connectionManager;\n addressManager;\n maxInboundStreams;\n maxOutboundStreams;\n maxPushIncomingStreams;\n maxPushOutgoingStreams;\n maxIdentifyMessageSize;\n maxObservedAddresses;\n events;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.started = false;\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.registrar = components.registrar;\n this.addressManager = components.addressManager;\n this.connectionManager = components.connectionManager;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:identify');\n this.identifyProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PROTOCOL_NAME}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PROTOCOL_VERSION}`;\n this.identifyPushProtocolStr = `/${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_NAME}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.MULTICODEC_IDENTIFY_PUSH_PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? defaultValues.timeout;\n this.maxInboundStreams = init.maxInboundStreams ?? defaultValues.maxInboundStreams;\n this.maxOutboundStreams = init.maxOutboundStreams ?? defaultValues.maxOutboundStreams;\n this.maxPushIncomingStreams = init.maxPushIncomingStreams ?? defaultValues.maxPushIncomingStreams;\n this.maxPushOutgoingStreams = init.maxPushOutgoingStreams ?? defaultValues.maxPushOutgoingStreams;\n this.maxIdentifyMessageSize = init.maxIdentifyMessageSize ?? defaultValues.maxIdentifyMessageSize;\n this.maxObservedAddresses = init.maxObservedAddresses ?? defaultValues.maxObservedAddresses;\n this.runOnTransientConnection = init.runOnTransientConnection ?? defaultValues.runOnTransientConnection;\n // Store self host metadata\n this.host = {\n protocolVersion: `${init.protocolPrefix ?? defaultValues.protocolPrefix}/${_consts_js__WEBPACK_IMPORTED_MODULE_6__.IDENTIFY_PROTOCOL_VERSION}`,\n agentVersion: init.agentVersion ?? `${components.nodeInfo.name}/${components.nodeInfo.version}`\n };\n if (init.runOnConnectionOpen ?? defaultValues.runOnConnectionOpen) {\n // When a new connection happens, trigger identify\n components.events.addEventListener('connection:open', (evt) => {\n const connection = evt.detail;\n this.identify(connection).catch(err => { this.log.error('error during identify trigged by connection:open', err); });\n });\n }\n // When self peer record changes, trigger identify-push\n components.events.addEventListener('self:peer:update', (evt) => {\n void this.push().catch(err => { this.log.error(err); });\n });\n // Append user agent version to default AGENT_VERSION depending on the environment\n if (this.host.agentVersion === `${components.nodeInfo.name}/${components.nodeInfo.version}`) {\n if (wherearewe__WEBPACK_IMPORTED_MODULE_5__.isNode || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isElectronMain) {\n this.host.agentVersion += ` UserAgent=${globalThis.process.version}`;\n }\n else if (wherearewe__WEBPACK_IMPORTED_MODULE_5__.isBrowser || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isWebWorker || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isElectronRenderer || wherearewe__WEBPACK_IMPORTED_MODULE_5__.isReactNative) {\n this.host.agentVersion += ` UserAgent=${globalThis.navigator.userAgent}`;\n }\n }\n }\n isStarted() {\n return this.started;\n }\n async start() {\n if (this.started) {\n return;\n }\n await this.peerStore.merge(this.peerId, {\n metadata: {\n AgentVersion: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.agentVersion),\n ProtocolVersion: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.protocolVersion)\n }\n });\n await this.registrar.handle(this.identifyProtocolStr, (data) => {\n void this._handleIdentify(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n await this.registrar.handle(this.identifyPushProtocolStr, (data) => {\n void this._handlePush(data).catch(err => {\n this.log.error(err);\n });\n }, {\n maxInboundStreams: this.maxPushIncomingStreams,\n maxOutboundStreams: this.maxPushOutgoingStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.registrar.unhandle(this.identifyProtocolStr);\n await this.registrar.unhandle(this.identifyPushProtocolStr);\n this.started = false;\n }\n /**\n * Send an Identify Push update to the list of connections\n */\n async pushToConnections(connections) {\n const listenAddresses = this.addressManager.getAddresses().map(ma => ma.decapsulateCode((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('p2p').code));\n const peerRecord = new _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord({\n peerId: this.peerId,\n multiaddrs: listenAddresses\n });\n const signedPeerRecord = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.seal(peerRecord, this.peerId);\n const supportedProtocols = this.registrar.getProtocols();\n const peer = await this.peerStore.get(this.peerId);\n const agentVersion = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__.toString)(peer.metadata.get('AgentVersion') ?? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.agentVersion));\n const protocolVersion = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_4__.toString)(peer.metadata.get('ProtocolVersion') ?? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(this.host.protocolVersion));\n const pushes = connections.map(async (connection) => {\n let stream;\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n try {\n stream = await connection.newStream(this.identifyPushProtocolStr, {\n signal,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n await pb.write({\n listenAddrs: listenAddresses.map(ma => ma.bytes),\n signedPeerRecord: signedPeerRecord.marshal(),\n protocols: supportedProtocols,\n agentVersion,\n protocolVersion\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n // Just log errors\n this.log.error('could not push identify update to peer', err);\n stream?.abort(err);\n }\n });\n await Promise.all(pushes);\n }\n /**\n * Calls `push` on all peer connections\n */\n async push() {\n // Do not try to push if we are not running\n if (!this.isStarted()) {\n return;\n }\n const connections = [];\n await Promise.all(this.connectionManager.getConnections().map(async (conn) => {\n try {\n const peer = await this.peerStore.get(conn.remotePeer);\n if (!peer.protocols.includes(this.identifyPushProtocolStr)) {\n return;\n }\n connections.push(conn);\n }\n catch (err) {\n if (err.code !== _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }));\n await this.pushToConnections(connections);\n }\n async _identify(connection, options = {}) {\n let stream;\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.identifyProtocolStr, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n const message = await pb.read(options);\n await stream.close(options);\n return message;\n }\n catch (err) {\n this.log.error('error while reading identify message', err);\n stream?.abort(err);\n throw err;\n }\n }\n async identify(connection, options = {}) {\n const message = await this._identify(connection, options);\n const { publicKey, protocols, observedAddr } = message;\n if (publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('public key was missing from identify message', 'ERR_MISSING_PUBLIC_KEY');\n }\n const id = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__.peerIdFromKeys)(publicKey);\n if (!connection.remotePeer.equals(id)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('identified peer does not match the expected peer', 'ERR_INVALID_PEER');\n }\n if (this.peerId.equals(id)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('identified peer is our own peer id?', 'ERR_INVALID_PEER');\n }\n // Get the observedAddr if there is one\n const cleanObservedAddr = getCleanMultiaddr(observedAddr);\n this.log('identify completed for peer %p and protocols %o', id, protocols);\n this.log('our observed address is %a', cleanObservedAddr);\n if (cleanObservedAddr != null &&\n this.addressManager.getObservedAddrs().length < (this.maxObservedAddresses ?? Infinity)) {\n this.log('storing our observed address %a', cleanObservedAddr);\n this.addressManager.addObservedAddr(cleanObservedAddr);\n }\n return this.#consumeIdentifyMessage(connection, message);\n }\n /**\n * Sends the `Identify` response with the Signed Peer Record\n * to the requesting peer over the given `connection`\n */\n async _handleIdentify(data) {\n const { connection, stream } = data;\n const signal = AbortSignal.timeout(this.timeout);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.setMaxListeners)(Infinity, signal);\n try {\n const publicKey = this.peerId.publicKey ?? new Uint8Array(0);\n const peerData = await this.peerStore.get(this.peerId);\n const multiaddrs = this.addressManager.getAddresses().map(ma => ma.decapsulateCode((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('p2p').code));\n let signedPeerRecord = peerData.peerRecordEnvelope;\n if (multiaddrs.length > 0 && signedPeerRecord == null) {\n const peerRecord = new _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord({\n peerId: this.peerId,\n multiaddrs\n });\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.seal(peerRecord, this.peerId);\n signedPeerRecord = envelope.marshal().subarray();\n }\n let observedAddr = connection.remoteAddr.bytes;\n if (!_multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_1__.IP_OR_DOMAIN.matches(connection.remoteAddr)) {\n observedAddr = undefined;\n }\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n await pb.write({\n protocolVersion: this.host.protocolVersion,\n agentVersion: this.host.agentVersion,\n publicKey,\n listenAddrs: multiaddrs.map(addr => addr.bytes),\n signedPeerRecord,\n observedAddr,\n protocols: peerData.protocols\n }, {\n signal\n });\n await stream.close({\n signal\n });\n }\n catch (err) {\n this.log.error('could not respond to identify request', err);\n stream.abort(err);\n }\n }\n /**\n * Reads the Identify Push message from the given `connection`\n */\n async _handlePush(data) {\n const { connection, stream } = data;\n try {\n if (this.peerId.equals(connection.remotePeer)) {\n throw new Error('received push from ourselves?');\n }\n const options = {\n signal: AbortSignal.timeout(this.timeout)\n };\n const pb = (0,it_protobuf_stream__WEBPACK_IMPORTED_MODULE_2__.pbStream)(stream, {\n maxDataLength: this.maxIdentifyMessageSize ?? MAX_IDENTIFY_MESSAGE_SIZE\n }).pb(_pb_message_js__WEBPACK_IMPORTED_MODULE_10__.Identify);\n const message = await pb.read(options);\n await stream.close(options);\n await this.#consumeIdentifyMessage(connection, message);\n }\n catch (err) {\n this.log.error('received invalid message', err);\n stream.abort(err);\n return;\n }\n this.log('handled push from %p', connection.remotePeer);\n }\n async #consumeIdentifyMessage(connection, message) {\n this.log('received identify from %p', connection.remotePeer);\n if (message == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('message was null or undefined', 'ERR_INVALID_MESSAGE');\n }\n const peer = {};\n if (message.listenAddrs.length > 0) {\n peer.addresses = message.listenAddrs.map(buf => ({\n isCertified: false,\n multiaddr: (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(buf)\n }));\n }\n if (message.protocols.length > 0) {\n peer.protocols = message.protocols;\n }\n if (message.publicKey != null) {\n peer.publicKey = message.publicKey;\n const peerId = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_12__.peerIdFromKeys)(message.publicKey);\n if (!peerId.equals(connection.remotePeer)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('public key did not match remote PeerId', 'ERR_INVALID_PUBLIC_KEY');\n }\n }\n let output;\n // if the peer record has been sent, prefer the addresses in the record as they are signed by the remote peer\n if (message.signedPeerRecord != null) {\n this.log('received signedPeerRecord from %p', connection.remotePeer);\n let peerRecordEnvelope = message.signedPeerRecord;\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.openAndCertify(peerRecordEnvelope, _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.DOMAIN);\n let peerRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.createFromProtobuf(envelope.payload);\n // Verify peerId\n if (!peerRecord.peerId.equals(envelope.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('signing key does not match PeerId in the PeerRecord', 'ERR_INVALID_SIGNING_KEY');\n }\n // Make sure remote peer is the one sending the record\n if (!connection.remotePeer.equals(peerRecord.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('signing key does not match remote PeerId', 'ERR_INVALID_PEER_RECORD_KEY');\n }\n let existingPeer;\n try {\n existingPeer = await this.peerStore.get(peerRecord.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n if (existingPeer != null) {\n // don't lose any existing metadata\n peer.metadata = existingPeer.metadata;\n // if we have previously received a signed record for this peer, compare it to the incoming one\n if (existingPeer.peerRecordEnvelope != null) {\n const storedEnvelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_8__.RecordEnvelope.createFromProtobuf(existingPeer.peerRecordEnvelope);\n const storedRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_7__.PeerRecord.createFromProtobuf(storedEnvelope.payload);\n // ensure seq is greater than, or equal to, the last received\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n peerRecord = storedRecord;\n peerRecordEnvelope = existingPeer.peerRecordEnvelope;\n }\n }\n }\n // store the signed record for next time\n peer.peerRecordEnvelope = peerRecordEnvelope;\n // override the stored addresses with the signed multiaddrs\n peer.addresses = peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }));\n output = {\n seq: peerRecord.seqNumber,\n addresses: peerRecord.multiaddrs\n };\n }\n else {\n this.log('%p did not send a signed peer record', connection.remotePeer);\n }\n this.log('patching %p with', connection.remotePeer, peer);\n await this.peerStore.patch(connection.remotePeer, peer);\n if (message.agentVersion != null || message.protocolVersion != null) {\n const metadata = {};\n if (message.agentVersion != null) {\n metadata.AgentVersion = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(message.agentVersion);\n }\n if (message.protocolVersion != null) {\n metadata.ProtocolVersion = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(message.protocolVersion);\n }\n this.log('merging %p metadata', connection.remotePeer, metadata);\n await this.peerStore.merge(connection.remotePeer, {\n metadata\n });\n }\n const result = {\n peerId: connection.remotePeer,\n protocolVersion: message.protocolVersion,\n agentVersion: message.agentVersion,\n publicKey: message.publicKey,\n listenAddrs: message.listenAddrs.map(buf => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(buf)),\n observedAddr: message.observedAddr == null ? undefined : (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(message.observedAddr),\n protocols: message.protocols,\n signedPeerRecord: output,\n connection\n };\n this.events.safeDispatchEvent('peer:identify', { detail: result });\n return result;\n }\n}\n/**\n * Takes the `addr` and converts it to a Multiaddr if possible\n */\nfunction getCleanMultiaddr(addr) {\n if (addr != null && addr.length > 0) {\n try {\n return (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(addr);\n }\n catch {\n }\n }\n}\n//# sourceMappingURL=identify.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/dist/src/identify.js?"); /***/ }), @@ -5258,226 +7468,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js": -/*!*******************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js ***! - \*******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ derivedEmptyPasswordKey: () => (/* binding */ derivedEmptyPasswordKey)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n\n\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nconst derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nfunction create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js": -/*!**************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js ***! - \**************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ create: () => (/* binding */ create)\n/* harmony export */ });\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _lengths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lengths.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js\");\n\n\nconst hashTypes = {\n SHA1: 'SHA-1',\n SHA256: 'SHA-256',\n SHA512: 'SHA-512'\n};\nconst sign = async (key, data) => {\n const buf = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].get().subtle.sign({ name: 'HMAC' }, key, data);\n return new Uint8Array(buf, 0, buf.byteLength);\n};\nasync function create(hashType, secret) {\n const hash = hashTypes[hashType];\n const key = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].get().subtle.importKey('raw', secret, {\n name: 'HMAC',\n hash: { name: hash }\n }, false, ['sign']);\n return {\n async digest(data) {\n return sign(key, data);\n },\n length: _lengths_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"][hashType]\n };\n}\n//# sourceMappingURL=index-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js": -/*!********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js ***! - \********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n SHA1: 20,\n SHA256: 32,\n SHA512: 64\n});\n//# sourceMappingURL=lengths.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js": -/*!*************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js ***! - \*************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateEphmeralKeyPair: () => (/* binding */ generateEphmeralKeyPair)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n\n\n\n\n\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n};\nconst curveTypes = Object.keys(bits);\nconst names = curveTypes.join(' / ');\nasync function generateEphmeralKeyPair(curve) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const pair = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.generateKey({\n name: 'ECDH',\n namedCurve: curve\n }, true, ['deriveBits']);\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub, forcePrivate) => {\n let privateKey;\n if (forcePrivate != null) {\n privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.importKey('jwk', unmarshalPrivateKey(curve, forcePrivate), {\n name: 'ECDH',\n namedCurve: curve\n }, false, ['deriveBits']);\n }\n else {\n privateKey = pair.privateKey;\n }\n const key = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.importKey('jwk', unmarshalPublicKey(curve, theirPub), {\n name: 'ECDH',\n namedCurve: curve\n }, false, []);\n const buffer = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.deriveBits({\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n }, privateKey, bits[curve]);\n return new Uint8Array(buffer, 0, buffer.byteLength);\n };\n const publicKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.exportKey('jwk', pair.publicKey);\n const ecdhKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n };\n return ecdhKey;\n}\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n};\n// Marshal converts a jwk encoded ECDH public key into the\n// form specified in section 4.3.6 of ANSI X9.62. (This is the format\n// go-ipfs uses)\nfunction marshalPublicKey(jwk) {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[jwk.crv];\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([\n Uint8Array.from([4]), // uncompressed point\n (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.x, byteLen),\n (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.y, byteLen)\n ], 1 + byteLen * 2);\n}\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey(curve, key) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[curve];\n if (!(0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT');\n }\n return {\n kty: 'EC',\n crv: curve,\n x: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1, byteLen + 1), 'base64url'),\n y: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n };\n}\nconst unmarshalPrivateKey = (curve, key) => ({\n ...unmarshalPublicKey(curve, key.public),\n d: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.private, 'base64url')\n});\n//# sourceMappingURL=ecdh-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js": -/*!****************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js ***! - \****************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ generateKeyFromSeed: () => (/* binding */ generateKeyFromSeed),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),\n/* harmony export */ publicKeyLength: () => (/* binding */ PUBLIC_KEY_BYTE_LENGTH)\n/* harmony export */ });\n/* harmony import */ var _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/curves/ed25519 */ \"./node_modules/@noble/curves/esm/ed25519.js\");\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\n\n\nfunction generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.utils.randomPrivateKey();\n const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nfunction generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nfunction hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nfunction hashAndVerify(publicKey, sig, msg) {\n return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js": -/*!**************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js ***! - \**************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* binding */ Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* binding */ Ed25519PublicKey),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ unmarshalEd25519PrivateKey: () => (/* binding */ unmarshalEd25519PrivateKey),\n/* harmony export */ unmarshalEd25519PublicKey: () => (/* binding */ unmarshalEd25519PublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n\n\n\n\n\n\n\n\n\nclass Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n }\n verify(data, sig) {\n return _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nclass Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n this._publicKey = ensureKey(publicKey, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n }\n sign(message) {\n return _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.bytes, key.bytes);\n }\n async hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256.digest(this.bytes);\n let bytes;\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_1__.identity.digest(this.public.bytes);\n return multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_7__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nfunction unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength) {\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength + _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const publicKeyBytes = bytes.subarray(_ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const publicKeyBytes = bytes.subarray(_ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nfunction unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nasync function generateKeyPair() {\n const { privateKey, publicKey } = _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nasync function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js": -/*!***************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js ***! - \***************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _ecdh_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ecdh.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js\");\n\n/**\n * Generates an ephemeral public key and returns a function that will compute\n * the shared secret key.\n *\n * Focuses only on ECDH now, but can be made more general in the future.\n */\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_ecdh_js__WEBPACK_IMPORTED_MODULE_0__.generateEphmeralKeyPair);\n//# sourceMappingURL=ephemeral-keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js": -/*!*********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js ***! - \*********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ exporter: () => (/* binding */ exporter)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ciphers/aes-gcm.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js\");\n\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nasync function exporter(privateKey, password) {\n const cipher = _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__.base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/importer.js": -/*!*********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/importer.js ***! - \*********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ importer: () => (/* binding */ importer)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ciphers/aes-gcm.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js\");\n\n\n/**\n * Attempts to decrypt a base64 encoded PrivateKey string\n * with the given password. The privateKey must have been exported\n * using the same password and underlying cipher (aes-gcm)\n */\nasync function importer(privateKey, password) {\n const encryptedKey = multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__.base64.decode(privateKey);\n const cipher = _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__.create();\n return cipher.decrypt(encryptedKey, password);\n}\n//# sourceMappingURL=importer.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/importer.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/index.js": -/*!******************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/index.js ***! - \******************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js": -/*!**************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js ***! - \**************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ keyStretcher: () => (/* binding */ keyStretcher)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../hmac/index.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js\");\n\n\n\n\nconst cipherMap = {\n 'AES-128': {\n ivSize: 16,\n keySize: 16\n },\n 'AES-256': {\n ivSize: 16,\n keySize: 32\n },\n Blowfish: {\n ivSize: 8,\n keySize: 32\n }\n};\n/**\n * Generates a set of keys for each party by stretching the shared key.\n * (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)\n */\nasync function keyStretcher(cipherType, hash, secret) {\n const cipher = cipherMap[cipherType];\n if (cipher == null) {\n const allowed = Object.keys(cipherMap).join(' / ');\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`unknown cipher type '${cipherType}'. Must be ${allowed}`, 'ERR_INVALID_CIPHER_TYPE');\n }\n if (hash == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('missing hash type', 'ERR_MISSING_HASH_TYPE');\n }\n const cipherKeySize = cipher.keySize;\n const ivSize = cipher.ivSize;\n const hmacKeySize = 20;\n const seed = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)('key expansion');\n const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize);\n const m = await _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__.create(hash, secret);\n let a = await m.digest(seed);\n const result = [];\n let j = 0;\n while (j < resultLength) {\n const b = await m.digest((0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([a, seed]));\n let todo = b.length;\n if (j + todo > resultLength) {\n todo = resultLength - j;\n }\n result.push(b);\n j += todo;\n a = await m.digest(a);\n }\n const half = resultLength / 2;\n const resultBuffer = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)(result);\n const r1 = resultBuffer.subarray(0, half);\n const r2 = resultBuffer.subarray(half, resultLength);\n const createKey = (res) => ({\n iv: res.subarray(0, ivSize),\n cipherKey: res.subarray(ivSize, ivSize + cipherKeySize),\n macKey: res.subarray(ivSize + cipherKeySize)\n });\n return {\n k1: createKey(r1),\n k2: createKey(r2)\n };\n}\n//# sourceMappingURL=key-stretcher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js": -/*!*****************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js ***! - \*****************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KeyType: () => (/* binding */ KeyType),\n/* harmony export */ PrivateKey: () => (/* binding */ PrivateKey),\n/* harmony export */ PublicKey: () => (/* binding */ PublicKey)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.enumeration)(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nvar PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nvar PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js": -/*!************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js ***! - \************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ getRandomValues: () => (/* reexport safe */ _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"]),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ keySize: () => (/* binding */ keySize),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ utils: () => (/* reexport module object */ _rsa_utils_js__WEBPACK_IMPORTED_MODULE_1__)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../random-bytes.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n\n\n\n\n\n\nasync function generateKey(bits) {\n const pair = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nasync function unmarshalPrivateKey(key) {\n const privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n\nasync function hashAndSign(key, msg) {\n const privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nasync function hashAndVerify(key, sig, msg) {\n const publicKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.exportKey('jwk', pair.privateKey),\n _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nfunction keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js": -/*!**********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js ***! - \**********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* binding */ MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* binding */ RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* binding */ RsaPublicKey),\n/* harmony export */ fromJwk: () => (/* binding */ fromJwk),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ unmarshalRsaPrivateKey: () => (/* binding */ unmarshalRsaPrivateKey),\n/* harmony export */ unmarshalRsaPublicKey: () => (/* binding */ unmarshalRsaPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n\n\n\n\n\n\n\n\nconst MAX_RSA_KEY_SIZE = 8192;\nclass RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_3__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkix(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nclass RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_7__[\"default\"](16);\n }\n sign(message) {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_3__.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkcs1(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_9__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nasync function unmarshalRsaPrivateKey(bytes) {\n const jwk = _rsa_js__WEBPACK_IMPORTED_MODULE_4__.pkcs1ToJwk(bytes);\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nfunction unmarshalRsaPublicKey(bytes) {\n const jwk = _rsa_js__WEBPACK_IMPORTED_MODULE_4__.pkixToJwk(bytes);\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nasync function fromJwk(jwk) {\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nasync function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js": -/*!**********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js ***! - \**********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ exportToPem: () => (/* binding */ exportToPem),\n/* harmony export */ importFromPem: () => (/* binding */ importFromPem),\n/* harmony export */ jwkToPkcs1: () => (/* binding */ jwkToPkcs1),\n/* harmony export */ jwkToPkix: () => (/* binding */ jwkToPkix),\n/* harmony export */ pkcs1ToJwk: () => (/* binding */ pkcs1ToJwk),\n/* harmony export */ pkixToJwk: () => (/* binding */ pkixToJwk)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @noble/hashes/pbkdf2 */ \"./node_modules/@noble/hashes/esm/pbkdf2.js\");\n/* harmony import */ var _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/@noble/hashes/esm/sha512.js\");\n/* harmony import */ var asn1js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! asn1js */ \"./node_modules/asn1js/build/index.es.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _random_bytes_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../random-bytes.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n\n\n\n\n\n\n\n\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nfunction pkcs1ToJwk(bytes) {\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nfunction jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: 0 }),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.n, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.e, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.d, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.p, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.q, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.dp, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.dq, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nfunction pkixToJwk(bytes) {\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nfunction jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // rsaEncryption\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.BitString({\n valueHex: new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.n, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nasync function exportToPem(privateKey, password) {\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // version (0)\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n }),\n // PrivateKey\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = (0,_random_bytes_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(SALT_LENGTH);\n const encryptionKey = await (0,_noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__.pbkdf2Async)(_noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__.sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = (0,_random_bytes_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // salt\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: ITERATIONS }),\n // key length\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // aes256-CBC\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...(0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nasync function importFromPem(pem, password) {\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await (0,_noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__.pbkdf2Async)(_noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__.sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return (0,_rsa_class_js__WEBPACK_IMPORTED_MODULE_8__.unmarshalRsaPrivateKey)(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js": -/*!******************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js ***! - \******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compressPublicKey: () => (/* binding */ compressPublicKey),\n/* harmony export */ computePublicKey: () => (/* binding */ computePublicKey),\n/* harmony export */ decompressPublicKey: () => (/* binding */ decompressPublicKey),\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),\n/* harmony export */ validatePrivateKey: () => (/* binding */ validatePrivateKey),\n/* harmony export */ validatePublicKey: () => (/* binding */ validatePublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/curves/secp256k1 */ \"./node_modules/@noble/curves/esm/secp256k1.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js\");\n\n\n\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\n\nfunction generateKey() {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nfunction hashAndSign(key, msg) {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_2__.isPromise)(p)) {\n return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nfunction hashAndVerify(key, sig, msg) {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_2__.isPromise)(p)) {\n return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.verify(sig, digest, key))\n .catch(err => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nfunction compressPublicKey(key) {\n const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nfunction decompressPublicKey(key) {\n const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nfunction validatePrivateKey(key) {\n try {\n _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(key, true);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nfunction validatePublicKey(key) {\n try {\n _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nfunction computePublicKey(privateKey) {\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js": -/*!****************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js ***! - \****************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Secp256k1PrivateKey: () => (/* binding */ Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* binding */ Secp256k1PublicKey),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ unmarshalSecp256k1PrivateKey: () => (/* binding */ unmarshalSecp256k1PrivateKey),\n/* harmony export */ unmarshalSecp256k1PublicKey: () => (/* binding */ unmarshalSecp256k1PublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./secp256k1.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js\");\n\n\n\n\n\n\n\n\nclass Secp256k1PublicKey {\n _key;\n constructor(key) {\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.compressPublicKey(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_4__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_4__.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n async hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n let bytes;\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_5__.isPromise)(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nclass Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.computePublicKey(key);\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePrivateKey(this._key);\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_4__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_4__.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_5__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_6__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nfunction unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nfunction unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nasync function generateKeyPair() {\n const privateKeyBytes = _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js": -/*!********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js ***! - \********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ randomBytes)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nfunction randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__.CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes)(length);\n}\n//# sourceMappingURL=random-bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/random-bytes.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js": -/*!************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64urlToBuffer: () => (/* binding */ base64urlToBuffer),\n/* harmony export */ isPromise: () => (/* binding */ isPromise)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n\n\nfunction base64urlToBuffer(str, len) {\n let buf = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/util.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js": -/*!*************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js ***! - \*************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); - -/***/ }), - /***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js": /*!*****************************************************************************************!*\ !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js ***! @@ -5529,84 +7519,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js": -/*!******************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js ***! - \******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Envelope: () => (/* binding */ Envelope)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.payloadType = reader.bytes();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n case 5:\n obj.signature = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, Envelope.codec());\n };\n Envelope.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, Envelope.codec());\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/index.js": -/*!***************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/index.js ***! - \***************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RecordEnvelope: () => (/* binding */ RecordEnvelope)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/errors.js\");\n/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./envelope.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js\");\n\n\n\n\n\n\n\n\n\nclass RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.decode(data);\n const peerId = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__.peerIdFromKeys)(envelopeData.publicKey);\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, peerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPrivateKey)(peerId.privateKey);\n const signature = await key.sign(signData.subarray());\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError('envelope signature is not valid for the given domain', _errors_js__WEBPACK_IMPORTED_MODULE_8__.codes.ERR_SIGNATURE_NOT_VALID);\n }\n return envelope;\n };\n peerId;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { peerId, payloadType, payload, signature } = init;\n this.peerId = peerId;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n if (this.marshaled == null) {\n this.marshaled = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n const key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPublicKey)(this.peerId.publicKey);\n return key.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(domain);\n const domainLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(domainUint8Array.byteLength);\n const payloadTypeLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payloadType.length);\n const payloadLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payload.length);\n return new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/envelope/index.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/errors.js": -/*!*******************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/errors.js ***! - \*******************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ codes: () => (/* binding */ codes)\n/* harmony export */ });\nconst codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n};\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/errors.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js": -/*!*******************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js ***! - \*******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ENVELOPE_DOMAIN_PEER_RECORD: () => (/* binding */ ENVELOPE_DOMAIN_PEER_RECORD),\n/* harmony export */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD: () => (/* binding */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD)\n/* harmony export */ });\n// The domain string used for peer records contained in a Envelope.\nconst ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nconst ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js": -/*!******************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js ***! - \******************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/utils/array-equals */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/utils/dist/src/array-equals.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _consts_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./consts.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js\");\n/* harmony import */ var _peer_record_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peer-record.js */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js\");\n\n\n\n\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nclass PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.decode(buf);\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromBytes)(peerRecord.peerId);\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!(0,_libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__.arrayEquals)(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js": -/*!************************************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js ***! - \************************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, AddressInfo.codec());\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes();\n break;\n case 2:\n obj.seq = reader.uint64();\n break;\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()));\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PeerRecord.codec());\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js?"); - -/***/ }), - -/***/ "./node_modules/@libp2p/identify/node_modules/@libp2p/utils/dist/src/array-equals.js": -/*!*******************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/@libp2p/utils/dist/src/array-equals.js ***! - \*******************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ arrayEquals: () => (/* binding */ arrayEquals)\n/* harmony export */ });\n/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nfunction arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/utils/dist/src/array-equals.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/identify/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -5617,7 +7530,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -5661,7 +7574,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -5782,7 +7695,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -5826,7 +7739,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -5951,17 +7864,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js": -/*!***********************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js ***! - \***********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ concat: () => (/* binding */ concat)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nfunction concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(output);\n}\n//# sourceMappingURL=concat.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/concat.js?"); - -/***/ }), - /***/ "./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js": /*!***********************************************************************************!*\ !*** ./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/equals.js ***! @@ -5995,17 +7897,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/as-uint8array.js": -/*!***********************************************************************************************!*\ - !*** ./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/as-uint8array.js ***! - \***********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ asUint8Array: () => (/* binding */ asUint8Array)\n/* harmony export */ });\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nfunction asUint8Array(buf) {\n return buf;\n}\n//# sourceMappingURL=as-uint8array.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/as-uint8array.js?"); - -/***/ }), - /***/ "./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/bases.js": /*!***************************************************************************************!*\ !*** ./node_modules/@libp2p/identify/node_modules/uint8arrays/dist/src/util/bases.js ***! @@ -6061,6 +7952,94 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/logger/dist/src/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/@libp2p/logger/dist/src/index.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ defaultLogger: () => (/* binding */ defaultLogger),\n/* harmony export */ disable: () => (/* binding */ disable),\n/* harmony export */ enable: () => (/* binding */ enable),\n/* harmony export */ enabled: () => (/* binding */ enabled),\n/* harmony export */ logger: () => (/* binding */ logger),\n/* harmony export */ peerLogger: () => (/* binding */ peerLogger),\n/* harmony export */ prefixLogger: () => (/* binding */ prefixLogger)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var weald__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! weald */ \"./node_modules/weald/dist/src/index.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@libp2p/logger/dist/src/utils.js\");\n/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\n\n\n\n\n// Add a formatter for converting to a base58 string\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.b = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_1__.base58btc.baseEncode(v);\n};\n// Add a formatter for converting to a base32 string\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.t = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_0__.base32.baseEncode(v);\n};\n// Add a formatter for converting to a base64 string\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.m = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_2__.base64.baseEncode(v);\n};\n// Add a formatter for stringifying peer ids\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.p = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying CIDs\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.c = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Datastore keys\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.k = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Multiaddrs\nweald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].formatters.a = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\nfunction createDisabledLogger(namespace) {\n const logger = () => { };\n logger.enabled = false;\n logger.color = '';\n logger.diff = 0;\n logger.log = () => { };\n logger.namespace = namespace;\n logger.destroy = () => true;\n logger.extend = () => logger;\n return logger;\n}\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nfunction peerLogger(peerId, options = {}) {\n return prefixLogger((0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.truncatePeerId)(peerId, options));\n}\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nfunction prefixLogger(prefix) {\n return {\n forComponent(name) {\n return logger(`${prefix}:${name}`);\n }\n };\n}\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nfunction defaultLogger() {\n return {\n forComponent(name) {\n return logger(name);\n }\n };\n}\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nfunction logger(name) {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`);\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].enabled(`${name}:trace`) && weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].names.map((r) => r.toString()).find((n) => n.includes(':trace')) != null) {\n trace = (0,weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(`${name}:trace`);\n }\n return Object.assign((0,weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(name), {\n error: (0,weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(`${name}:error`),\n trace\n });\n}\nfunction disable() {\n weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].disable();\n}\nfunction enable(namespaces) {\n weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].enable(namespaces);\n}\nfunction enabled(namespaces) {\n return weald__WEBPACK_IMPORTED_MODULE_3__[\"default\"].enabled(namespaces);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/dist/src/utils.js": +/*!*******************************************************!*\ + !*** ./node_modules/@libp2p/logger/dist/src/utils.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ truncatePeerId: () => (/* binding */ truncatePeerId)\n/* harmony export */ });\nfunction truncatePeerId(peerId, options = {}) {\n const prefixLength = options.prefixLength ?? 2;\n const suffixLength = options.suffixLength ?? 4;\n const peerIdString = peerId.toString();\n return `${peerIdString.substring(0, prefixLength)}…${peerIdString.substring(peerIdString.length, peerIdString.length - suffixLength)}`;\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/dist/src/utils.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base32.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base32.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base32: () => (/* binding */ base32),\n/* harmony export */ base32hex: () => (/* binding */ base32hex),\n/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),\n/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),\n/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),\n/* harmony export */ base32pad: () => (/* binding */ base32pad),\n/* harmony export */ base32padupper: () => (/* binding */ base32padupper),\n/* harmony export */ base32upper: () => (/* binding */ base32upper),\n/* harmony export */ base32z: () => (/* binding */ base32z)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nconst base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nconst base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nconst base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nconst base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nconst base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nconst base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nconst base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nconst base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base32.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base58.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base58.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base58btc: () => (/* binding */ base58btc),\n/* harmony export */ base58flickr: () => (/* binding */ base58flickr)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nconst base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base58.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base64.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base64.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64pad: () => (/* binding */ base64pad),\n/* harmony export */ base64url: () => (/* binding */ base64url),\n/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nconst base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nconst base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nconst base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bases/base64.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bytes.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bytes.js ***! + \*********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ empty: () => (/* binding */ empty),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ fromHex: () => (/* binding */ fromHex),\n/* harmony export */ fromString: () => (/* binding */ fromString),\n/* harmony export */ isBinary: () => (/* binding */ isBinary),\n/* harmony export */ toHex: () => (/* binding */ toHex),\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\nconst empty = new Uint8Array(0);\nfunction toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nfunction fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nfunction equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nfunction coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nfunction isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nfunction fromString(str) {\n return new TextEncoder().encode(str);\n}\nfunction toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/vendor/base-x.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/vendor/base-x.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);\n//# sourceMappingURL=base-x.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/logger/node_modules/multiformats/dist/src/vendor/base-x.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/mplex/dist/src/decode.js": /*!*******************************************************!*\ !*** ./node_modules/@libp2p/mplex/dist/src/decode.js ***! @@ -6090,7 +8069,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ mplex: () => (/* binding */ mplex)\n/* harmony export */ });\n/* harmony import */ var _mplex_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mplex.js */ \"./node_modules/@libp2p/mplex/dist/src/mplex.js\");\n/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\n\nclass Mplex {\n protocol = '/mplex/6.7.0';\n _init;\n components;\n constructor(components, init = {}) {\n this.components = components;\n this._init = init;\n }\n createStreamMuxer(init = {}) {\n return new _mplex_js__WEBPACK_IMPORTED_MODULE_0__.MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n });\n }\n}\nfunction mplex(init = {}) {\n return (components) => new Mplex(components, init);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ mplex: () => (/* binding */ mplex)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/index.js\");\n/* harmony import */ var _mplex_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mplex.js */ \"./node_modules/@libp2p/mplex/dist/src/mplex.js\");\n/**\n * @packageDocumentation\n *\n * This is a [simple stream multiplexer(https://docs.libp2p.io/concepts/multiplex/mplex/) that has been deprecated.\n *\n * Please use [@chainsafe/libp2p-yamux](https://www.npmjs.com/package/@chainsafe/libp2p-yamux) instead.\n *\n * @example\n *\n * ```TypeScript\n * import { mplex } from '@libp2p/mplex'\n * import { pipe } from 'it-pipe'\n *\n * const factory = mplex()\n *\n * const muxer = factory.createStreamMuxer(components, {\n * onStream: stream => { // Receive a duplex stream from the remote\n * // ...receive data from the remote and optionally send data back\n * },\n * onStreamEnd: stream => {\n * // ...handle any tracking you may need of stream closures\n * }\n * })\n *\n * pipe(conn, muxer, conn) // conn is duplex connection to another peer\n *\n * const stream = muxer.newStream() // Create a new duplex stream to the remote\n *\n * // Use the duplex stream to send some data to the remote...\n * pipe([1, 2, 3], stream)\n * ```\n */\n\n\nclass Mplex {\n protocol = '/mplex/6.7.0';\n _init;\n components;\n constructor(components, init = {}) {\n this.components = components;\n this._init = init;\n }\n [Symbol.toStringTag] = '@libp2p/mplex';\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_0__.serviceCapabilities] = [\n '@libp2p/stream-multiplexing'\n ];\n createStreamMuxer(init = {}) {\n return new _mplex_js__WEBPACK_IMPORTED_MODULE_1__.MplexStreamMuxer(this.components, {\n ...init,\n ...this._init\n });\n }\n}\nfunction mplex(init = {}) {\n return (components) => new Mplex(components, init);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/index.js?"); /***/ }), @@ -6112,7 +8091,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MplexStreamMuxer: () => (/* binding */ MplexStreamMuxer)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_utils_close_source__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/utils/close-source */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/close-source.js\");\n/* harmony import */ var _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/utils/rate-limiter */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/rate-limiter.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var uint8arrays__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/index.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/@libp2p/mplex/dist/src/decode.js\");\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/@libp2p/mplex/dist/src/encode.js\");\n/* harmony import */ var _message_types_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./message-types.js */ \"./node_modules/@libp2p/mplex/dist/src/message-types.js\");\n/* harmony import */ var _stream_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./stream.js */ \"./node_modules/@libp2p/mplex/dist/src/stream.js\");\n\n\n\n\n\n\n\n\n\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB\nconst DISCONNECT_THRESHOLD = 5;\nconst CLOSE_TIMEOUT = 500;\nfunction printMessage(msg) {\n const output = {\n ...msg,\n type: `${_message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypeNames[msg.type]} (${msg.type})`\n };\n if (msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.NEW_STREAM) {\n output.data = (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray());\n }\n if (msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR || msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_RECEIVER) {\n output.data = (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16');\n }\n return output;\n}\nclass MplexStreamMuxer {\n protocol = '/mplex/6.7.0';\n sink;\n source;\n log;\n _streamId;\n _streams;\n _init;\n _source;\n closeController;\n rateLimiter;\n closeTimeout;\n logger;\n constructor(components, init) {\n init = init ?? {};\n this.log = components.logger.forComponent('libp2p:mplex');\n this.logger = components.logger;\n this._streamId = 0;\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n };\n this._init = init;\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT;\n /**\n * An iterable sink\n */\n this.sink = this._createSink();\n /**\n * An iterable source\n */\n this._source = (0,it_pushable__WEBPACK_IMPORTED_MODULE_1__.pushable)({\n objectMode: true,\n onEnd: () => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy();\n }\n for (const stream of this._streams.receivers.values()) {\n stream.destroy();\n }\n }\n });\n this.source = (0,it_pipe__WEBPACK_IMPORTED_MODULE_0__.pipe)(this._source, source => (0,_encode_js__WEBPACK_IMPORTED_MODULE_4__.encode)(source));\n /**\n * Close controller\n */\n this.closeController = new AbortController();\n this.rateLimiter = new _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_5__.RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n });\n }\n /**\n * Returns a Map of streams and their ids\n */\n get streams() {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams = [];\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream);\n }\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream);\n }\n return streams;\n }\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream(name) {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed');\n }\n const id = this._streamId++;\n name = name == null ? id.toString() : name.toString();\n const registry = this._streams.initiators;\n return this._newStream({ id, name, type: 'initiator', registry });\n }\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close(options) {\n if (this.closeController.signal.aborted) {\n return;\n }\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout);\n try {\n // try to gracefully close all streams\n await Promise.all(this.streams.map(async (s) => s.close({\n signal\n })));\n this._source.end();\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n });\n this.closeController.abort();\n }\n catch (err) {\n this.abort(err);\n }\n }\n abort(err) {\n if (this.closeController.signal.aborted) {\n return;\n }\n this.streams.forEach(s => { s.abort(err); });\n this.closeController.abort(err);\n }\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream(options) {\n const { id, name } = options;\n const registry = this._streams.receivers;\n return this._newStream({ id, name, type: 'receiver', registry });\n }\n _newStream(options) {\n const { id, name, type, registry } = options;\n this.log('new %s stream %s', type, id);\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS');\n }\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`);\n }\n const send = async (msg) => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg));\n }\n this._source.push(msg);\n };\n const onEnd = () => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);\n registry.delete(id);\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream);\n }\n };\n const stream = (0,_stream_js__WEBPACK_IMPORTED_MODULE_7__.createStream)({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });\n registry.set(id, stream);\n return stream;\n }\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink() {\n const sink = async (source) => {\n const abortListener = () => {\n (0,_libp2p_utils_close_source__WEBPACK_IMPORTED_MODULE_8__.closeSource)(source, this.log);\n };\n this.closeController.signal.addEventListener('abort', abortListener);\n try {\n const decoder = new _decode_js__WEBPACK_IMPORTED_MODULE_9__.Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg);\n }\n }\n this._source.end();\n }\n catch (err) {\n this.log('error in sink', err);\n this._source.end(err); // End the source with an error\n }\n finally {\n this.closeController.signal.removeEventListener('abort', abortListener);\n }\n };\n return sink;\n }\n async _handleIncoming(message) {\n const { id, type } = message;\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message));\n }\n // Create a new stream?\n if (message.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open');\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER\n });\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1);\n }\n catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'));\n return;\n }\n return;\n }\n const stream = this._newReceiverStream({ id, name: (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(message.data instanceof Uint8Array ? message.data : message.data.subarray()) });\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream);\n }\n return;\n }\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;\n const stream = list.get(id);\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypeNames[type]);\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1);\n }\n catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'));\n return;\n }\n return;\n }\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE;\n try {\n switch (type) {\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR ? _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER : _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_INITIATOR\n });\n // Inform the stream consumer they are not fast enough\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL');\n }\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data);\n break;\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.CLOSE_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite();\n break;\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset();\n break;\n default:\n this.log('unknown message type %s', type);\n }\n }\n catch (err) {\n this.log.error('error while processing message', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=mplex.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/mplex.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MplexStreamMuxer: () => (/* binding */ MplexStreamMuxer)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_utils_close_source__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/utils/close-source */ \"./node_modules/@libp2p/utils/dist/src/close-source.js\");\n/* harmony import */ var _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/utils/rate-limiter */ \"./node_modules/@libp2p/utils/dist/src/rate-limiter.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var uint8arrays__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/index.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/@libp2p/mplex/dist/src/decode.js\");\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/@libp2p/mplex/dist/src/encode.js\");\n/* harmony import */ var _message_types_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./message-types.js */ \"./node_modules/@libp2p/mplex/dist/src/message-types.js\");\n/* harmony import */ var _stream_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./stream.js */ \"./node_modules/@libp2p/mplex/dist/src/stream.js\");\n\n\n\n\n\n\n\n\n\n\nconst MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION = 1024;\nconst MAX_STREAM_BUFFER_SIZE = 1024 * 1024 * 4; // 4MB\nconst DISCONNECT_THRESHOLD = 5;\nconst CLOSE_TIMEOUT = 500;\nfunction printMessage(msg) {\n const output = {\n ...msg,\n type: `${_message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypeNames[msg.type]} (${msg.type})`\n };\n if (msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.NEW_STREAM) {\n output.data = (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray());\n }\n if (msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR || msg.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_RECEIVER) {\n output.data = (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(msg.data instanceof Uint8Array ? msg.data : msg.data.subarray(), 'base16');\n }\n return output;\n}\nclass MplexStreamMuxer {\n protocol = '/mplex/6.7.0';\n sink;\n source;\n log;\n _streamId;\n _streams;\n _init;\n _source;\n closeController;\n rateLimiter;\n closeTimeout;\n logger;\n constructor(components, init) {\n init = init ?? {};\n this.log = components.logger.forComponent('libp2p:mplex');\n this.logger = components.logger;\n this._streamId = 0;\n this._streams = {\n /**\n * Stream to ids map\n */\n initiators: new Map(),\n /**\n * Stream to ids map\n */\n receivers: new Map()\n };\n this._init = init;\n this.closeTimeout = init.closeTimeout ?? CLOSE_TIMEOUT;\n /**\n * An iterable sink\n */\n this.sink = this._createSink();\n /**\n * An iterable source\n */\n this._source = (0,it_pushable__WEBPACK_IMPORTED_MODULE_1__.pushable)({\n objectMode: true,\n onEnd: () => {\n // the source has ended, we can't write any more messages to gracefully\n // close streams so all we can do is destroy them\n for (const stream of this._streams.initiators.values()) {\n stream.destroy();\n }\n for (const stream of this._streams.receivers.values()) {\n stream.destroy();\n }\n }\n });\n this.source = (0,it_pipe__WEBPACK_IMPORTED_MODULE_0__.pipe)(this._source, source => (0,_encode_js__WEBPACK_IMPORTED_MODULE_4__.encode)(source));\n /**\n * Close controller\n */\n this.closeController = new AbortController();\n this.rateLimiter = new _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_5__.RateLimiter({\n points: init.disconnectThreshold ?? DISCONNECT_THRESHOLD,\n duration: 1\n });\n }\n /**\n * Returns a Map of streams and their ids\n */\n get streams() {\n // Inbound and Outbound streams may have the same ids, so we need to make those unique\n const streams = [];\n for (const stream of this._streams.initiators.values()) {\n streams.push(stream);\n }\n for (const stream of this._streams.receivers.values()) {\n streams.push(stream);\n }\n return streams;\n }\n /**\n * Initiate a new stream with the given name. If no name is\n * provided, the id of the stream will be used.\n */\n newStream(name) {\n if (this.closeController.signal.aborted) {\n throw new Error('Muxer already closed');\n }\n const id = this._streamId++;\n name = name == null ? id.toString() : name.toString();\n const registry = this._streams.initiators;\n return this._newStream({ id, name, type: 'initiator', registry });\n }\n /**\n * Close or abort all tracked streams and stop the muxer\n */\n async close(options) {\n if (this.closeController.signal.aborted) {\n return;\n }\n const signal = options?.signal ?? AbortSignal.timeout(this.closeTimeout);\n try {\n // try to gracefully close all streams\n await Promise.all(this.streams.map(async (s) => s.close({\n signal\n })));\n this._source.end();\n // try to gracefully close the muxer\n await this._source.onEmpty({\n signal\n });\n this.closeController.abort();\n }\n catch (err) {\n this.abort(err);\n }\n }\n abort(err) {\n if (this.closeController.signal.aborted) {\n return;\n }\n this.streams.forEach(s => { s.abort(err); });\n this.closeController.abort(err);\n }\n /**\n * Called whenever an inbound stream is created\n */\n _newReceiverStream(options) {\n const { id, name } = options;\n const registry = this._streams.receivers;\n return this._newStream({ id, name, type: 'receiver', registry });\n }\n _newStream(options) {\n const { id, name, type, registry } = options;\n this.log('new %s stream %s', type, id);\n if (type === 'initiator' && this._streams.initiators.size === (this._init.maxOutboundStreams ?? MAX_STREAMS_OUTBOUND_STREAMS_PER_CONNECTION)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Too many outbound streams open', 'ERR_TOO_MANY_OUTBOUND_STREAMS');\n }\n if (registry.has(id)) {\n throw new Error(`${type} stream ${id} already exists!`);\n }\n const send = async (msg) => {\n if (this.log.enabled) {\n this.log.trace('%s stream %s send', type, id, printMessage(msg));\n }\n this._source.push(msg);\n };\n const onEnd = () => {\n this.log('%s stream with id %s and protocol %s ended', type, id, stream.protocol);\n registry.delete(id);\n if (this._init.onStreamEnd != null) {\n this._init.onStreamEnd(stream);\n }\n };\n const stream = (0,_stream_js__WEBPACK_IMPORTED_MODULE_7__.createStream)({ id, name, send, type, onEnd, maxMsgSize: this._init.maxMsgSize, logger: this.logger });\n registry.set(id, stream);\n return stream;\n }\n /**\n * Creates a sink with an abortable source. Incoming messages will\n * also have their size restricted. All messages will be varint decoded.\n */\n _createSink() {\n const sink = async (source) => {\n const abortListener = () => {\n (0,_libp2p_utils_close_source__WEBPACK_IMPORTED_MODULE_8__.closeSource)(source, this.log);\n };\n this.closeController.signal.addEventListener('abort', abortListener);\n try {\n const decoder = new _decode_js__WEBPACK_IMPORTED_MODULE_9__.Decoder(this._init.maxMsgSize, this._init.maxUnprocessedMessageQueueSize);\n for await (const chunk of source) {\n for (const msg of decoder.write(chunk)) {\n await this._handleIncoming(msg);\n }\n }\n this._source.end();\n }\n catch (err) {\n this.log('error in sink', err);\n this._source.end(err); // End the source with an error\n }\n finally {\n this.closeController.signal.removeEventListener('abort', abortListener);\n }\n };\n return sink;\n }\n async _handleIncoming(message) {\n const { id, type } = message;\n if (this.log.enabled) {\n this.log.trace('incoming message', printMessage(message));\n }\n // Create a new stream?\n if (message.type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.NEW_STREAM) {\n if (this._streams.receivers.size === (this._init.maxInboundStreams ?? MAX_STREAMS_INBOUND_STREAMS_PER_CONNECTION)) {\n this.log('too many inbound streams open');\n // not going to allow this stream, send the reset message manually\n // instead of setting it up just to tear it down\n this._source.push({\n id,\n type: _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER\n });\n // if we've hit our stream limit, and the remote keeps trying to open\n // more new streams, if they are doing this very quickly maybe they\n // are attacking us and we should close the connection\n try {\n await this.rateLimiter.consume('new-stream', 1);\n }\n catch {\n this.log('rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many open streams'));\n return;\n }\n return;\n }\n const stream = this._newReceiverStream({ id, name: (0,uint8arrays__WEBPACK_IMPORTED_MODULE_2__.toString)(message.data instanceof Uint8Array ? message.data : message.data.subarray()) });\n if (this._init.onIncomingStream != null) {\n this._init.onIncomingStream(stream);\n }\n return;\n }\n const list = (type & 1) === 1 ? this._streams.initiators : this._streams.receivers;\n const stream = list.get(id);\n if (stream == null) {\n this.log('missing stream %s for message type %s', id, _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypeNames[type]);\n // if the remote keeps sending us messages for streams that have been\n // closed or were never opened they may be attacking us so if they do\n // this very quickly all we can do is close the connection\n try {\n await this.rateLimiter.consume('missing-stream', 1);\n }\n catch {\n this.log('rate limit hit when receiving messages for streams that do not exist - closing remote connection');\n // since there's no backpressure in mplex, the only thing we can really do to protect ourselves is close the connection\n this.abort(new Error('Too many messages for missing streams'));\n return;\n }\n return;\n }\n const maxBufferSize = this._init.maxStreamBufferSize ?? MAX_STREAM_BUFFER_SIZE;\n try {\n switch (type) {\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_RECEIVER:\n if (stream.sourceReadableLength() > maxBufferSize) {\n // Stream buffer has got too large, reset the stream\n this._source.push({\n id: message.id,\n type: type === _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.MESSAGE_INITIATOR ? _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER : _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_INITIATOR\n });\n // Inform the stream consumer they are not fast enough\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers', 'ERR_STREAM_INPUT_BUFFER_FULL');\n }\n // We got data from the remote, push it into our local stream\n stream.sourcePush(message.data);\n break;\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.CLOSE_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.CLOSE_RECEIVER:\n // The remote has stopped writing, so we can stop reading\n stream.remoteCloseWrite();\n break;\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_INITIATOR:\n case _message_types_js__WEBPACK_IMPORTED_MODULE_3__.MessageTypes.RESET_RECEIVER:\n // The remote has errored, stop reading and writing to the stream immediately\n stream.reset();\n break;\n default:\n this.log('unknown message type %s', type);\n }\n }\n catch (err) {\n this.log.error('error while processing message', err);\n stream.abort(err);\n }\n }\n}\n//# sourceMappingURL=mplex.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/mplex.js?"); /***/ }), @@ -6123,7 +8102,29 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MplexStream: () => (/* binding */ MplexStream),\n/* harmony export */ createStream: () => (/* binding */ createStream)\n/* harmony export */ });\n/* harmony import */ var _libp2p_utils_abstract_stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/utils/abstract-stream */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/abstract-stream.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/@libp2p/mplex/dist/src/decode.js\");\n/* harmony import */ var _message_types_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./message-types.js */ \"./node_modules/@libp2p/mplex/dist/src/message-types.js\");\n\n\n\n\n\nclass MplexStream extends _libp2p_utils_abstract_stream__WEBPACK_IMPORTED_MODULE_2__.AbstractStream {\n name;\n streamId;\n send;\n types;\n maxDataSize;\n constructor(init) {\n super(init);\n this.types = init.direction === 'outbound' ? _message_types_js__WEBPACK_IMPORTED_MODULE_3__.InitiatorMessageTypes : _message_types_js__WEBPACK_IMPORTED_MODULE_3__.ReceiverMessageTypes;\n this.send = init.send;\n this.name = init.name;\n this.streamId = init.streamId;\n this.maxDataSize = init.maxDataSize;\n }\n async sendNewStream() {\n await this.send({ id: this.streamId, type: _message_types_js__WEBPACK_IMPORTED_MODULE_3__.InitiatorMessageTypes.NEW_STREAM, data: new uint8arraylist__WEBPACK_IMPORTED_MODULE_0__.Uint8ArrayList((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(this.name)) });\n }\n async sendData(data) {\n data = data.sublist();\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize);\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n });\n data.consume(toSend);\n }\n }\n async sendReset() {\n await this.send({ id: this.streamId, type: this.types.RESET });\n }\n async sendCloseWrite() {\n await this.send({ id: this.streamId, type: this.types.CLOSE });\n }\n async sendCloseRead() {\n // mplex does not support close read, only close write\n }\n}\nfunction createStream(options) {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = _decode_js__WEBPACK_IMPORTED_MODULE_4__.MAX_MSG_SIZE } = options;\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name == null ? id : name}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n });\n}\n//# sourceMappingURL=stream.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/stream.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MplexStream: () => (/* binding */ MplexStream),\n/* harmony export */ createStream: () => (/* binding */ createStream)\n/* harmony export */ });\n/* harmony import */ var _libp2p_utils_abstract_stream__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/utils/abstract-stream */ \"./node_modules/@libp2p/utils/dist/src/abstract-stream.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/@libp2p/mplex/dist/src/decode.js\");\n/* harmony import */ var _message_types_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./message-types.js */ \"./node_modules/@libp2p/mplex/dist/src/message-types.js\");\n\n\n\n\n\nclass MplexStream extends _libp2p_utils_abstract_stream__WEBPACK_IMPORTED_MODULE_2__.AbstractStream {\n name;\n streamId;\n send;\n types;\n maxDataSize;\n constructor(init) {\n super(init);\n this.types = init.direction === 'outbound' ? _message_types_js__WEBPACK_IMPORTED_MODULE_3__.InitiatorMessageTypes : _message_types_js__WEBPACK_IMPORTED_MODULE_3__.ReceiverMessageTypes;\n this.send = init.send;\n this.name = init.name;\n this.streamId = init.streamId;\n this.maxDataSize = init.maxDataSize;\n }\n async sendNewStream() {\n await this.send({ id: this.streamId, type: _message_types_js__WEBPACK_IMPORTED_MODULE_3__.InitiatorMessageTypes.NEW_STREAM, data: new uint8arraylist__WEBPACK_IMPORTED_MODULE_0__.Uint8ArrayList((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(this.name)) });\n }\n async sendData(data) {\n data = data.sublist();\n while (data.byteLength > 0) {\n const toSend = Math.min(data.byteLength, this.maxDataSize);\n await this.send({\n id: this.streamId,\n type: this.types.MESSAGE,\n data: data.sublist(0, toSend)\n });\n data.consume(toSend);\n }\n }\n async sendReset() {\n await this.send({ id: this.streamId, type: this.types.RESET });\n }\n async sendCloseWrite() {\n await this.send({ id: this.streamId, type: this.types.CLOSE });\n }\n async sendCloseRead() {\n // mplex does not support close read, only close write\n }\n}\nfunction createStream(options) {\n const { id, name, send, onEnd, type = 'initiator', maxMsgSize = _decode_js__WEBPACK_IMPORTED_MODULE_4__.MAX_MSG_SIZE } = options;\n return new MplexStream({\n id: type === 'initiator' ? (`i${id}`) : `r${id}`,\n streamId: id,\n name: `${name ?? id}`,\n direction: type === 'initiator' ? 'outbound' : 'inbound',\n maxDataSize: maxMsgSize,\n onEnd,\n send,\n log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`)\n });\n}\n//# sourceMappingURL=stream.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/dist/src/stream.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/connection/index.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/connection/index.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ connectionSymbol: () => (/* binding */ connectionSymbol),\n/* harmony export */ isConnection: () => (/* binding */ isConnection)\n/* harmony export */ });\nconst connectionSymbol = Symbol.for('@libp2p/connection');\nfunction isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/connection/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/content-routing/index.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/content-routing/index.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ contentRoutingSymbol: () => (/* binding */ contentRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/content-routing/index.js?"); /***/ }), @@ -6138,47 +8139,135 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/abstract-stream.js": -/*!*******************************************************************************************!*\ - !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/abstract-stream.js ***! - \*******************************************************************************************/ +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/event-target.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/event-target.js ***! + \********************************************************************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbstractStream: () => (/* binding */ AbstractStream)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _close_source_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./close-source.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/close-source.js\");\n\n\n\n\n\n\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET';\nconst ERR_SINK_INVALID_STATE = 'ERR_SINK_INVALID_STATE';\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000;\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\nclass AbstractStream {\n id;\n direction;\n timeline;\n protocol;\n metadata;\n source;\n status;\n readStatus;\n writeStatus;\n log;\n sinkController;\n sinkEnd;\n closed;\n endErr;\n streamSource;\n onEnd;\n onCloseRead;\n onCloseWrite;\n onReset;\n onAbort;\n sendCloseWriteTimeout;\n sendingData;\n constructor(init) {\n this.sinkController = new AbortController();\n this.sinkEnd = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n this.closed = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n this.log = init.log;\n // stream status\n this.status = 'open';\n this.readStatus = 'ready';\n this.writeStatus = 'ready';\n this.id = init.id;\n this.metadata = init.metadata ?? {};\n this.direction = init.direction;\n this.timeline = {\n open: Date.now()\n };\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT;\n this.onEnd = init.onEnd;\n this.onCloseRead = init?.onCloseRead;\n this.onCloseWrite = init?.onCloseWrite;\n this.onReset = init?.onReset;\n this.onAbort = init?.onAbort;\n this.source = this.streamSource = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err);\n }\n else {\n this.log.trace('source ended');\n }\n this.onSourceEnd(err);\n }\n });\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this);\n }\n async sink(source) {\n if (this.writeStatus !== 'ready') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`writable end state is \"${this.writeStatus}\" not \"ready\"`, ERR_SINK_INVALID_STATE);\n }\n try {\n this.writeStatus = 'writing';\n const options = {\n signal: this.sinkController.signal\n };\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options);\n if (isPromise(res)) {\n await res;\n }\n }\n const abortListener = () => {\n (0,_close_source_js__WEBPACK_IMPORTED_MODULE_5__.closeSource)(source, this.log);\n };\n try {\n this.sinkController.signal.addEventListener('abort', abortListener);\n this.log.trace('sink reading from source');\n for await (let data of source) {\n data = data instanceof Uint8Array ? new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(data) : data;\n const res = this.sendData(data, options);\n if (isPromise(res)) {\n this.sendingData = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n await res;\n this.sendingData.resolve();\n this.sendingData = undefined;\n }\n }\n }\n finally {\n this.sinkController.signal.removeEventListener('abort', abortListener);\n }\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus);\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing';\n this.log.trace('send close write to remote');\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n });\n this.writeStatus = 'closed';\n }\n this.onSinkEnd();\n }\n catch (err) {\n this.log.trace('sink ended with error, calling abort with error', err);\n this.abort(err);\n throw err;\n }\n finally {\n this.log.trace('resolve sink end');\n this.sinkEnd.resolve();\n }\n }\n onSourceEnd(err) {\n if (this.timeline.closeRead != null) {\n return;\n }\n this.timeline.closeRead = Date.now();\n this.readStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseRead?.();\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('source ended, waiting for sink to end');\n }\n }\n onSinkEnd(err) {\n if (this.timeline.closeWrite != null) {\n return;\n }\n this.timeline.closeWrite = Date.now();\n this.writeStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseWrite?.();\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('sink ended, waiting for source to end');\n }\n }\n // Close for both Reading and Writing\n async close(options) {\n this.log.trace('closing gracefully');\n this.status = 'closing';\n // wait for read and write ends to close\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal);\n this.status = 'closed';\n this.log.trace('closed gracefully');\n }\n async closeRead(options = {}) {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return;\n }\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus);\n const readStatus = this.readStatus;\n this.readStatus = 'closing';\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote');\n await this.sendCloseRead(options);\n }\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength);\n this.streamSource.end();\n }\n this.log.trace('closed readable end of stream');\n }\n async closeWrite(options = {}) {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return;\n }\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus);\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array');\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sink([]), options.signal);\n }\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sendingData.promise, options.signal);\n }\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink');\n this.sinkController.abort();\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sinkEnd.promise, options.signal);\n }\n this.writeStatus = 'closed';\n this.log.trace('closed writable end of stream');\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n this.log('abort with error', err);\n // try to send a reset message\n this.log('try to send reset to remote');\n const res = this.sendReset();\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err);\n });\n }\n this.status = 'aborted';\n this.timeline.abort = Date.now();\n this._closeSinkAndSource(err);\n this.onAbort?.(err);\n }\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('stream reset', ERR_STREAM_RESET);\n this.status = 'reset';\n this.timeline.reset = Date.now();\n this._closeSinkAndSource(err);\n this.onReset?.();\n }\n _closeSinkAndSource(err) {\n this._closeSink(err);\n this._closeSource(err);\n }\n _closeSink(err) {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source');\n this.sinkController.abort();\n }\n this.onSinkEnd(err);\n }\n _closeSource(err) {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength);\n this.readStatus = 'closing';\n this.streamSource.end(err);\n }\n }\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite() {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed');\n return;\n }\n this.log.trace('remote close write');\n this._closeSource();\n }\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead() {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed');\n return;\n }\n this.log.trace('remote close read');\n this._closeSink();\n }\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed');\n return;\n }\n this.log.trace('stream destroyed');\n this._closeSinkAndSource();\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush(data) {\n this.streamSource.push(data);\n }\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength() {\n return this.streamSource.readableLength;\n }\n}\n//# sourceMappingURL=abstract-stream.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/abstract-stream.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/event-target.js?"); /***/ }), -/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/close-source.js": -/*!****************************************************************************************!*\ - !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/close-source.js ***! - \****************************************************************************************/ +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.browser.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.browser.js ***! + \**********************************************************************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ closeSource: () => (/* binding */ closeSource)\n/* harmony export */ });\n/* harmony import */ var get_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! get-iterator */ \"./node_modules/get-iterator/dist/src/index.js\");\n/* harmony import */ var _is_promise_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./is-promise.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/is-promise.js\");\n\n\nfunction closeSource(source, log) {\n const res = (0,get_iterator__WEBPACK_IMPORTED_MODULE_0__.getIterator)(source).return?.();\n if ((0,_is_promise_js__WEBPACK_IMPORTED_MODULE_1__.isPromise)(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err);\n });\n }\n}\n//# sourceMappingURL=close-source.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/close-source.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/** Noop for browser compatibility */\nfunction setMaxListeners() { }\n//# sourceMappingURL=events.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.browser.js?"); /***/ }), -/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/is-promise.js": +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.js": /*!**************************************************************************************!*\ - !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/is-promise.js ***! + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.js ***! \**************************************************************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPromise: () => (/* binding */ isPromise)\n/* harmony export */ });\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=is-promise.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/is-promise.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.browser.js\");\n\n// create a setMaxListeners that doesn't break browser usage\nconst setMaxListeners = (n, ...eventTargets) => {\n try {\n (0,events__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(n, ...eventTargets);\n }\n catch {\n // swallow error, gulp\n }\n};\n//# sourceMappingURL=events.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.js?"); /***/ }), -/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/rate-limiter.js": -/*!****************************************************************************************!*\ - !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/rate-limiter.js ***! - \****************************************************************************************/ +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/index.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/index.js ***! + \*************************************************************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RateLimiter: () => (/* binding */ RateLimiter)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var delay__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! delay */ \"./node_modules/delay/index.js\");\n\n\nclass RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await (0,delay__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nclass MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/utils/dist/src/rate-limiter.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AbortError),\n/* harmony export */ AggregateCodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AggregateCodeError),\n/* harmony export */ CodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.CodeError),\n/* harmony export */ CustomEvent: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.CustomEvent),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_TIMEOUT),\n/* harmony export */ Ed25519: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.Ed25519),\n/* harmony export */ FaultTolerance: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.FaultTolerance),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoTransmissionError),\n/* harmony export */ KEEP_ALIVE: () => (/* reexport safe */ _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__.KEEP_ALIVE),\n/* harmony export */ RSA: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.RSA),\n/* harmony export */ StrictNoSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictNoSign),\n/* harmony export */ StrictSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.TopicValidatorResult),\n/* harmony export */ TypedEventEmitter: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.TypedEventEmitter),\n/* harmony export */ UnexpectedPeerError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.UnexpectedPeerError),\n/* harmony export */ connectionSymbol: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.connectionSymbol),\n/* harmony export */ contentRoutingSymbol: () => (/* reexport safe */ _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__.contentRoutingSymbol),\n/* harmony export */ isConnection: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.isConnection),\n/* harmony export */ isPeerId: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.isPeerId),\n/* harmony export */ isStartable: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.isStartable),\n/* harmony export */ isTransport: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.isTransport),\n/* harmony export */ peerDiscoverySymbol: () => (/* reexport safe */ _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__.peerDiscoverySymbol),\n/* harmony export */ peerIdSymbol: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.peerIdSymbol),\n/* harmony export */ peerRoutingSymbol: () => (/* reexport safe */ _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__.peerRoutingSymbol),\n/* harmony export */ secp256k1: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.secp256k1),\n/* harmony export */ serviceCapabilities: () => (/* binding */ serviceCapabilities),\n/* harmony export */ serviceDependencies: () => (/* binding */ serviceDependencies),\n/* harmony export */ setMaxListeners: () => (/* reexport safe */ _events_js__WEBPACK_IMPORTED_MODULE_11__.setMaxListeners),\n/* harmony export */ start: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.start),\n/* harmony export */ stop: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.stop),\n/* harmony export */ transportSymbol: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.transportSymbol)\n/* harmony export */ });\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/connection/index.js\");\n/* harmony import */ var _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./content-routing/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _keys_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/keys/index.js\");\n/* harmony import */ var _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peer-discovery/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./peer-id/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./peer-routing/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./peer-store/tags.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./pubsub/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/pubsub/index.js\");\n/* harmony import */ var _transport_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./transport/index.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _event_target_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./event-target.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _startable_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./startable.js */ \"./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/startable.js\");\n/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nconst serviceDependencies = Symbol.for('@libp2p/service-dependencies');\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/keys/index.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/keys/index.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519: () => (/* binding */ Ed25519),\n/* harmony export */ RSA: () => (/* binding */ RSA),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\nconst Ed25519 = 'Ed25519';\nconst RSA = 'RSA';\nconst secp256k1 = 'secp256k1';\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/keys/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ peerDiscoverySymbol: () => (/* binding */ peerDiscoverySymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-id/index.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-id/index.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPeerId: () => (/* binding */ isPeerId),\n/* harmony export */ peerIdSymbol: () => (/* binding */ peerIdSymbol)\n/* harmony export */ });\nconst peerIdSymbol = Symbol.for('@libp2p/peer-id');\nfunction isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-id/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-routing/index.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-routing/index.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ peerRoutingSymbol: () => (/* binding */ peerRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-routing/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-store/tags.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-store/tags.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KEEP_ALIVE: () => (/* binding */ KEEP_ALIVE)\n/* harmony export */ });\nconst KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/peer-store/tags.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/pubsub/index.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/pubsub/index.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ StrictNoSign: () => (/* binding */ StrictNoSign),\n/* harmony export */ StrictSign: () => (/* binding */ StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* binding */ TopicValidatorResult)\n/* harmony export */ });\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nconst StrictSign = 'StrictSign';\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nconst StrictNoSign = 'StrictNoSign';\nvar TopicValidatorResult;\n(function (TopicValidatorResult) {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n TopicValidatorResult[\"Accept\"] = \"accept\";\n /**\n * The message is neither delivered nor forwarded to the network\n */\n TopicValidatorResult[\"Ignore\"] = \"ignore\";\n /**\n * The message is considered invalid, and it should be rejected\n */\n TopicValidatorResult[\"Reject\"] = \"reject\";\n})(TopicValidatorResult || (TopicValidatorResult = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/pubsub/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/startable.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/startable.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isStartable: () => (/* binding */ isStartable),\n/* harmony export */ start: () => (/* binding */ start),\n/* harmony export */ stop: () => (/* binding */ stop)\n/* harmony export */ });\nfunction isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nasync function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nasync function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/startable.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/transport/index.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/transport/index.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FaultTolerance: () => (/* binding */ FaultTolerance),\n/* harmony export */ isTransport: () => (/* binding */ isTransport),\n/* harmony export */ transportSymbol: () => (/* binding */ transportSymbol)\n/* harmony export */ });\nconst transportSymbol = Symbol.for('@libp2p/transport');\nfunction isTransport(other) {\n return other != null && Boolean(other[transportSymbol]);\n}\n/**\n * Enum Transport Manager Fault Tolerance values\n */\nvar FaultTolerance;\n(function (FaultTolerance) {\n /**\n * should be used for failing in any listen circumstance\n */\n FaultTolerance[FaultTolerance[\"FATAL_ALL\"] = 0] = \"FATAL_ALL\";\n /**\n * should be used for not failing when not listening\n */\n FaultTolerance[FaultTolerance[\"NO_FATAL\"] = 1] = \"NO_FATAL\";\n})(FaultTolerance || (FaultTolerance = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/@libp2p/interface/dist/src/transport/index.js?"); /***/ }), @@ -6189,7 +8278,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -6233,7 +8322,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -6354,7 +8443,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -6398,7 +8487,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -6574,7 +8663,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compare: () => (/* reexport safe */ _compare__WEBPACK_IMPORTED_MODULE_2__.compare),\n/* harmony export */ concat: () => (/* reexport safe */ _concat__WEBPACK_IMPORTED_MODULE_3__.concat),\n/* harmony export */ equals: () => (/* reexport safe */ _equals_js__WEBPACK_IMPORTED_MODULE_0__.equals),\n/* harmony export */ fromString: () => (/* reexport safe */ _from_string__WEBPACK_IMPORTED_MODULE_4__.fromString),\n/* harmony export */ toString: () => (/* reexport safe */ _to_string__WEBPACK_IMPORTED_MODULE_5__.toString),\n/* harmony export */ xor: () => (/* reexport safe */ _xor_js__WEBPACK_IMPORTED_MODULE_1__.xor)\n/* harmony export */ });\n/* harmony import */ var _equals_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./equals.js */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _xor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xor.js */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/xor.js\");\n/* harmony import */ var _compare__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! #compare */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/compare.js\");\n/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! #concat */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var _from_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! #from-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _to_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! #to-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * `Uint8Array`s bring memory-efficient(ish) byte handling to browsers - they are similar to Node.js `Buffer`s but lack a lot of the utility methods present on that class.\n *\n * This module exports a number of function that let you do common operations - joining Uint8Arrays together, seeing if they have the same contents etc.\n *\n * Since Node.js `Buffer`s are also `Uint8Array`s, it falls back to `Buffer` internally where it makes sense for performance reasons.\n *\n * ## alloc(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * ### Example\n *\n * ```js\n * import { alloc } from 'uint8arrays/alloc'\n *\n * const buf = alloc(100)\n * ```\n *\n * ## allocUnsafe(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * On platforms that support it, memory referenced by the returned `Uint8Array` will not be initialized.\n *\n * ### Example\n *\n * ```js\n * import { allocUnsafe } from 'uint8arrays/alloc'\n *\n * const buf = allocUnsafe(100)\n * ```\n *\n * ## compare(a, b)\n *\n * Compare two `Uint8Arrays`\n *\n * ### Example\n *\n * ```js\n * import { compare } from 'uint8arrays/compare'\n *\n * const arrays = [\n * Uint8Array.from([3, 4, 5]),\n * Uint8Array.from([0, 1, 2])\n * ]\n *\n * const sorted = arrays.sort(compare)\n *\n * console.info(sorted)\n * // [\n * // Uint8Array[0, 1, 2]\n * // Uint8Array[3, 4, 5]\n * // ]\n * ```\n *\n * ## concat(arrays, \\[length])\n *\n * Concatenate one or more `Uint8Array`s and return a `Uint8Array` with their contents.\n *\n * If you know the length of the arrays, pass it as a second parameter, otherwise it will be calculated by traversing the list of arrays.\n *\n * ### Example\n *\n * ```js\n * import { concat } from 'uint8arrays/concat'\n *\n * const arrays = [\n * Uint8Array.from([0, 1, 2]),\n * Uint8Array.from([3, 4, 5])\n * ]\n *\n * const all = concat(arrays, 6)\n *\n * console.info(all)\n * // Uint8Array[0, 1, 2, 3, 4, 5]\n * ```\n *\n * ## equals(a, b)\n *\n * Returns true if the two arrays are the same array or if they have the same length and contents.\n *\n * ### Example\n *\n * ```js\n * import { equals } from 'uint8arrays/equals'\n *\n * const a = Uint8Array.from([0, 1, 2])\n * const b = Uint8Array.from([3, 4, 5])\n * const c = Uint8Array.from([0, 1, 2])\n *\n * console.info(equals(a, b)) // false\n * console.info(equals(a, c)) // true\n * console.info(equals(a, a)) // true\n * ```\n *\n * ## fromString(string, encoding = 'utf8')\n *\n * Returns a new `Uint8Array` created from the passed string and interpreted as the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { fromString } from 'uint8arrays/from-string'\n *\n * console.info(fromString('hello world')) // Uint8Array[104, 101 ...\n * console.info(fromString('00010203aabbcc', 'base16')) // Uint8Array[0, 1 ...\n * console.info(fromString('AAECA6q7zA', 'base64')) // Uint8Array[0, 1 ...\n * console.info(fromString('01234', 'ascii')) // Uint8Array[48, 49 ...\n * ```\n *\n * ## toString(array, encoding = 'utf8')\n *\n * Returns a string created from the passed `Uint8Array` in the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { toString } from 'uint8arrays/to-string'\n *\n * console.info(toString(Uint8Array.from([104, 101...]))) // 'hello world'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base16')) // '00010203aabbcc'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base64')) // 'AAECA6q7zA'\n * console.info(toString(Uint8Array.from([48, 49, 50...]), 'ascii')) // '01234'\n * ```\n *\n * ## xor(a, b)\n *\n * Returns a `Uint8Array` containing `a` and `b` xored together.\n *\n * ### Example\n *\n * ```js\n * import { xor } from 'uint8arrays/xor'\n *\n * console.info(xor(Uint8Array.from([1, 0]), Uint8Array.from([0, 1]))) // Uint8Array[1, 1]\n * ```\n */\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compare: () => (/* reexport safe */ _compare__WEBPACK_IMPORTED_MODULE_2__.compare),\n/* harmony export */ concat: () => (/* reexport safe */ _concat__WEBPACK_IMPORTED_MODULE_3__.concat),\n/* harmony export */ equals: () => (/* reexport safe */ _equals_js__WEBPACK_IMPORTED_MODULE_0__.equals),\n/* harmony export */ fromString: () => (/* reexport safe */ _from_string__WEBPACK_IMPORTED_MODULE_4__.fromString),\n/* harmony export */ toString: () => (/* reexport safe */ _to_string__WEBPACK_IMPORTED_MODULE_5__.toString),\n/* harmony export */ xor: () => (/* reexport safe */ _xor_js__WEBPACK_IMPORTED_MODULE_1__.xor)\n/* harmony export */ });\n/* harmony import */ var _equals_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./equals.js */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _xor_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./xor.js */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/xor.js\");\n/* harmony import */ var _compare__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! #compare */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/compare.js\");\n/* harmony import */ var _concat__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! #concat */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var _from_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! #from-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _to_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! #to-string */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * `Uint8Array`s bring memory-efficient(ish) byte handling to browsers - they are similar to Node.js `Buffer`s but lack a lot of the utility methods present on that class.\n *\n * This module exports a number of function that let you do common operations - joining Uint8Arrays together, seeing if they have the same contents etc.\n *\n * Since Node.js `Buffer`s are also `Uint8Array`s, it falls back to `Buffer` internally where it makes sense for performance reasons.\n *\n * ## alloc(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * ### Example\n *\n * ```js\n * import { alloc } from 'uint8arrays/alloc'\n *\n * const buf = alloc(100)\n * ```\n *\n * ## allocUnsafe(size)\n *\n * Create a new `Uint8Array`. When running under Node.js, `Buffer` will be used in preference to `Uint8Array`.\n *\n * On platforms that support it, memory referenced by the returned `Uint8Array` will not be initialized.\n *\n * ### Example\n *\n * ```js\n * import { allocUnsafe } from 'uint8arrays/alloc'\n *\n * const buf = allocUnsafe(100)\n * ```\n *\n * ## compare(a, b)\n *\n * Compare two `Uint8Arrays`\n *\n * ### Example\n *\n * ```js\n * import { compare } from 'uint8arrays/compare'\n *\n * const arrays = [\n * Uint8Array.from([3, 4, 5]),\n * Uint8Array.from([0, 1, 2])\n * ]\n *\n * const sorted = arrays.sort(compare)\n *\n * console.info(sorted)\n * // [\n * // Uint8Array[0, 1, 2]\n * // Uint8Array[3, 4, 5]\n * // ]\n * ```\n *\n * ## concat(arrays, \\[length])\n *\n * Concatenate one or more `Uint8Array`s and return a `Uint8Array` with their contents.\n *\n * If you know the length of the arrays, pass it as a second parameter, otherwise it will be calculated by traversing the list of arrays.\n *\n * ### Example\n *\n * ```js\n * import { concat } from 'uint8arrays/concat'\n *\n * const arrays = [\n * Uint8Array.from([0, 1, 2]),\n * Uint8Array.from([3, 4, 5])\n * ]\n *\n * const all = concat(arrays, 6)\n *\n * console.info(all)\n * // Uint8Array[0, 1, 2, 3, 4, 5]\n * ```\n *\n * ## equals(a, b)\n *\n * Returns true if the two arrays are the same array or if they have the same length and contents.\n *\n * ### Example\n *\n * ```js\n * import { equals } from 'uint8arrays/equals'\n *\n * const a = Uint8Array.from([0, 1, 2])\n * const b = Uint8Array.from([3, 4, 5])\n * const c = Uint8Array.from([0, 1, 2])\n *\n * console.info(equals(a, b)) // false\n * console.info(equals(a, c)) // true\n * console.info(equals(a, a)) // true\n * ```\n *\n * ## fromString(string, encoding = 'utf8')\n *\n * Returns a new `Uint8Array` created from the passed string and interpreted as the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { fromString } from 'uint8arrays/from-string'\n *\n * console.info(fromString('hello world')) // Uint8Array[104, 101 ...\n * console.info(fromString('00010203aabbcc', 'base16')) // Uint8Array[0, 1 ...\n * console.info(fromString('AAECA6q7zA', 'base64')) // Uint8Array[0, 1 ...\n * console.info(fromString('01234', 'ascii')) // Uint8Array[48, 49 ...\n * ```\n *\n * ## toString(array, encoding = 'utf8')\n *\n * Returns a string created from the passed `Uint8Array` in the passed encoding.\n *\n * Supports `utf8` and any of the [multibase encodings](https://github.com/multiformats/multibase/blob/master/multibase.csv) as implemented by the [multiformats module](https://www.npmjs.com/package/multiformats).\n *\n * ### Example\n *\n * ```js\n * import { toString } from 'uint8arrays/to-string'\n *\n * console.info(toString(Uint8Array.from([104, 101...]))) // 'hello world'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base16')) // '00010203aabbcc'\n * console.info(toString(Uint8Array.from([0, 1, 2...]), 'base64')) // 'AAECA6q7zA'\n * console.info(toString(Uint8Array.from([48, 49, 50...]), 'ascii')) // '01234'\n * ```\n *\n * ## xor(a, b)\n *\n * Returns a `Uint8Array` containing `a` and `b` xored together.\n *\n * ### Example\n *\n * ```js\n * import { xor } from 'uint8arrays/xor'\n *\n * console.info(xor(Uint8Array.from([1, 0]), Uint8Array.from([0, 1]))) // Uint8Array[1, 1]\n * ```\n *\n * ## xorCompare(a, b)\n *\n * Compares the distances between two xor `Uint8Array`s.\n *\n * ### Example\n *\n * ```ts\n * import { xor } from 'uint8arrays/xor'\n * import { xorCompare } from 'uint8arrays/xor-compare'\n *\n * const target = Uint8Array.from([1, 1])\n * const val1 = Uint8Array.from([1, 0])\n * const xor1 = xor(target, val1)\n *\n * const val2 = Uint8Array.from([0, 1])\n * const xor2 = xor(target, val2)\n *\n * console.info(xorCompare(xor1, xor2)) // -1 or 0 or 1\n * ```\n */\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/index.js?"); /***/ }), @@ -6618,7 +8707,458 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ xor: () => (/* binding */ xor)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns the xor distance between two arrays\n */\nfunction xor(a, b) {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length');\n }\n const result = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(a.length);\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i];\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(result);\n}\n//# sourceMappingURL=xor.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/xor.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ xor: () => (/* binding */ xor)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns the xor distance between two Uint8Arrays\n */\nfunction xor(a, b) {\n if (a.length !== b.length) {\n throw new Error('Inputs should have the same length');\n }\n const result = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(a.length);\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i];\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(result);\n}\n//# sourceMappingURL=xor.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/mplex/node_modules/uint8arrays/dist/src/xor.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/dist/src/map.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/dist/src/map.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerMap: () => (/* binding */ PeerMap),\n/* harmony export */ peerMap: () => (/* binding */ peerMap)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/peer-collections/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util.js */ \"./node_modules/@libp2p/peer-collections/dist/src/util.js\");\n\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nclass PeerMap {\n map;\n constructor(map) {\n this.map = new Map();\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value);\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n clear() {\n this.map.clear();\n }\n delete(peer) {\n return this.map.delete(peer.toString());\n }\n entries() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.map.entries(), (val) => {\n return [(0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val[0]), val[1]];\n });\n }\n forEach(fn) {\n this.map.forEach((value, key) => {\n fn(value, (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(key), this);\n });\n }\n get(peer) {\n return this.map.get(peer.toString());\n }\n has(peer) {\n return this.map.has(peer.toString());\n }\n set(peer, value) {\n this.map.set(peer.toString(), value);\n }\n keys() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.map.keys(), (val) => {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val);\n });\n }\n values() {\n return this.map.values();\n }\n get size() {\n return this.map.size;\n }\n}\nfunction peerMap() {\n return new PeerMap();\n}\n//# sourceMappingURL=map.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/dist/src/map.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/dist/src/set.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/dist/src/set.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerSet: () => (/* binding */ PeerSet),\n/* harmony export */ peerSet: () => (/* binding */ peerSet)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/peer-collections/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util.js */ \"./node_modules/@libp2p/peer-collections/dist/src/util.js\");\n\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nclass PeerSet {\n set;\n constructor(set) {\n this.set = new Set();\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString());\n }\n }\n }\n get size() {\n return this.set.size;\n }\n [Symbol.iterator]() {\n return this.values();\n }\n add(peer) {\n this.set.add(peer.toString());\n }\n clear() {\n this.set.clear();\n }\n delete(peer) {\n this.set.delete(peer.toString());\n }\n entries() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.set.entries(), (val) => {\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val[0]);\n return [peerId, peerId];\n });\n }\n forEach(predicate) {\n this.set.forEach((str) => {\n const id = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(str);\n predicate(id, id, this);\n });\n }\n has(peer) {\n return this.set.has(peer.toString());\n }\n values() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.set.values(), (val) => {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val);\n });\n }\n intersection(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n difference(other) {\n const output = new PeerSet();\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n union(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n output.add(peerId);\n }\n for (const peerId of this) {\n output.add(peerId);\n }\n return output;\n }\n}\nfunction peerSet() {\n return new PeerSet();\n}\n//# sourceMappingURL=set.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/dist/src/set.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/dist/src/util.js": +/*!****************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/dist/src/util.js ***! + \****************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ mapIterable: () => (/* binding */ mapIterable)\n/* harmony export */ });\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nfunction mapIterable(iter, map) {\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n const next = iter.next();\n const val = next.value;\n if (next.done === true || val == null) {\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n return {\n done: false,\n value: map(val)\n };\n }\n };\n return iterator;\n}\n//# sourceMappingURL=util.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/dist/src/util.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/errors.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/errors.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ AggregateCodeError: () => (/* binding */ AggregateCodeError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* binding */ ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* binding */ ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* binding */ ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* binding */ ERR_TIMEOUT),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* binding */ InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* binding */ InvalidCryptoTransmissionError),\n/* harmony export */ UnexpectedPeerError: () => (/* binding */ UnexpectedPeerError)\n/* harmony export */ });\n/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nclass AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nclass CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nclass InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nclass InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nconst ERR_TIMEOUT = 'ERR_TIMEOUT';\nconst ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nconst ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nconst ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/errors.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/peer-id/index.js": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/peer-id/index.js ***! + \********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPeerId: () => (/* binding */ isPeerId),\n/* harmony export */ peerIdSymbol: () => (/* binding */ peerIdSymbol)\n/* harmony export */ });\nconst peerIdSymbol = Symbol.for('@libp2p/peer-id');\nfunction isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/peer-id/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/@libp2p/peer-id/dist/src/index.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/@libp2p/peer-id/dist/src/index.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-collections/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/@libp2p/peer-id/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base10.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base10.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base10: () => (/* binding */ base10)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base10 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base10.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base16.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base16.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base16: () => (/* binding */ base16),\n/* harmony export */ base16upper: () => (/* binding */ base16upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base16 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nconst base16upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base16.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base2.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base2.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base2: () => (/* binding */ base2)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base2 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base2.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base256emoji.js": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base256emoji.js ***! + \********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base256emoji.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base32.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base32.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base32: () => (/* binding */ base32),\n/* harmony export */ base32hex: () => (/* binding */ base32hex),\n/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),\n/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),\n/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),\n/* harmony export */ base32pad: () => (/* binding */ base32pad),\n/* harmony export */ base32padupper: () => (/* binding */ base32padupper),\n/* harmony export */ base32upper: () => (/* binding */ base32upper),\n/* harmony export */ base32z: () => (/* binding */ base32z)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nconst base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nconst base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nconst base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nconst base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nconst base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nconst base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nconst base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nconst base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base32.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base36.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base36.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base36: () => (/* binding */ base36),\n/* harmony export */ base36upper: () => (/* binding */ base36upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nconst base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base36.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base58btc: () => (/* binding */ base58btc),\n/* harmony export */ base58flickr: () => (/* binding */ base58flickr)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nconst base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base64.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base64.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64pad: () => (/* binding */ base64pad),\n/* harmony export */ base64url: () => (/* binding */ base64url),\n/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nconst base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nconst base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nconst base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base64.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base8.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base8.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base8: () => (/* binding */ base8)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base8 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base8.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/identity.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/identity.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base.js\");\n\n\nconst identity = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.from)({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.toString)(buf),\n decode: (str) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.fromString)(str)\n});\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/interface.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/interface.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// Base encoders / decoders just base encode / decode between binary and\n// textual representation. They are unaware of multibase.\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/basics.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/basics.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.CID),\n/* harmony export */ bases: () => (/* binding */ bases),\n/* harmony export */ bytes: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.bytes),\n/* harmony export */ codecs: () => (/* binding */ codecs),\n/* harmony export */ digest: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.digest),\n/* harmony export */ hasher: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.hasher),\n/* harmony export */ hashes: () => (/* binding */ hashes),\n/* harmony export */ varint: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.varint)\n/* harmony export */ });\n/* harmony import */ var _bases_base10_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base10.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base10.js\");\n/* harmony import */ var _bases_base16_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base16.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base16.js\");\n/* harmony import */ var _bases_base2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base2.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base2.js\");\n/* harmony import */ var _bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bases/base256emoji.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base256emoji.js\");\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bases_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./bases/base64.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _bases_base8_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bases/base8.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base8.js\");\n/* harmony import */ var _bases_identity_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bases/identity.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/identity.js\");\n/* harmony import */ var _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./codecs/json.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/json.js\");\n/* harmony import */ var _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./codecs/raw.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/raw.js\");\n/* harmony import */ var _hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./hashes/identity.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var _hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./hashes/sha2.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/index.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst bases = { ..._bases_identity_js__WEBPACK_IMPORTED_MODULE_9__, ..._bases_base2_js__WEBPACK_IMPORTED_MODULE_2__, ..._bases_base8_js__WEBPACK_IMPORTED_MODULE_8__, ..._bases_base10_js__WEBPACK_IMPORTED_MODULE_0__, ..._bases_base16_js__WEBPACK_IMPORTED_MODULE_1__, ..._bases_base32_js__WEBPACK_IMPORTED_MODULE_4__, ..._bases_base36_js__WEBPACK_IMPORTED_MODULE_5__, ..._bases_base58_js__WEBPACK_IMPORTED_MODULE_6__, ..._bases_base64_js__WEBPACK_IMPORTED_MODULE_7__, ..._bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ };\nconst hashes = { ..._hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__, ..._hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ };\nconst codecs = { raw: _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__, json: _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ };\n\n//# sourceMappingURL=basics.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/basics.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/block/interface.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/block/interface.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/block/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ empty: () => (/* binding */ empty),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ fromHex: () => (/* binding */ fromHex),\n/* harmony export */ fromString: () => (/* binding */ fromString),\n/* harmony export */ isBinary: () => (/* binding */ isBinary),\n/* harmony export */ toHex: () => (/* binding */ toHex),\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\nconst empty = new Uint8Array(0);\nfunction toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nfunction fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nfunction equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nfunction coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nfunction isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nfunction fromString(str) {\n return new TextEncoder().encode(str);\n}\nfunction toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/cid.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/cid.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/cid.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/interface.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/interface.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/json.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/json.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nconst name = 'json';\nconst code = 0x0200;\nfunction encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nfunction decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/json.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/raw.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/raw.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n\nconst name = 'raw';\nconst code = 0x55;\nfunction encode(node) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(node);\n}\nfunction decode(data) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(data);\n}\n//# sourceMappingURL=raw.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/raw.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/hasher.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/hasher.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hasher: () => (/* binding */ Hasher),\n/* harmony export */ from: () => (/* binding */ from)\n/* harmony export */ });\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js\");\n\nfunction from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nclass Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/hasher.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/identity.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/identity.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js\");\n\n\nconst code = 0x0;\nconst name = 'identity';\nconst encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;\nfunction digest(input) {\n return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));\n}\nconst identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/interface.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/interface.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// # Multihash\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/sha2-browser.js": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***! + \*********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha256: () => (/* binding */ sha256),\n/* harmony export */ sha512: () => (/* binding */ sha512)\n/* harmony export */ });\n/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* global crypto */\n\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nconst sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nconst sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/sha2-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/index.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/index.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),\n/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),\n/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),\n/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/interface.js\");\n/**\n * @packageDocumentation\n *\n * This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.\n *\n * This library provides implementations for most basics and many others can be found in linked repositories.\n *\n * ```TypeScript\n * import { CID } from 'multiformats/cid'\n * import * as json from 'multiformats/codecs/json'\n * import { sha256 } from 'multiformats/hashes/sha2'\n *\n * const bytes = json.encode({ hello: 'world' })\n *\n * const hash = await sha256.digest(bytes)\n * const cid = CID.create(1, json.code, hash)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Creating Blocks\n *\n * ```TypeScript\n * import * as Block from 'multiformats/block'\n * import * as codec from '@ipld/dag-cbor'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * const value = { hello: 'world' }\n *\n * // encode a block\n * let block = await Block.encode({ value, codec, hasher })\n *\n * block.value // { hello: 'world' }\n * block.bytes // Uint8Array\n * block.cid // CID() w/ sha2-256 hash address and dag-cbor codec\n *\n * // you can also decode blocks from their binary state\n * block = await Block.decode({ bytes: block.bytes, codec, hasher })\n *\n * // if you have the cid you can also verify the hash on decode\n * block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })\n * ```\n *\n * ## Multibase Encoders / Decoders / Codecs\n *\n * CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:\n *\n * ```TypeScript\n * import { base64 } from \"multiformats/bases/base64\"\n * cid.toString(base64.encoder)\n * //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'\n * ```\n *\n * Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:\n *\n * ```TypeScript\n * CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * Dual of multibase encoder & decoder is defined as multibase codec and it exposes\n * them as `encoder` and `decoder` properties. For added convenience codecs also\n * implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be\n * used as either or both:\n *\n * ```TypeScript\n * cid.toString(base64)\n * CID.parse(cid.toString(base64), base64)\n * ```\n *\n * **Note:** CID implementation comes bundled with `base32` and `base58btc`\n * multibase codecs so that CIDs can be base serialized to (version specific)\n * default base encoding and parsed without having to supply base encoders/decoders:\n *\n * ```TypeScript\n * const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')\n * v1.toString()\n * //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'\n *\n * const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n * v0.toString()\n * //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'\n * v0.toV1().toString()\n * //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'\n * ```\n *\n * ## Multicodec Encoders / Decoders / Codecs\n *\n * This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).\n * Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.\n * Here is an example implementation of JSON `BlockCodec`.\n *\n * ```TypeScript\n * export const { name, code, encode, decode } = {\n * name: 'json',\n * code: 0x0200,\n * encode: json => new TextEncoder().encode(JSON.stringify(json)),\n * decode: bytes => JSON.parse(new TextDecoder().decode(bytes))\n * }\n * ```\n *\n * ## Multihash Hashers\n *\n * This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:\n *\n * ```TypeScript\n * import * as hasher from 'multiformats/hashes/hasher'\n *\n * const sha256 = hasher.from({\n * // As per multiformats table\n * // https://github.com/multiformats/multicodec/blob/master/table.csv#L9\n * name: 'sha2-256',\n * code: 0x12,\n *\n * encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())\n * })\n *\n * const hash = await sha256.digest(json.encode({ hello: 'world' }))\n * CID.create(1, json.code, hash)\n *\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Traversal\n *\n * This library contains higher-order functions for traversing graphs of data easily.\n *\n * `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.\n *\n * ```TypeScript\n * import { walk } from 'multiformats/traversal'\n * import * as Block from 'multiformats/block'\n * import * as codec from 'multiformats/codecs/json'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * // build a DAG (a single block for this simple example)\n * const value = { hello: 'world' }\n * const block = await Block.encode({ value, codec, hasher })\n * const { cid } = block\n * console.log(cid)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n *\n * // create a loader function that also collects CIDs of blocks in\n * // their traversal order\n * const load = (cid, blocks) => async (cid) => {\n * // fetch a block using its cid\n * // e.g.: const block = await fetchBlockByCID(cid)\n * blocks.push(cid)\n * return block\n * }\n *\n * // collect blocks in this DAG starting from the root `cid`\n * const blocks = []\n * await walk({ cid, load: load(cid, blocks) })\n *\n * console.log(blocks)\n * //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]\n * ```\n *\n * ## Legacy interface\n *\n * [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an\n * [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.\n *\n * ## Implementations\n *\n * By default, no base encodings (other than base32 & base58btc), hash functions,\n * or codec implementations are exposed by `multiformats`, you need to\n * import the ones you need yourself.\n *\n * ### Multibase codecs\n *\n * | bases | import | repo |\n * | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |\n * | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n *\n * Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.\n *\n * ### Multihash hashers\n *\n * | hashes | import | repo |\n * | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |\n * | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |\n * | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |\n * | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |\n * | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |\n * | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |\n *\n * ### IPLD codecs (multicodec)\n *\n * | codec | import | repo |\n * | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |\n * | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |\n * | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |\n * | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |\n * | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |\n */\n\n\n\n\n\n// This way TS will also expose all the types from module\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/interface.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/interface.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _bases_interface_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/bases/interface.js\");\n/* harmony import */ var _hashes_interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/hashes/interface.js\");\n/* harmony import */ var _codecs_interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/codecs/interface.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/link/interface.js\");\n/* harmony import */ var _block_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./block/interface.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/block/interface.js\");\n\n\n\n\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/link/interface.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/link/interface.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */\n/* eslint-disable no-use-before-define */\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/link/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encodeTo: () => (/* binding */ encodeTo),\n/* harmony export */ encodingLength: () => (/* binding */ encodingLength)\n/* harmony export */ });\n/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/varint.js\");\n\nfunction decode(data, offset = 0) {\n const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode(data, offset);\n return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode.bytes];\n}\nfunction encodeTo(int, target, offset = 0) {\n _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encode(int, target, offset);\n return target;\n}\nfunction encodingLength(int) {\n return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/base-x.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/base-x.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);\n//# sourceMappingURL=base-x.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/base-x.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/varint.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/varint.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/vendor/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/alloc.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/alloc.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ alloc: () => (/* binding */ alloc),\n/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)\n/* harmony export */ });\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nfunction alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nfunction allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/alloc.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/equals.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/equals.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/equals.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/from-string.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/from-string.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fromString: () => (/* binding */ fromString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction fromString(string, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/from-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/to-string.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/to-string.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction toString(array, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/to-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/util/bases.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/util/bases.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/peer-collections/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/alloc.js\");\n\n\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);\n//# sourceMappingURL=bases.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-collections/node_modules/uint8arrays/dist/src/util/bases.js?"); /***/ }), @@ -6930,6 +9470,732 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js": +/*!************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js ***! + \************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Envelope: () => (/* binding */ Envelope)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.payloadType = reader.bytes();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n case 5:\n obj.signature = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, Envelope.codec());\n };\n Envelope.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, Envelope.codec());\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/dist/src/envelope/index.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/envelope/index.js ***! + \*********************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RecordEnvelope: () => (/* binding */ RecordEnvelope)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@libp2p/peer-record/dist/src/errors.js\");\n/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./envelope.js */ \"./node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js\");\n\n\n\n\n\n\n\n\n\nclass RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.decode(data);\n const peerId = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__.peerIdFromKeys)(envelopeData.publicKey);\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, peerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPrivateKey)(peerId.privateKey);\n const signature = await key.sign(signData.subarray());\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError('envelope signature is not valid for the given domain', _errors_js__WEBPACK_IMPORTED_MODULE_8__.codes.ERR_SIGNATURE_NOT_VALID);\n }\n return envelope;\n };\n peerId;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { peerId, payloadType, payload, signature } = init;\n this.peerId = peerId;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n if (this.marshaled == null) {\n this.marshaled = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n const key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPublicKey)(this.peerId.publicKey);\n return key.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(domain);\n const domainLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(domainUint8Array.byteLength);\n const payloadTypeLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payloadType.length);\n const payloadLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payload.length);\n return new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/envelope/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/dist/src/errors.js": +/*!*************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/errors.js ***! + \*************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ codes: () => (/* binding */ codes)\n/* harmony export */ });\nconst codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n};\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/errors.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js": +/*!*************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js ***! + \*************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ENVELOPE_DOMAIN_PEER_RECORD: () => (/* binding */ ENVELOPE_DOMAIN_PEER_RECORD),\n/* harmony export */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD: () => (/* binding */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD)\n/* harmony export */ });\n// The domain string used for peer records contained in a Envelope.\nconst ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nconst ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js": +/*!************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js ***! + \************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/utils/array-equals */ \"./node_modules/@libp2p/utils/dist/src/array-equals.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _consts_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./consts.js */ \"./node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js\");\n/* harmony import */ var _peer_record_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peer-record.js */ \"./node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js\");\n\n\n\n\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nclass PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.decode(buf);\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromBytes)(peerRecord.peerId);\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!(0,_libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__.arrayEquals)(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js ***! + \******************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, AddressInfo.codec());\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes();\n break;\n case 2:\n obj.seq = reader.uint64();\n break;\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()));\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PeerRecord.codec());\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js ***! + \**********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ derivedEmptyPasswordKey: () => (/* binding */ derivedEmptyPasswordKey)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n\n\n\n// WebKit on Linux does not support deriving a key from an empty PBKDF2 key.\n// So, as a workaround, we provide the generated key as a constant. We test that\n// this generated key is accurate in test/workaround.spec.ts\n// Generated via:\n// await crypto.subtle.exportKey('jwk',\n// await crypto.subtle.deriveKey(\n// { name: 'PBKDF2', salt: new Uint8Array(16), iterations: 32767, hash: { name: 'SHA-256' } },\n// await crypto.subtle.importKey('raw', new Uint8Array(0), { name: 'PBKDF2' }, false, ['deriveKey']),\n// { name: 'AES-GCM', length: 128 }, true, ['encrypt', 'decrypt'])\n// )\nconst derivedEmptyPasswordKey = { alg: 'A128GCM', ext: true, k: 'scm9jmO_4BJAgdwWGVulLg', key_ops: ['encrypt', 'decrypt'], kty: 'oct' };\n// Based off of code from https://github.com/luke-park/SecureCompatibleEncryptionExamples\nfunction create(opts) {\n const algorithm = opts?.algorithm ?? 'AES-GCM';\n let keyLength = opts?.keyLength ?? 16;\n const nonceLength = opts?.nonceLength ?? 12;\n const digest = opts?.digest ?? 'SHA-256';\n const saltLength = opts?.saltLength ?? 16;\n const iterations = opts?.iterations ?? 32767;\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get();\n keyLength *= 8; // Browser crypto uses bits instead of bytes\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to encrypt the data.\n */\n async function encrypt(data, password) {\n const salt = crypto.getRandomValues(new Uint8Array(saltLength));\n const nonce = crypto.getRandomValues(new Uint8Array(nonceLength));\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['encrypt']);\n }\n }\n else {\n // Derive a key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['encrypt']);\n }\n // Encrypt the string.\n const ciphertext = await crypto.subtle.encrypt(aesGcm, cryptoKey, data);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([salt, aesGcm.iv, new Uint8Array(ciphertext)]);\n }\n /**\n * Uses the provided password to derive a pbkdf2 key. The key\n * will then be used to decrypt the data. The options used to create\n * this decryption cipher must be the same as those used to create\n * the encryption cipher.\n */\n async function decrypt(data, password) {\n const salt = data.subarray(0, saltLength);\n const nonce = data.subarray(saltLength, saltLength + nonceLength);\n const ciphertext = data.subarray(saltLength + nonceLength);\n const aesGcm = { name: algorithm, iv: nonce };\n if (typeof password === 'string') {\n password = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(password);\n }\n let cryptoKey;\n if (password.length === 0) {\n try {\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const runtimeDerivedEmptyPassword = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, runtimeDerivedEmptyPassword, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n catch {\n cryptoKey = await crypto.subtle.importKey('jwk', derivedEmptyPasswordKey, { name: 'AES-GCM' }, true, ['decrypt']);\n }\n }\n else {\n // Derive the key using PBKDF2.\n const deriveParams = { name: 'PBKDF2', salt, iterations, hash: { name: digest } };\n const rawKey = await crypto.subtle.importKey('raw', password, { name: 'PBKDF2' }, false, ['deriveKey']);\n cryptoKey = await crypto.subtle.deriveKey(deriveParams, rawKey, { name: algorithm, length: keyLength }, true, ['decrypt']);\n }\n // Decrypt the string.\n const plaintext = await crypto.subtle.decrypt(aesGcm, cryptoKey, ciphertext);\n return new Uint8Array(plaintext);\n }\n const cipher = {\n encrypt,\n decrypt\n };\n return cipher;\n}\n//# sourceMappingURL=aes-gcm.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ create: () => (/* binding */ create)\n/* harmony export */ });\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _lengths_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lengths.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js\");\n\n\nconst hashTypes = {\n SHA1: 'SHA-1',\n SHA256: 'SHA-256',\n SHA512: 'SHA-512'\n};\nconst sign = async (key, data) => {\n const buf = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].get().subtle.sign({ name: 'HMAC' }, key, data);\n return new Uint8Array(buf, 0, buf.byteLength);\n};\nasync function create(hashType, secret) {\n const hash = hashTypes[hashType];\n const key = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].get().subtle.importKey('raw', secret, {\n name: 'HMAC',\n hash: { name: hash }\n }, false, ['sign']);\n return {\n async digest(data) {\n return sign(key, data);\n },\n length: _lengths_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"][hashType]\n };\n}\n//# sourceMappingURL=index-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n SHA1: 20,\n SHA256: 32,\n SHA512: 64\n});\n//# sourceMappingURL=lengths.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/lengths.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateEphmeralKeyPair: () => (/* binding */ generateEphmeralKeyPair)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n\n\n\n\n\n\nconst bits = {\n 'P-256': 256,\n 'P-384': 384,\n 'P-521': 521\n};\nconst curveTypes = Object.keys(bits);\nconst names = curveTypes.join(' / ');\nasync function generateEphmeralKeyPair(curve) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const pair = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.generateKey({\n name: 'ECDH',\n namedCurve: curve\n }, true, ['deriveBits']);\n // forcePrivate is used for testing only\n const genSharedKey = async (theirPub, forcePrivate) => {\n let privateKey;\n if (forcePrivate != null) {\n privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.importKey('jwk', unmarshalPrivateKey(curve, forcePrivate), {\n name: 'ECDH',\n namedCurve: curve\n }, false, ['deriveBits']);\n }\n else {\n privateKey = pair.privateKey;\n }\n const key = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.importKey('jwk', unmarshalPublicKey(curve, theirPub), {\n name: 'ECDH',\n namedCurve: curve\n }, false, []);\n const buffer = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.deriveBits({\n name: 'ECDH',\n // @ts-expect-error namedCurve is missing from the types\n namedCurve: curve,\n public: key\n }, privateKey, bits[curve]);\n return new Uint8Array(buffer, 0, buffer.byteLength);\n };\n const publicKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get().subtle.exportKey('jwk', pair.publicKey);\n const ecdhKey = {\n key: marshalPublicKey(publicKey),\n genSharedKey\n };\n return ecdhKey;\n}\nconst curveLengths = {\n 'P-256': 32,\n 'P-384': 48,\n 'P-521': 66\n};\n// Marshal converts a jwk encoded ECDH public key into the\n// form specified in section 4.3.6 of ANSI X9.62. (This is the format\n// go-ipfs uses)\nfunction marshalPublicKey(jwk) {\n if (jwk.crv == null || jwk.x == null || jwk.y == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n if (jwk.crv !== 'P-256' && jwk.crv !== 'P-384' && jwk.crv !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${jwk.crv}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[jwk.crv];\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([\n Uint8Array.from([4]), // uncompressed point\n (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.x, byteLen),\n (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.base64urlToBuffer)(jwk.y, byteLen)\n ], 1 + byteLen * 2);\n}\n// Unmarshal converts a point, serialized by Marshal, into an jwk encoded key\nfunction unmarshalPublicKey(curve, key) {\n if (curve !== 'P-256' && curve !== 'P-384' && curve !== 'P-521') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Unknown curve: ${curve}. Must be ${names}`, 'ERR_INVALID_CURVE');\n }\n const byteLen = curveLengths[curve];\n if (!(0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(key.subarray(0, 1), Uint8Array.from([4]))) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Cannot unmarshal public key - invalid key format', 'ERR_INVALID_KEY_FORMAT');\n }\n return {\n kty: 'EC',\n crv: curve,\n x: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1, byteLen + 1), 'base64url'),\n y: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.subarray(1 + byteLen), 'base64url'),\n ext: true\n };\n}\nconst unmarshalPrivateKey = (curve, key) => ({\n ...unmarshalPublicKey(curve, key.public),\n d: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(key.private, 'base64url')\n});\n//# sourceMappingURL=ecdh-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ generateKeyFromSeed: () => (/* binding */ generateKeyFromSeed),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),\n/* harmony export */ publicKeyLength: () => (/* binding */ PUBLIC_KEY_BYTE_LENGTH)\n/* harmony export */ });\n/* harmony import */ var _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/curves/ed25519 */ \"./node_modules/@noble/curves/esm/ed25519.js\");\n\nconst PUBLIC_KEY_BYTE_LENGTH = 32;\nconst PRIVATE_KEY_BYTE_LENGTH = 64; // private key is actually 32 bytes but for historical reasons we concat private and public keys\nconst KEYS_BYTE_LENGTH = 32;\n\n\nfunction generateKey() {\n // the actual private key (32 bytes)\n const privateKeyRaw = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.utils.randomPrivateKey();\n const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);\n // concatenated the public key to the private key\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\n/**\n * Generate keypair from a 32 byte uint8array\n */\nfunction generateKeyFromSeed(seed) {\n if (seed.length !== KEYS_BYTE_LENGTH) {\n throw new TypeError('\"seed\" must be 32 bytes in length.');\n }\n else if (!(seed instanceof Uint8Array)) {\n throw new TypeError('\"seed\" must be a node.js Buffer, or Uint8Array.');\n }\n // based on node forges algorithm, the seed is used directly as private key\n const privateKeyRaw = seed;\n const publicKey = _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.getPublicKey(privateKeyRaw);\n const privateKey = concatKeys(privateKeyRaw, publicKey);\n return {\n privateKey,\n publicKey\n };\n}\nfunction hashAndSign(privateKey, msg) {\n const privateKeyRaw = privateKey.subarray(0, KEYS_BYTE_LENGTH);\n return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.sign(msg instanceof Uint8Array ? msg : msg.subarray(), privateKeyRaw);\n}\nfunction hashAndVerify(publicKey, sig, msg) {\n return _noble_curves_ed25519__WEBPACK_IMPORTED_MODULE_0__.ed25519.verify(sig, msg instanceof Uint8Array ? msg : msg.subarray(), publicKey);\n}\nfunction concatKeys(privateKeyRaw, publicKey) {\n const privateKey = new Uint8Array(PRIVATE_KEY_BYTE_LENGTH);\n for (let i = 0; i < KEYS_BYTE_LENGTH; i++) {\n privateKey[i] = privateKeyRaw[i];\n privateKey[KEYS_BYTE_LENGTH + i] = publicKey[i];\n }\n return privateKey;\n}\n//# sourceMappingURL=ed25519-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* binding */ Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* binding */ Ed25519PublicKey),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ unmarshalEd25519PrivateKey: () => (/* binding */ unmarshalEd25519PrivateKey),\n/* harmony export */ unmarshalEd25519PublicKey: () => (/* binding */ unmarshalEd25519PublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _ed25519_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-browser.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n\n\n\n\n\n\n\n\n\nclass Ed25519PublicKey {\n _key;\n constructor(key) {\n this._key = ensureKey(key, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n }\n verify(data, sig) {\n return _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nclass Ed25519PrivateKey {\n _key;\n _publicKey;\n // key - 64 byte Uint8Array containing private key\n // publicKey - 32 byte Uint8Array containing public key\n constructor(key, publicKey) {\n this._key = ensureKey(key, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n this._publicKey = ensureKey(publicKey, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n }\n sign(message) {\n return _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.hashAndSign(this._key, message);\n }\n get public() {\n return new Ed25519PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.Ed25519,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_3__.equals)(this.bytes, key.bytes);\n }\n async hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_2__.sha256.digest(this.bytes);\n let bytes;\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the identity multihash containing its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n *\n * @returns {Promise}\n */\n async id() {\n const encoding = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_1__.identity.digest(this.public.bytes);\n return multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(encoding.bytes).substring(1);\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_7__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nfunction unmarshalEd25519PrivateKey(bytes) {\n // Try the old, redundant public key version\n if (bytes.length > _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength) {\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength + _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n const privateKeyBytes = bytes.subarray(0, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const publicKeyBytes = bytes.subarray(_ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength, bytes.length);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n }\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const privateKeyBytes = bytes.subarray(0, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.privateKeyLength);\n const publicKeyBytes = bytes.subarray(_ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n return new Ed25519PrivateKey(privateKeyBytes, publicKeyBytes);\n}\nfunction unmarshalEd25519PublicKey(bytes) {\n bytes = ensureKey(bytes, _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.publicKeyLength);\n return new Ed25519PublicKey(bytes);\n}\nasync function generateKeyPair() {\n const { privateKey, publicKey } = _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.generateKey();\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nasync function generateKeyPairFromSeed(seed) {\n const { privateKey, publicKey } = _ed25519_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyFromSeed(seed);\n return new Ed25519PrivateKey(privateKey, publicKey);\n}\nfunction ensureKey(key, length) {\n key = Uint8Array.from(key ?? []);\n if (key.length !== length) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`Key must be a Uint8Array of length ${length}, got ${key.length}`, 'ERR_INVALID_KEY_TYPE');\n }\n return key;\n}\n//# sourceMappingURL=ed25519-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _ecdh_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ecdh.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ecdh-browser.js\");\n\n/**\n * Generates an ephemeral public key and returns a function that will compute\n * the shared secret key.\n *\n * Focuses only on ECDH now, but can be made more general in the future.\n */\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_ecdh_js__WEBPACK_IMPORTED_MODULE_0__.generateEphmeralKeyPair);\n//# sourceMappingURL=ephemeral-keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ exporter: () => (/* binding */ exporter)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ciphers/aes-gcm.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js\");\n\n\n/**\n * Exports the given PrivateKey as a base64 encoded string.\n * The PrivateKey is encrypted via a password derived PBKDF2 key\n * leveraging the aes-gcm cipher algorithm.\n */\nasync function exporter(privateKey, password) {\n const cipher = _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__.create();\n const encryptedKey = await cipher.encrypt(privateKey, password);\n return multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__.base64.encode(encryptedKey);\n}\n//# sourceMappingURL=exporter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/importer.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/importer.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ importer: () => (/* binding */ importer)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ciphers/aes-gcm.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/ciphers/aes-gcm.browser.js\");\n\n\n/**\n * Attempts to decrypt a base64 encoded PrivateKey string\n * with the given password. The privateKey must have been exported\n * using the same password and underlying cipher (aes-gcm)\n */\nasync function importer(privateKey, password) {\n const encryptedKey = multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_0__.base64.decode(privateKey);\n const cipher = _ciphers_aes_gcm_js__WEBPACK_IMPORTED_MODULE_1__.create();\n return cipher.decrypt(encryptedKey, password);\n}\n//# sourceMappingURL=importer.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/importer.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/index.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/index.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ keyStretcher: () => (/* binding */ keyStretcher)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../hmac/index.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/hmac/index-browser.js\");\n\n\n\n\nconst cipherMap = {\n 'AES-128': {\n ivSize: 16,\n keySize: 16\n },\n 'AES-256': {\n ivSize: 16,\n keySize: 32\n },\n Blowfish: {\n ivSize: 8,\n keySize: 32\n }\n};\n/**\n * Generates a set of keys for each party by stretching the shared key.\n * (myIV, theirIV, myCipherKey, theirCipherKey, myMACKey, theirMACKey)\n */\nasync function keyStretcher(cipherType, hash, secret) {\n const cipher = cipherMap[cipherType];\n if (cipher == null) {\n const allowed = Object.keys(cipherMap).join(' / ');\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`unknown cipher type '${cipherType}'. Must be ${allowed}`, 'ERR_INVALID_CIPHER_TYPE');\n }\n if (hash == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('missing hash type', 'ERR_MISSING_HASH_TYPE');\n }\n const cipherKeySize = cipher.keySize;\n const ivSize = cipher.ivSize;\n const hmacKeySize = 20;\n const seed = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)('key expansion');\n const resultLength = 2 * (ivSize + cipherKeySize + hmacKeySize);\n const m = await _hmac_index_js__WEBPACK_IMPORTED_MODULE_3__.create(hash, secret);\n let a = await m.digest(seed);\n const result = [];\n let j = 0;\n while (j < resultLength) {\n const b = await m.digest((0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([a, seed]));\n let todo = b.length;\n if (j + todo > resultLength) {\n todo = resultLength - j;\n }\n result.push(b);\n j += todo;\n a = await m.digest(a);\n }\n const half = resultLength / 2;\n const resultBuffer = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)(result);\n const r1 = resultBuffer.subarray(0, half);\n const r2 = resultBuffer.subarray(half, resultLength);\n const createKey = (res) => ({\n iv: res.subarray(0, ivSize),\n cipherKey: res.subarray(ivSize, ivSize + cipherKeySize),\n macKey: res.subarray(ivSize + cipherKeySize)\n });\n return {\n k1: createKey(r1),\n k2: createKey(r2)\n };\n}\n//# sourceMappingURL=key-stretcher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KeyType: () => (/* binding */ KeyType),\n/* harmony export */ PrivateKey: () => (/* binding */ PrivateKey),\n/* harmony export */ PublicKey: () => (/* binding */ PublicKey)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar KeyType;\n(function (KeyType) {\n KeyType[\"RSA\"] = \"RSA\";\n KeyType[\"Ed25519\"] = \"Ed25519\";\n KeyType[\"Secp256k1\"] = \"Secp256k1\";\n})(KeyType || (KeyType = {}));\nvar __KeyTypeValues;\n(function (__KeyTypeValues) {\n __KeyTypeValues[__KeyTypeValues[\"RSA\"] = 0] = \"RSA\";\n __KeyTypeValues[__KeyTypeValues[\"Ed25519\"] = 1] = \"Ed25519\";\n __KeyTypeValues[__KeyTypeValues[\"Secp256k1\"] = 2] = \"Secp256k1\";\n})(__KeyTypeValues || (__KeyTypeValues = {}));\n(function (KeyType) {\n KeyType.codec = () => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.enumeration)(__KeyTypeValues);\n };\n})(KeyType || (KeyType = {}));\nvar PublicKey;\n(function (PublicKey) {\n let _codec;\n PublicKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PublicKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PublicKey.codec());\n };\n PublicKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PublicKey.codec());\n };\n})(PublicKey || (PublicKey = {}));\nvar PrivateKey;\n(function (PrivateKey) {\n let _codec;\n PrivateKey.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if (obj.Type != null) {\n w.uint32(8);\n KeyType.codec().encode(obj.Type, w);\n }\n if (obj.Data != null) {\n w.uint32(18);\n w.bytes(obj.Data);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {};\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.Type = KeyType.codec().decode(reader);\n break;\n case 2:\n obj.Data = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PrivateKey.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PrivateKey.codec());\n };\n PrivateKey.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PrivateKey.codec());\n };\n})(PrivateKey || (PrivateKey = {}));\n//# sourceMappingURL=keys.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ getRandomValues: () => (/* reexport safe */ _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"]),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ keySize: () => (/* binding */ keySize),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ utils: () => (/* reexport module object */ _rsa_utils_js__WEBPACK_IMPORTED_MODULE_1__)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _random_bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../random-bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n\n\n\n\n\n\nasync function generateKey(bits) {\n const pair = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength: bits,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: { name: 'SHA-256' }\n }, true, ['sign', 'verify']);\n const keys = await exportKey(pair);\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n// Takes a jwk key\nasync function unmarshalPrivateKey(key) {\n const privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['sign']);\n const pair = [\n privateKey,\n await derivePublicFromPrivate(key)\n ];\n const keys = await exportKey({\n privateKey: pair[0],\n publicKey: pair[1]\n });\n return {\n privateKey: keys[0],\n publicKey: keys[1]\n };\n}\n\nasync function hashAndSign(key, msg) {\n const privateKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['sign']);\n const sig = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.sign({ name: 'RSASSA-PKCS1-v1_5' }, privateKey, msg instanceof Uint8Array ? msg : msg.subarray());\n return new Uint8Array(sig, 0, sig.byteLength);\n}\nasync function hashAndVerify(key, sig, msg) {\n const publicKey = await _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', key, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, false, ['verify']);\n return _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.verify({ name: 'RSASSA-PKCS1-v1_5' }, publicKey, sig, msg instanceof Uint8Array ? msg : msg.subarray());\n}\nasync function exportKey(pair) {\n if (pair.privateKey == null || pair.publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Private and public key are required', 'ERR_INVALID_PARAMETERS');\n }\n return Promise.all([\n _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.exportKey('jwk', pair.privateKey),\n _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.exportKey('jwk', pair.publicKey)\n ]);\n}\nasync function derivePublicFromPrivate(jwKey) {\n return _webcrypto_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"].get().subtle.importKey('jwk', {\n kty: jwKey.kty,\n n: jwKey.n,\n e: jwKey.e\n }, {\n name: 'RSASSA-PKCS1-v1_5',\n hash: { name: 'SHA-256' }\n }, true, ['verify']);\n}\nfunction keySize(jwk) {\n if (jwk.kty !== 'RSA') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('invalid key type', 'ERR_INVALID_KEY_TYPE');\n }\n else if (jwk.n == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('invalid key modulus', 'ERR_INVALID_KEY_MODULUS');\n }\n const bytes = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(jwk.n, 'base64url');\n return bytes.length * 8;\n}\n//# sourceMappingURL=rsa-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* binding */ MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* binding */ RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* binding */ RsaPublicKey),\n/* harmony export */ fromJwk: () => (/* binding */ fromJwk),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ unmarshalRsaPrivateKey: () => (/* binding */ unmarshalRsaPrivateKey),\n/* harmony export */ unmarshalRsaPublicKey: () => (/* binding */ unmarshalRsaPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-browser.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _rsa_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./rsa.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n\n\n\n\n\n\n\n\nconst MAX_RSA_KEY_SIZE = 8192;\nclass RsaPublicKey {\n _key;\n constructor(key) {\n this._key = key;\n }\n verify(data, sig) {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_3__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkix(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n}\nclass RsaPrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey;\n }\n genSecret() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_7__[\"default\"](16);\n }\n sign(message) {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_3__.hashAndSign(this._key, message);\n }\n get public() {\n if (this._publicKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('public key not provided', 'ERR_PUBKEY_NOT_PROVIDED');\n }\n return new RsaPublicKey(this._publicKey);\n }\n marshal() {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.jwkToPkcs1(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_5__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_5__.KeyType.RSA,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_6__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(hash, 'base58btc');\n }\n /**\n * Exports the key as libp2p-key - a aes-gcm encrypted value with the key\n * derived from the password.\n *\n * To export it as a password protected PEM file, please use the `exportPEM`\n * function from `@libp2p/rsa`.\n */\n async export(password, format = 'pkcs-8') {\n if (format === 'pkcs-8') {\n return _rsa_js__WEBPACK_IMPORTED_MODULE_4__.exportToPem(this, password);\n }\n else if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_9__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nasync function unmarshalRsaPrivateKey(bytes) {\n const jwk = _rsa_js__WEBPACK_IMPORTED_MODULE_4__.pkcs1ToJwk(bytes);\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nfunction unmarshalRsaPublicKey(bytes) {\n const jwk = _rsa_js__WEBPACK_IMPORTED_MODULE_4__.pkixToJwk(bytes);\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n return new RsaPublicKey(jwk);\n}\nasync function fromJwk(jwk) {\n if (_rsa_js__WEBPACK_IMPORTED_MODULE_3__.keySize(jwk) > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.unmarshalPrivateKey(jwk);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\nasync function generateKeyPair(bits) {\n if (bits > MAX_RSA_KEY_SIZE) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('key size is too large', 'ERR_KEY_SIZE_TOO_LARGE');\n }\n const keys = await _rsa_js__WEBPACK_IMPORTED_MODULE_3__.generateKey(bits);\n return new RsaPrivateKey(keys.privateKey, keys.publicKey);\n}\n//# sourceMappingURL=rsa-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ exportToPem: () => (/* binding */ exportToPem),\n/* harmony export */ importFromPem: () => (/* binding */ importFromPem),\n/* harmony export */ jwkToPkcs1: () => (/* binding */ jwkToPkcs1),\n/* harmony export */ jwkToPkix: () => (/* binding */ jwkToPkix),\n/* harmony export */ pkcs1ToJwk: () => (/* binding */ pkcs1ToJwk),\n/* harmony export */ pkixToJwk: () => (/* binding */ pkixToJwk)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @noble/hashes/pbkdf2 */ \"./node_modules/@noble/hashes/esm/pbkdf2.js\");\n/* harmony import */ var _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/@noble/hashes/esm/sha512.js\");\n/* harmony import */ var asn1js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! asn1js */ \"./node_modules/asn1js/build/index.es.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _random_bytes_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../random-bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../webcrypto.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n\n\n\n\n\n\n\n\n\n/**\n * Convert a PKCS#1 in ASN1 DER format to a JWK key\n */\nfunction pkcs1ToJwk(bytes) {\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value;\n const key = {\n n: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[1].toBigInt()), 'base64url'),\n e: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[2].toBigInt()), 'base64url'),\n d: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[3].toBigInt()), 'base64url'),\n p: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[4].toBigInt()), 'base64url'),\n q: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[5].toBigInt()), 'base64url'),\n dp: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[6].toBigInt()), 'base64url'),\n dq: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[7].toBigInt()), 'base64url'),\n qi: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[8].toBigInt()), 'base64url'),\n kty: 'RSA',\n alg: 'RS256'\n };\n return key;\n}\n/**\n * Convert a JWK key into PKCS#1 in ASN1 DER format\n */\nfunction jwkToPkcs1(jwk) {\n if (jwk.n == null || jwk.e == null || jwk.d == null || jwk.p == null || jwk.q == null || jwk.dp == null || jwk.dq == null || jwk.qi == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: 0 }),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.n, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.e, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.d, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.p, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.q, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.dp, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.dq, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.qi, 'base64url')))\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\n/**\n * Convert a PKCIX in ASN1 DER format to a JWK key\n */\nfunction pkixToJwk(bytes) {\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(bytes);\n // @ts-expect-error this looks fragile but DER is a canonical format so we are\n // safe to have deeply property chains like this\n const values = result.valueBlock.value[1].valueBlock.value[0].valueBlock.value;\n return {\n kty: 'RSA',\n n: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[0].toBigInt()), 'base64url'),\n e: (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(bnToBuf(values[1].toBigInt()), 'base64url')\n };\n}\n/**\n * Convert a JWK key to PKCIX in ASN1 DER format\n */\nfunction jwkToPkix(jwk) {\n if (jwk.n == null || jwk.e == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('JWK was missing components', 'ERR_INVALID_PARAMETERS');\n }\n const root = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // rsaEncryption\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n }),\n // this appears to be a bug in asn1js.js - this should really be a Sequence\n // and not a BitString but it generates the same bytes as node-forge so 🤷‍♂️\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.BitString({\n valueHex: new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.n, 'base64url'))),\n asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer.fromBigInt(bufToBn((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(jwk.e, 'base64url')))\n ]\n }).toBER()\n })\n ]\n });\n const der = root.toBER();\n return new Uint8Array(der, 0, der.byteLength);\n}\nfunction bnToBuf(bn) {\n let hex = bn.toString(16);\n if (hex.length % 2 > 0) {\n hex = `0${hex}`;\n }\n const len = hex.length / 2;\n const u8 = new Uint8Array(len);\n let i = 0;\n let j = 0;\n while (i < len) {\n u8[i] = parseInt(hex.slice(j, j + 2), 16);\n i += 1;\n j += 2;\n }\n return u8;\n}\nfunction bufToBn(u8) {\n const hex = [];\n u8.forEach(function (i) {\n let h = i.toString(16);\n if (h.length % 2 > 0) {\n h = `0${h}`;\n }\n hex.push(h);\n });\n return BigInt('0x' + hex.join(''));\n}\nconst SALT_LENGTH = 16;\nconst KEY_SIZE = 32;\nconst ITERATIONS = 10000;\nasync function exportToPem(privateKey, password) {\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get();\n // PrivateKeyInfo\n const keyWrapper = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // version (0)\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: 0 }),\n // privateKeyAlgorithm\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // rsaEncryption OID\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.1.1'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n }),\n // PrivateKey\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({\n valueHex: privateKey.marshal()\n })\n ]\n });\n const keyBuf = keyWrapper.toBER();\n const keyArr = new Uint8Array(keyBuf, 0, keyBuf.byteLength);\n const salt = (0,_random_bytes_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(SALT_LENGTH);\n const encryptionKey = await (0,_noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__.pbkdf2Async)(_noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__.sha512, password, salt, {\n c: ITERATIONS,\n dkLen: KEY_SIZE\n });\n const iv = (0,_random_bytes_js__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(16);\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['encrypt']);\n const encrypted = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, keyArr);\n const pbkdf2Params = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // salt\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({ valueHex: salt }),\n // iteration count\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: ITERATIONS }),\n // key length\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Integer({ value: KEY_SIZE }),\n // AlgorithmIdentifier\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // hmacWithSHA512\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({ value: '1.2.840.113549.2.11' }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Null()\n ]\n })\n ]\n });\n const encryptionAlgorithm = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // pkcs5PBES2\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.5.13'\n }),\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // keyDerivationFunc\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // pkcs5PBKDF2\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '1.2.840.113549.1.5.12'\n }),\n // PBKDF2-params\n pbkdf2Params\n ]\n }),\n // encryptionScheme\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n // aes256-CBC\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.ObjectIdentifier({\n value: '2.16.840.1.101.3.4.1.42'\n }),\n // iv\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({\n valueHex: iv\n })\n ]\n })\n ]\n })\n ]\n });\n const finalWrapper = new asn1js__WEBPACK_IMPORTED_MODULE_0__.Sequence({\n value: [\n encryptionAlgorithm,\n new asn1js__WEBPACK_IMPORTED_MODULE_0__.OctetString({ valueHex: encrypted })\n ]\n });\n const finalWrapperBuf = finalWrapper.toBER();\n const finalWrapperArr = new Uint8Array(finalWrapperBuf, 0, finalWrapperBuf.byteLength);\n return [\n '-----BEGIN ENCRYPTED PRIVATE KEY-----',\n ...(0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(finalWrapperArr, 'base64pad').split(/(.{64})/).filter(Boolean),\n '-----END ENCRYPTED PRIVATE KEY-----'\n ].join('\\n');\n}\nasync function importFromPem(pem, password) {\n const crypto = _webcrypto_js__WEBPACK_IMPORTED_MODULE_4__[\"default\"].get();\n let plaintext;\n if (pem.includes('-----BEGIN ENCRYPTED PRIVATE KEY-----')) {\n const key = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(pem\n .replace('-----BEGIN ENCRYPTED PRIVATE KEY-----', '')\n .replace('-----END ENCRYPTED PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(key);\n const { iv, salt, iterations, keySize, cipherText } = findEncryptedPEMData(result);\n const encryptionKey = await (0,_noble_hashes_pbkdf2__WEBPACK_IMPORTED_MODULE_6__.pbkdf2Async)(_noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_7__.sha512, password, salt, {\n c: iterations,\n dkLen: keySize\n });\n const cryptoKey = await crypto.subtle.importKey('raw', encryptionKey, 'AES-CBC', false, ['decrypt']);\n const decrypted = toUint8Array(await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv\n }, cryptoKey, cipherText));\n const { result: decryptedResult } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(decrypted);\n plaintext = findPEMData(decryptedResult);\n }\n else if (pem.includes('-----BEGIN PRIVATE KEY-----')) {\n const key = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(pem\n .replace('-----BEGIN PRIVATE KEY-----', '')\n .replace('-----END PRIVATE KEY-----', '')\n .replace(/\\n/g, '')\n .trim(), 'base64pad');\n const { result } = asn1js__WEBPACK_IMPORTED_MODULE_0__.fromBER(key);\n plaintext = findPEMData(result);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Could not parse private key from PEM data', 'ERR_INVALID_PARAMETERS');\n }\n return (0,_rsa_class_js__WEBPACK_IMPORTED_MODULE_8__.unmarshalRsaPrivateKey)(plaintext);\n}\nfunction findEncryptedPEMData(root) {\n const encryptionAlgorithm = root.valueBlock.value[0];\n const scheme = encryptionAlgorithm.valueBlock.value[0].toString();\n if (scheme !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.13') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only pkcs5PBES2 encrypted private keys are supported', 'ERR_INVALID_PARAMS');\n }\n const keyDerivationFunc = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[0];\n const keyDerivationFuncName = keyDerivationFunc.valueBlock.value[0].toString();\n if (keyDerivationFuncName !== 'OBJECT IDENTIFIER : 1.2.840.113549.1.5.12') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only pkcs5PBKDF2 key derivation functions are supported', 'ERR_INVALID_PARAMS');\n }\n const pbkdf2Params = keyDerivationFunc.valueBlock.value[1];\n const salt = toUint8Array(pbkdf2Params.valueBlock.value[0].getValue());\n let iterations = ITERATIONS;\n let keySize = KEY_SIZE;\n if (pbkdf2Params.valueBlock.value.length === 3) {\n iterations = Number(pbkdf2Params.valueBlock.value[1].toBigInt());\n keySize = Number((pbkdf2Params.valueBlock.value[2]).toBigInt());\n }\n else if (pbkdf2Params.valueBlock.value.length === 2) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key', 'ERR_INVALID_PARAMS');\n }\n const encryptionScheme = encryptionAlgorithm.valueBlock.value[1].valueBlock.value[1];\n const encryptionSchemeName = encryptionScheme.valueBlock.value[0].toString();\n if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.2.840.113549.3.7') {\n // des-EDE3-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 1.3.14.3.2.7') {\n // des-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2') {\n // aes128-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22') {\n // aes192-CBC\n }\n else if (encryptionSchemeName === 'OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42') {\n // aes256-CBC\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Only AES-CBC encryption schemes are supported', 'ERR_INVALID_PARAMS');\n }\n const iv = toUint8Array(encryptionScheme.valueBlock.value[1].getValue());\n return {\n cipherText: toUint8Array(root.valueBlock.value[1].getValue()),\n salt,\n iterations,\n keySize,\n iv\n };\n}\nfunction findPEMData(seq) {\n return toUint8Array(seq.valueBlock.value[2].getValue());\n}\nfunction toUint8Array(buf) {\n return new Uint8Array(buf, 0, buf.byteLength);\n}\n//# sourceMappingURL=rsa-utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js ***! + \*********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ compressPublicKey: () => (/* binding */ compressPublicKey),\n/* harmony export */ computePublicKey: () => (/* binding */ computePublicKey),\n/* harmony export */ decompressPublicKey: () => (/* binding */ decompressPublicKey),\n/* harmony export */ generateKey: () => (/* binding */ generateKey),\n/* harmony export */ hashAndSign: () => (/* binding */ hashAndSign),\n/* harmony export */ hashAndVerify: () => (/* binding */ hashAndVerify),\n/* harmony export */ privateKeyLength: () => (/* binding */ PRIVATE_KEY_BYTE_LENGTH),\n/* harmony export */ validatePrivateKey: () => (/* binding */ validatePrivateKey),\n/* harmony export */ validatePublicKey: () => (/* binding */ validatePublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/curves/secp256k1 */ \"./node_modules/@noble/curves/esm/secp256k1.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js\");\n\n\n\n\nconst PRIVATE_KEY_BYTE_LENGTH = 32;\n\nfunction generateKey() {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.utils.randomPrivateKey();\n}\n/**\n * Hash and sign message with private key\n */\nfunction hashAndSign(key, msg) {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_2__.isPromise)(p)) {\n return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.sign(digest, key).toDERRawBytes())\n .catch(err => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.sign(p.digest, key).toDERRawBytes();\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\n/**\n * Hash message and verify signature with public key\n */\nfunction hashAndVerify(key, sig, msg) {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(msg instanceof Uint8Array ? msg : msg.subarray());\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_2__.isPromise)(p)) {\n return p.then(({ digest }) => _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.verify(sig, digest, key))\n .catch(err => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n });\n }\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.verify(sig, p.digest, key);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_INPUT');\n }\n}\nfunction compressPublicKey(key) {\n const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(true);\n return point;\n}\nfunction decompressPublicKey(key) {\n const point = _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key).toRawBytes(false);\n return point;\n}\nfunction validatePrivateKey(key) {\n try {\n _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(key, true);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\nfunction validatePublicKey(key) {\n try {\n _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.ProjectivePoint.fromHex(key);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PUBLIC_KEY');\n }\n}\nfunction computePublicKey(privateKey) {\n try {\n return _noble_curves_secp256k1__WEBPACK_IMPORTED_MODULE_1__.secp256k1.getPublicKey(privateKey, true);\n }\n catch (err) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), 'ERR_INVALID_PRIVATE_KEY');\n }\n}\n//# sourceMappingURL=secp256k1-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Secp256k1PrivateKey: () => (/* binding */ Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* binding */ Secp256k1PublicKey),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ unmarshalSecp256k1PrivateKey: () => (/* binding */ unmarshalSecp256k1PrivateKey),\n/* harmony export */ unmarshalSecp256k1PublicKey: () => (/* binding */ unmarshalSecp256k1PublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js\");\n/* harmony import */ var _exporter_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./exporter.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/exporter.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./secp256k1.js */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-browser.js\");\n\n\n\n\n\n\n\n\nclass Secp256k1PublicKey {\n _key;\n constructor(key) {\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePublicKey(key);\n this._key = key;\n }\n verify(data, sig) {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.hashAndVerify(this._key, sig, data);\n }\n marshal() {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.compressPublicKey(this._key);\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_4__.PublicKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_4__.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n async hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n let bytes;\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_5__.isPromise)(p)) {\n ({ bytes } = await p);\n }\n else {\n bytes = p.bytes;\n }\n return bytes;\n }\n}\nclass Secp256k1PrivateKey {\n _key;\n _publicKey;\n constructor(key, publicKey) {\n this._key = key;\n this._publicKey = publicKey ?? _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.computePublicKey(key);\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePrivateKey(this._key);\n _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.validatePublicKey(this._publicKey);\n }\n sign(message) {\n return _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.hashAndSign(this._key, message);\n }\n get public() {\n return new Secp256k1PublicKey(this._publicKey);\n }\n marshal() {\n return this._key;\n }\n get bytes() {\n return _keys_js__WEBPACK_IMPORTED_MODULE_4__.PrivateKey.encode({\n Type: _keys_js__WEBPACK_IMPORTED_MODULE_4__.KeyType.Secp256k1,\n Data: this.marshal()\n }).subarray();\n }\n equals(key) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.bytes, key.bytes);\n }\n hash() {\n const p = multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_0__.sha256.digest(this.bytes);\n if ((0,_util_js__WEBPACK_IMPORTED_MODULE_5__.isPromise)(p)) {\n return p.then(({ bytes }) => bytes);\n }\n return p.bytes;\n }\n /**\n * Gets the ID of the key.\n *\n * The key id is the base58 encoding of the SHA-256 multihash of its public key.\n * The public key is a protobuf encoding containing a type and the DER encoding\n * of the PKCS SubjectPublicKeyInfo.\n */\n async id() {\n const hash = await this.public.hash();\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_2__.toString)(hash, 'base58btc');\n }\n /**\n * Exports the key into a password protected `format`\n */\n async export(password, format = 'libp2p-key') {\n if (format === 'libp2p-key') {\n return (0,_exporter_js__WEBPACK_IMPORTED_MODULE_6__.exporter)(this.bytes, password);\n }\n else {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError(`export format '${format}' is not supported`, 'ERR_INVALID_EXPORT_FORMAT');\n }\n }\n}\nfunction unmarshalSecp256k1PrivateKey(bytes) {\n return new Secp256k1PrivateKey(bytes);\n}\nfunction unmarshalSecp256k1PublicKey(bytes) {\n return new Secp256k1PublicKey(bytes);\n}\nasync function generateKeyPair() {\n const privateKeyBytes = _secp256k1_js__WEBPACK_IMPORTED_MODULE_3__.generateKey();\n return new Secp256k1PrivateKey(privateKeyBytes);\n}\n//# sourceMappingURL=secp256k1-class.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ randomBytes)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n/**\n * Generates a Uint8Array with length `number` populated by random bytes\n */\nfunction randomBytes(length) {\n if (isNaN(length) || length <= 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_0__.CodeError('random bytes length must be a Number bigger than 0', 'ERR_INVALID_LENGTH');\n }\n return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes)(length);\n}\n//# sourceMappingURL=random-bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/random-bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64urlToBuffer: () => (/* binding */ base64urlToBuffer),\n/* harmony export */ isPromise: () => (/* binding */ isPromise)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n\n\nfunction base64urlToBuffer(str, len) {\n let buf = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(str, 'base64urlpad');\n if (len != null) {\n if (buf.length > len)\n throw new Error('byte array longer than desired length');\n buf = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_0__.concat)([new Uint8Array(len - buf.length), buf]);\n }\n return buf;\n}\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=util.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/util.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ AggregateCodeError: () => (/* binding */ AggregateCodeError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* binding */ ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* binding */ ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* binding */ ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* binding */ ERR_TIMEOUT),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* binding */ InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* binding */ InvalidCryptoTransmissionError),\n/* harmony export */ UnexpectedPeerError: () => (/* binding */ UnexpectedPeerError)\n/* harmony export */ });\n/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nclass AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nclass CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nclass InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nclass InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nconst ERR_TIMEOUT = 'ERR_TIMEOUT';\nconst ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nconst ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nconst ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/peer-id/index.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/peer-id/index.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPeerId: () => (/* binding */ isPeerId),\n/* harmony export */ peerIdSymbol: () => (/* binding */ peerIdSymbol)\n/* harmony export */ });\nconst peerIdSymbol = Symbol.for('@libp2p/peer-id');\nfunction isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/peer-id/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/@libp2p/peer-id/dist/src/index.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/@libp2p/peer-id/dist/src/index.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/peer-record/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/@libp2p/peer-id/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base10.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base10.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base10: () => (/* binding */ base10)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base10 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base10.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base16.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base16.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base16: () => (/* binding */ base16),\n/* harmony export */ base16upper: () => (/* binding */ base16upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base16 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nconst base16upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base16.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base2.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base2.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base2: () => (/* binding */ base2)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base2 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base2.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base256emoji.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base256emoji.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base256emoji.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base32.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base32.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base32: () => (/* binding */ base32),\n/* harmony export */ base32hex: () => (/* binding */ base32hex),\n/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),\n/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),\n/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),\n/* harmony export */ base32pad: () => (/* binding */ base32pad),\n/* harmony export */ base32padupper: () => (/* binding */ base32padupper),\n/* harmony export */ base32upper: () => (/* binding */ base32upper),\n/* harmony export */ base32z: () => (/* binding */ base32z)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nconst base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nconst base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nconst base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nconst base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nconst base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nconst base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nconst base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nconst base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base32.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base36.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base36.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base36: () => (/* binding */ base36),\n/* harmony export */ base36upper: () => (/* binding */ base36upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nconst base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base36.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base58btc: () => (/* binding */ base58btc),\n/* harmony export */ base58flickr: () => (/* binding */ base58flickr)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nconst base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64pad: () => (/* binding */ base64pad),\n/* harmony export */ base64url: () => (/* binding */ base64url),\n/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nconst base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nconst base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nconst base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base8.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base8.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base8: () => (/* binding */ base8)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base8 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base8.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/identity.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/identity.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base.js\");\n\n\nconst identity = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.from)({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.toString)(buf),\n decode: (str) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.fromString)(str)\n});\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/interface.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/interface.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// Base encoders / decoders just base encode / decode between binary and\n// textual representation. They are unaware of multibase.\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/basics.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/basics.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.CID),\n/* harmony export */ bases: () => (/* binding */ bases),\n/* harmony export */ bytes: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.bytes),\n/* harmony export */ codecs: () => (/* binding */ codecs),\n/* harmony export */ digest: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.digest),\n/* harmony export */ hasher: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.hasher),\n/* harmony export */ hashes: () => (/* binding */ hashes),\n/* harmony export */ varint: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.varint)\n/* harmony export */ });\n/* harmony import */ var _bases_base10_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base10.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base10.js\");\n/* harmony import */ var _bases_base16_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base16.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base16.js\");\n/* harmony import */ var _bases_base2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base2.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base2.js\");\n/* harmony import */ var _bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bases/base256emoji.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base256emoji.js\");\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bases_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./bases/base64.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _bases_base8_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bases/base8.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base8.js\");\n/* harmony import */ var _bases_identity_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bases/identity.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/identity.js\");\n/* harmony import */ var _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./codecs/json.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/json.js\");\n/* harmony import */ var _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./codecs/raw.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/raw.js\");\n/* harmony import */ var _hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./hashes/identity.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var _hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./hashes/sha2.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/index.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst bases = { ..._bases_identity_js__WEBPACK_IMPORTED_MODULE_9__, ..._bases_base2_js__WEBPACK_IMPORTED_MODULE_2__, ..._bases_base8_js__WEBPACK_IMPORTED_MODULE_8__, ..._bases_base10_js__WEBPACK_IMPORTED_MODULE_0__, ..._bases_base16_js__WEBPACK_IMPORTED_MODULE_1__, ..._bases_base32_js__WEBPACK_IMPORTED_MODULE_4__, ..._bases_base36_js__WEBPACK_IMPORTED_MODULE_5__, ..._bases_base58_js__WEBPACK_IMPORTED_MODULE_6__, ..._bases_base64_js__WEBPACK_IMPORTED_MODULE_7__, ..._bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ };\nconst hashes = { ..._hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__, ..._hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ };\nconst codecs = { raw: _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__, json: _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ };\n\n//# sourceMappingURL=basics.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/basics.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/block/interface.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/block/interface.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/block/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ empty: () => (/* binding */ empty),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ fromHex: () => (/* binding */ fromHex),\n/* harmony export */ fromString: () => (/* binding */ fromString),\n/* harmony export */ isBinary: () => (/* binding */ isBinary),\n/* harmony export */ toHex: () => (/* binding */ toHex),\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\nconst empty = new Uint8Array(0);\nfunction toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nfunction fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nfunction equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nfunction coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nfunction isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nfunction fromString(str) {\n return new TextEncoder().encode(str);\n}\nfunction toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/cid.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/cid.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/cid.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/interface.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/interface.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/json.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/json.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nconst name = 'json';\nconst code = 0x0200;\nfunction encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nfunction decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/json.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/raw.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/raw.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n\nconst name = 'raw';\nconst code = 0x55;\nfunction encode(node) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(node);\n}\nfunction decode(data) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(data);\n}\n//# sourceMappingURL=raw.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/raw.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/hasher.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/hasher.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hasher: () => (/* binding */ Hasher),\n/* harmony export */ from: () => (/* binding */ from)\n/* harmony export */ });\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js\");\n\nfunction from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nclass Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/hasher.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js\");\n\n\nconst code = 0x0;\nconst name = 'identity';\nconst encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;\nfunction digest(input) {\n return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));\n}\nconst identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/interface.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/interface.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// # Multihash\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha256: () => (/* binding */ sha256),\n/* harmony export */ sha512: () => (/* binding */ sha512)\n/* harmony export */ });\n/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* global crypto */\n\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nconst sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nconst sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/sha2-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/index.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/index.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),\n/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),\n/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),\n/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/interface.js\");\n/**\n * @packageDocumentation\n *\n * This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.\n *\n * This library provides implementations for most basics and many others can be found in linked repositories.\n *\n * ```TypeScript\n * import { CID } from 'multiformats/cid'\n * import * as json from 'multiformats/codecs/json'\n * import { sha256 } from 'multiformats/hashes/sha2'\n *\n * const bytes = json.encode({ hello: 'world' })\n *\n * const hash = await sha256.digest(bytes)\n * const cid = CID.create(1, json.code, hash)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Creating Blocks\n *\n * ```TypeScript\n * import * as Block from 'multiformats/block'\n * import * as codec from '@ipld/dag-cbor'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * const value = { hello: 'world' }\n *\n * // encode a block\n * let block = await Block.encode({ value, codec, hasher })\n *\n * block.value // { hello: 'world' }\n * block.bytes // Uint8Array\n * block.cid // CID() w/ sha2-256 hash address and dag-cbor codec\n *\n * // you can also decode blocks from their binary state\n * block = await Block.decode({ bytes: block.bytes, codec, hasher })\n *\n * // if you have the cid you can also verify the hash on decode\n * block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })\n * ```\n *\n * ## Multibase Encoders / Decoders / Codecs\n *\n * CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:\n *\n * ```TypeScript\n * import { base64 } from \"multiformats/bases/base64\"\n * cid.toString(base64.encoder)\n * //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'\n * ```\n *\n * Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:\n *\n * ```TypeScript\n * CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * Dual of multibase encoder & decoder is defined as multibase codec and it exposes\n * them as `encoder` and `decoder` properties. For added convenience codecs also\n * implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be\n * used as either or both:\n *\n * ```TypeScript\n * cid.toString(base64)\n * CID.parse(cid.toString(base64), base64)\n * ```\n *\n * **Note:** CID implementation comes bundled with `base32` and `base58btc`\n * multibase codecs so that CIDs can be base serialized to (version specific)\n * default base encoding and parsed without having to supply base encoders/decoders:\n *\n * ```TypeScript\n * const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')\n * v1.toString()\n * //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'\n *\n * const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n * v0.toString()\n * //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'\n * v0.toV1().toString()\n * //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'\n * ```\n *\n * ## Multicodec Encoders / Decoders / Codecs\n *\n * This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).\n * Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.\n * Here is an example implementation of JSON `BlockCodec`.\n *\n * ```TypeScript\n * export const { name, code, encode, decode } = {\n * name: 'json',\n * code: 0x0200,\n * encode: json => new TextEncoder().encode(JSON.stringify(json)),\n * decode: bytes => JSON.parse(new TextDecoder().decode(bytes))\n * }\n * ```\n *\n * ## Multihash Hashers\n *\n * This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:\n *\n * ```TypeScript\n * import * as hasher from 'multiformats/hashes/hasher'\n *\n * const sha256 = hasher.from({\n * // As per multiformats table\n * // https://github.com/multiformats/multicodec/blob/master/table.csv#L9\n * name: 'sha2-256',\n * code: 0x12,\n *\n * encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())\n * })\n *\n * const hash = await sha256.digest(json.encode({ hello: 'world' }))\n * CID.create(1, json.code, hash)\n *\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Traversal\n *\n * This library contains higher-order functions for traversing graphs of data easily.\n *\n * `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.\n *\n * ```TypeScript\n * import { walk } from 'multiformats/traversal'\n * import * as Block from 'multiformats/block'\n * import * as codec from 'multiformats/codecs/json'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * // build a DAG (a single block for this simple example)\n * const value = { hello: 'world' }\n * const block = await Block.encode({ value, codec, hasher })\n * const { cid } = block\n * console.log(cid)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n *\n * // create a loader function that also collects CIDs of blocks in\n * // their traversal order\n * const load = (cid, blocks) => async (cid) => {\n * // fetch a block using its cid\n * // e.g.: const block = await fetchBlockByCID(cid)\n * blocks.push(cid)\n * return block\n * }\n *\n * // collect blocks in this DAG starting from the root `cid`\n * const blocks = []\n * await walk({ cid, load: load(cid, blocks) })\n *\n * console.log(blocks)\n * //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]\n * ```\n *\n * ## Legacy interface\n *\n * [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an\n * [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.\n *\n * ## Implementations\n *\n * By default, no base encodings (other than base32 & base58btc), hash functions,\n * or codec implementations are exposed by `multiformats`, you need to\n * import the ones you need yourself.\n *\n * ### Multibase codecs\n *\n * | bases | import | repo |\n * | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |\n * | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n *\n * Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.\n *\n * ### Multihash hashers\n *\n * | hashes | import | repo |\n * | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |\n * | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |\n * | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |\n * | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |\n * | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |\n * | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |\n *\n * ### IPLD codecs (multicodec)\n *\n * | codec | import | repo |\n * | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |\n * | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |\n * | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |\n * | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |\n * | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |\n */\n\n\n\n\n\n// This way TS will also expose all the types from module\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/interface.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/interface.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _bases_interface_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/bases/interface.js\");\n/* harmony import */ var _hashes_interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/hashes/interface.js\");\n/* harmony import */ var _codecs_interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/codecs/interface.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/link/interface.js\");\n/* harmony import */ var _block_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./block/interface.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/block/interface.js\");\n\n\n\n\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/link/interface.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/link/interface.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */\n/* eslint-disable no-use-before-define */\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/link/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encodeTo: () => (/* binding */ encodeTo),\n/* harmony export */ encodingLength: () => (/* binding */ encodingLength)\n/* harmony export */ });\n/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/varint.js\");\n\nfunction decode(data, offset = 0) {\n const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode(data, offset);\n return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode.bytes];\n}\nfunction encodeTo(int, target, offset = 0) {\n _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encode(int, target, offset);\n return target;\n}\nfunction encodingLength(int) {\n return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/base-x.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/base-x.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);\n//# sourceMappingURL=base-x.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/base-x.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/varint.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/varint.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/vendor/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/alloc.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/alloc.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ alloc: () => (/* binding */ alloc),\n/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)\n/* harmony export */ });\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nfunction alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nfunction allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/alloc.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ concat: () => (/* binding */ concat)\n/* harmony export */ });\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var _util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #util/as-uint8array */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/as-uint8array.js\");\n\n\n/**\n * Returns a new Uint8Array created by concatenating the passed Uint8Arrays\n */\nfunction concat(arrays, length) {\n if (length == null) {\n length = arrays.reduce((acc, curr) => acc + curr.length, 0);\n }\n const output = (0,_alloc__WEBPACK_IMPORTED_MODULE_0__.allocUnsafe)(length);\n let offset = 0;\n for (const arr of arrays) {\n output.set(arr, offset);\n offset += arr.length;\n }\n return (0,_util_as_uint8array__WEBPACK_IMPORTED_MODULE_1__.asUint8Array)(output);\n}\n//# sourceMappingURL=concat.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/concat.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/equals.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fromString: () => (/* binding */ fromString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction fromString(string, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/from-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction toString(array, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/to-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/as-uint8array.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/as-uint8array.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ asUint8Array: () => (/* binding */ asUint8Array)\n/* harmony export */ });\n/**\n * To guarantee Uint8Array semantics, convert nodejs Buffers\n * into vanilla Uint8Arrays\n */\nfunction asUint8Array(buf) {\n return buf;\n}\n//# sourceMappingURL=as-uint8array.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/as-uint8array.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/bases.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/bases.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/peer-record/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/alloc.js\");\n\n\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);\n//# sourceMappingURL=bases.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/peer-record/node_modules/uint8arrays/dist/src/util/bases.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/ping/dist/src/constants.js": /*!*********************************************************!*\ !*** ./node_modules/@libp2p/ping/dist/src/constants.js ***! @@ -6959,7 +10225,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PingService: () => (/* binding */ PingService)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/crypto */ \"./node_modules/@libp2p/ping/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/ping/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_first__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-first */ \"./node_modules/it-first/dist/src/index.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/ping/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@libp2p/ping/dist/src/constants.js\");\n\n\n\n\n\n\nclass PingService {\n protocol;\n components;\n started;\n timeout;\n maxInboundStreams;\n maxOutboundStreams;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.components = components;\n this.log = components.logger.forComponent('libp2p:ping');\n this.started = false;\n this.protocol = `/${init.protocolPrefix ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_PREFIX}/${_constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_NAME}/${_constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.TIMEOUT;\n this.maxInboundStreams = init.maxInboundStreams ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_INBOUND_STREAMS;\n this.maxOutboundStreams = init.maxOutboundStreams ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_OUTBOUND_STREAMS;\n this.runOnTransientConnection = init.runOnTransientConnection ?? true;\n this.handleMessage = this.handleMessage.bind(this);\n }\n async start() {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.components.registrar.unhandle(this.protocol);\n this.started = false;\n }\n isStarted() {\n return this.started;\n }\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage(data) {\n this.log('incoming ping from %p', data.connection.remotePeer);\n const { stream } = data;\n const start = Date.now();\n void (0,it_pipe__WEBPACK_IMPORTED_MODULE_1__.pipe)(stream, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);\n })\n .finally(() => {\n const ms = Date.now() - start;\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms);\n });\n }\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping(peer, options = {}) {\n this.log('pinging %p', peer);\n const start = Date.now();\n const data = (0,_libp2p_crypto__WEBPACK_IMPORTED_MODULE_4__[\"default\"])(_constants_js__WEBPACK_IMPORTED_MODULE_3__.PING_LENGTH);\n const connection = await this.components.connectionManager.openConnection(peer, options);\n let stream;\n let onAbort = () => { };\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n onAbort = () => {\n stream?.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError('ping timeout', _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.ERR_TIMEOUT));\n };\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true });\n const result = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_1__.pipe)([data], stream, async (source) => (0,it_first__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(source));\n const ms = Date.now() - start;\n if (result == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError(`Did not receive a ping ack after ${ms}ms`, _constants_js__WEBPACK_IMPORTED_MODULE_3__.ERR_WRONG_PING_ACK);\n }\n if (!(0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(data, result.subarray())) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError(`Received wrong ping ack after ${ms}ms`, _constants_js__WEBPACK_IMPORTED_MODULE_3__.ERR_WRONG_PING_ACK);\n }\n this.log('ping %p complete in %dms', connection.remotePeer, ms);\n return ms;\n }\n catch (err) {\n this.log.error('error while pinging %p', connection.remotePeer, err);\n stream?.abort(err);\n throw err;\n }\n finally {\n options.signal?.removeEventListener('abort', onAbort);\n if (stream != null) {\n await stream.close();\n }\n }\n }\n}\n//# sourceMappingURL=ping.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/ping/dist/src/ping.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PingService: () => (/* binding */ PingService)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/crypto */ \"./node_modules/@libp2p/ping/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/ping/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_first__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-first */ \"./node_modules/it-first/dist/src/index.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/ping/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@libp2p/ping/dist/src/constants.js\");\n\n\n\n\n\n\nclass PingService {\n protocol;\n components;\n started;\n timeout;\n maxInboundStreams;\n maxOutboundStreams;\n runOnTransientConnection;\n log;\n constructor(components, init = {}) {\n this.components = components;\n this.log = components.logger.forComponent('libp2p:ping');\n this.started = false;\n this.protocol = `/${init.protocolPrefix ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_PREFIX}/${_constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_NAME}/${_constants_js__WEBPACK_IMPORTED_MODULE_3__.PROTOCOL_VERSION}`;\n this.timeout = init.timeout ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.TIMEOUT;\n this.maxInboundStreams = init.maxInboundStreams ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_INBOUND_STREAMS;\n this.maxOutboundStreams = init.maxOutboundStreams ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_OUTBOUND_STREAMS;\n this.runOnTransientConnection = init.runOnTransientConnection ?? true;\n this.handleMessage = this.handleMessage.bind(this);\n }\n [Symbol.toStringTag] = '@libp2p/ping';\n async start() {\n await this.components.registrar.handle(this.protocol, this.handleMessage, {\n maxInboundStreams: this.maxInboundStreams,\n maxOutboundStreams: this.maxOutboundStreams,\n runOnTransientConnection: this.runOnTransientConnection\n });\n this.started = true;\n }\n async stop() {\n await this.components.registrar.unhandle(this.protocol);\n this.started = false;\n }\n isStarted() {\n return this.started;\n }\n /**\n * A handler to register with Libp2p to process ping messages\n */\n handleMessage(data) {\n this.log('incoming ping from %p', data.connection.remotePeer);\n const { stream } = data;\n const start = Date.now();\n const signal = AbortSignal.timeout(this.timeout);\n signal.addEventListener('abort', () => {\n stream?.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('ping timeout', _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.ERR_TIMEOUT));\n });\n void (0,it_pipe__WEBPACK_IMPORTED_MODULE_1__.pipe)(stream, async function* (source) {\n let received = 0;\n for await (const buf of source) {\n received += buf.byteLength;\n if (received > _constants_js__WEBPACK_IMPORTED_MODULE_3__.PING_LENGTH) {\n stream?.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Too much data received', _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.ERR_INVALID_MESSAGE));\n return;\n }\n yield buf;\n }\n }, stream)\n .catch(err => {\n this.log.error('incoming ping from %p failed with error', data.connection.remotePeer, err);\n stream?.abort(err);\n })\n .finally(() => {\n const ms = Date.now() - start;\n this.log('incoming ping from %p complete in %dms', data.connection.remotePeer, ms);\n });\n }\n /**\n * Ping a given peer and wait for its response, getting the operation latency.\n */\n async ping(peer, options = {}) {\n this.log('pinging %p', peer);\n const start = Date.now();\n const data = (0,_libp2p_crypto__WEBPACK_IMPORTED_MODULE_5__[\"default\"])(_constants_js__WEBPACK_IMPORTED_MODULE_3__.PING_LENGTH);\n const connection = await this.components.connectionManager.openConnection(peer, options);\n let stream;\n let onAbort = () => { };\n if (options.signal == null) {\n const signal = AbortSignal.timeout(this.timeout);\n options = {\n ...options,\n signal\n };\n }\n try {\n stream = await connection.newStream(this.protocol, {\n ...options,\n runOnTransientConnection: this.runOnTransientConnection\n });\n onAbort = () => {\n stream?.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('ping timeout', _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.ERR_TIMEOUT));\n };\n // make stream abortable\n options.signal?.addEventListener('abort', onAbort, { once: true });\n const result = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_1__.pipe)([data], stream, async (source) => (0,it_first__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(source));\n const ms = Date.now() - start;\n if (result == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`Did not receive a ping ack after ${ms}ms`, _constants_js__WEBPACK_IMPORTED_MODULE_3__.ERR_WRONG_PING_ACK);\n }\n if (!(0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(data, result.subarray())) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`Received wrong ping ack after ${ms}ms`, _constants_js__WEBPACK_IMPORTED_MODULE_3__.ERR_WRONG_PING_ACK);\n }\n this.log('ping %p complete in %dms', connection.remotePeer, ms);\n return ms;\n }\n catch (err) {\n this.log.error('error while pinging %p', connection.remotePeer, err);\n stream?.abort(err);\n throw err;\n }\n finally {\n options.signal?.removeEventListener('abort', onAbort);\n if (stream != null) {\n await stream.close();\n }\n }\n }\n}\n//# sourceMappingURL=ping.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/ping/dist/src/ping.js?"); /***/ }), @@ -7058,7 +10324,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/pubsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/pubsub/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/pubsub/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/@libp2p/peer-id/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/pubsub/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/pubsub/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/pubsub/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/pubsub/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@libp2p/pubsub/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -7069,7 +10335,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -7113,7 +10379,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -7234,7 +10500,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -7278,7 +10544,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/pubsub/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -7447,6 +10713,677 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/utils/dist/src/abstract-stream.js": +/*!****************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/abstract-stream.js ***! + \****************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbstractStream: () => (/* binding */ AbstractStream)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _close_source_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./close-source.js */ \"./node_modules/@libp2p/utils/dist/src/close-source.js\");\n\n\n\n\n\n\n\nconst ERR_STREAM_RESET = 'ERR_STREAM_RESET';\nconst ERR_SINK_INVALID_STATE = 'ERR_SINK_INVALID_STATE';\nconst DEFAULT_SEND_CLOSE_WRITE_TIMEOUT = 5000;\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\nclass AbstractStream {\n id;\n direction;\n timeline;\n protocol;\n metadata;\n source;\n status;\n readStatus;\n writeStatus;\n log;\n sinkController;\n sinkEnd;\n closed;\n endErr;\n streamSource;\n onEnd;\n onCloseRead;\n onCloseWrite;\n onReset;\n onAbort;\n sendCloseWriteTimeout;\n sendingData;\n constructor(init) {\n this.sinkController = new AbortController();\n this.sinkEnd = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n this.closed = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n this.log = init.log;\n // stream status\n this.status = 'open';\n this.readStatus = 'ready';\n this.writeStatus = 'ready';\n this.id = init.id;\n this.metadata = init.metadata ?? {};\n this.direction = init.direction;\n this.timeline = {\n open: Date.now()\n };\n this.sendCloseWriteTimeout = init.sendCloseWriteTimeout ?? DEFAULT_SEND_CLOSE_WRITE_TIMEOUT;\n this.onEnd = init.onEnd;\n this.onCloseRead = init?.onCloseRead;\n this.onCloseWrite = init?.onCloseWrite;\n this.onReset = init?.onReset;\n this.onAbort = init?.onAbort;\n this.source = this.streamSource = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({\n onEnd: (err) => {\n if (err != null) {\n this.log.trace('source ended with error', err);\n }\n else {\n this.log.trace('source ended');\n }\n this.onSourceEnd(err);\n }\n });\n // necessary because the libp2p upgrader wraps the sink function\n this.sink = this.sink.bind(this);\n }\n async sink(source) {\n if (this.writeStatus !== 'ready') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`writable end state is \"${this.writeStatus}\" not \"ready\"`, ERR_SINK_INVALID_STATE);\n }\n try {\n this.writeStatus = 'writing';\n const options = {\n signal: this.sinkController.signal\n };\n if (this.direction === 'outbound') { // If initiator, open a new stream\n const res = this.sendNewStream(options);\n if (isPromise(res)) {\n await res;\n }\n }\n const abortListener = () => {\n (0,_close_source_js__WEBPACK_IMPORTED_MODULE_5__.closeSource)(source, this.log);\n };\n try {\n this.sinkController.signal.addEventListener('abort', abortListener);\n this.log.trace('sink reading from source');\n for await (let data of source) {\n data = data instanceof Uint8Array ? new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(data) : data;\n const res = this.sendData(data, options);\n if (isPromise(res)) {\n this.sendingData = (0,p_defer__WEBPACK_IMPORTED_MODULE_3__[\"default\"])();\n await res;\n this.sendingData.resolve();\n this.sendingData = undefined;\n }\n }\n }\n finally {\n this.sinkController.signal.removeEventListener('abort', abortListener);\n }\n this.log.trace('sink finished reading from source, write status is \"%s\"', this.writeStatus);\n if (this.writeStatus === 'writing') {\n this.writeStatus = 'closing';\n this.log.trace('send close write to remote');\n await this.sendCloseWrite({\n signal: AbortSignal.timeout(this.sendCloseWriteTimeout)\n });\n this.writeStatus = 'closed';\n }\n this.onSinkEnd();\n }\n catch (err) {\n this.log.trace('sink ended with error, calling abort with error', err);\n this.abort(err);\n throw err;\n }\n finally {\n this.log.trace('resolve sink end');\n this.sinkEnd.resolve();\n }\n }\n onSourceEnd(err) {\n if (this.timeline.closeRead != null) {\n return;\n }\n this.timeline.closeRead = Date.now();\n this.readStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseRead?.();\n if (this.timeline.closeWrite != null) {\n this.log.trace('source and sink ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('source ended, waiting for sink to end');\n }\n }\n onSinkEnd(err) {\n if (this.timeline.closeWrite != null) {\n return;\n }\n this.timeline.closeWrite = Date.now();\n this.writeStatus = 'closed';\n if (err != null && this.endErr == null) {\n this.endErr = err;\n }\n this.onCloseWrite?.();\n if (this.timeline.closeRead != null) {\n this.log.trace('sink and source ended');\n this.timeline.close = Date.now();\n if (this.status !== 'aborted' && this.status !== 'reset') {\n this.status = 'closed';\n }\n if (this.onEnd != null) {\n this.onEnd(this.endErr);\n }\n this.closed.resolve();\n }\n else {\n this.log.trace('sink ended, waiting for source to end');\n }\n }\n // Close for both Reading and Writing\n async close(options) {\n this.log.trace('closing gracefully');\n this.status = 'closing';\n // wait for read and write ends to close\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(Promise.all([\n this.closeWrite(options),\n this.closeRead(options),\n this.closed.promise\n ]), options?.signal);\n this.status = 'closed';\n this.log.trace('closed gracefully');\n }\n async closeRead(options = {}) {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n return;\n }\n this.log.trace('closing readable end of stream with starting read status \"%s\"', this.readStatus);\n const readStatus = this.readStatus;\n this.readStatus = 'closing';\n if (this.status !== 'reset' && this.status !== 'aborted' && this.timeline.closeRead == null) {\n this.log.trace('send close read to remote');\n await this.sendCloseRead(options);\n }\n if (readStatus === 'ready') {\n this.log.trace('ending internal source queue with %d queued bytes', this.streamSource.readableLength);\n this.streamSource.end();\n }\n this.log.trace('closed readable end of stream');\n }\n async closeWrite(options = {}) {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n return;\n }\n this.log.trace('closing writable end of stream with starting write status \"%s\"', this.writeStatus);\n if (this.writeStatus === 'ready') {\n this.log.trace('sink was never sunk, sink an empty array');\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sink([]), options.signal);\n }\n if (this.writeStatus === 'writing') {\n // try to let sending outgoing data succeed\n if (this.sendingData != null) {\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sendingData.promise, options.signal);\n }\n // stop reading from the source passed to `.sink`\n this.log.trace('aborting source passed to .sink');\n this.sinkController.abort();\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_1__.raceSignal)(this.sinkEnd.promise, options.signal);\n }\n this.writeStatus = 'closed';\n this.log.trace('closed writable end of stream');\n }\n /**\n * Close immediately for reading and writing and send a reset message (local\n * error)\n */\n abort(err) {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n this.log('abort with error', err);\n // try to send a reset message\n this.log('try to send reset to remote');\n const res = this.sendReset();\n if (isPromise(res)) {\n res.catch((err) => {\n this.log.error('error sending reset message', err);\n });\n }\n this.status = 'aborted';\n this.timeline.abort = Date.now();\n this._closeSinkAndSource(err);\n this.onAbort?.(err);\n }\n /**\n * Receive a reset message - close immediately for reading and writing (remote\n * error)\n */\n reset() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n return;\n }\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('stream reset', ERR_STREAM_RESET);\n this.status = 'reset';\n this.timeline.reset = Date.now();\n this._closeSinkAndSource(err);\n this.onReset?.();\n }\n _closeSinkAndSource(err) {\n this._closeSink(err);\n this._closeSource(err);\n }\n _closeSink(err) {\n // if the sink function is running, cause it to end\n if (this.writeStatus === 'writing') {\n this.log.trace('end sink source');\n this.sinkController.abort();\n }\n this.onSinkEnd(err);\n }\n _closeSource(err) {\n // if the source is not ending, end it\n if (this.readStatus !== 'closing' && this.readStatus !== 'closed') {\n this.log.trace('ending source with %d bytes to be read by consumer', this.streamSource.readableLength);\n this.readStatus = 'closing';\n this.streamSource.end(err);\n }\n }\n /**\n * The remote closed for writing so we should expect to receive no more\n * messages\n */\n remoteCloseWrite() {\n if (this.readStatus === 'closing' || this.readStatus === 'closed') {\n this.log('received remote close write but local source is already closed');\n return;\n }\n this.log.trace('remote close write');\n this._closeSource();\n }\n /**\n * The remote closed for reading so we should not send any more\n * messages\n */\n remoteCloseRead() {\n if (this.writeStatus === 'closing' || this.writeStatus === 'closed') {\n this.log('received remote close read but local sink is already closed');\n return;\n }\n this.log.trace('remote close read');\n this._closeSink();\n }\n /**\n * The underlying muxer has closed, no more messages can be sent or will\n * be received, close immediately to free up resources\n */\n destroy() {\n if (this.status === 'closed' || this.status === 'aborted' || this.status === 'reset') {\n this.log('received destroy but we are already closed');\n return;\n }\n this.log.trace('stream destroyed');\n this._closeSinkAndSource();\n }\n /**\n * When an extending class reads data from it's implementation-specific source,\n * call this method to allow the stream consumer to read the data.\n */\n sourcePush(data) {\n this.streamSource.push(data);\n }\n /**\n * Returns the amount of unread data - can be used to prevent large amounts of\n * data building up when the stream consumer is too slow.\n */\n sourceReadableLength() {\n return this.streamSource.readableLength;\n }\n}\n//# sourceMappingURL=abstract-stream.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/abstract-stream.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/adaptive-timeout.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/adaptive-timeout.js ***! + \*****************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AdaptiveTimeout: () => (/* binding */ AdaptiveTimeout),\n/* harmony export */ DEFAULT_FAILURE_MULTIPLIER: () => (/* binding */ DEFAULT_FAILURE_MULTIPLIER),\n/* harmony export */ DEFAULT_MIN_TIMEOUT: () => (/* binding */ DEFAULT_MIN_TIMEOUT),\n/* harmony export */ DEFAULT_TIMEOUT_MULTIPLIER: () => (/* binding */ DEFAULT_TIMEOUT_MULTIPLIER)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var any_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! any-signal */ \"./node_modules/any-signal/dist/src/index.js\");\n/* harmony import */ var _moving_average_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./moving-average.js */ \"./node_modules/@libp2p/utils/dist/src/moving-average.js\");\n\n\n\nconst DEFAULT_TIMEOUT_MULTIPLIER = 1.2;\nconst DEFAULT_FAILURE_MULTIPLIER = 2;\nconst DEFAULT_MIN_TIMEOUT = 2000;\nclass AdaptiveTimeout {\n success;\n failure;\n next;\n metric;\n timeoutMultiplier;\n failureMultiplier;\n minTimeout;\n constructor(init = {}) {\n this.success = new _moving_average_js__WEBPACK_IMPORTED_MODULE_1__.MovingAverage(init.interval ?? 5000);\n this.failure = new _moving_average_js__WEBPACK_IMPORTED_MODULE_1__.MovingAverage(init.interval ?? 5000);\n this.next = new _moving_average_js__WEBPACK_IMPORTED_MODULE_1__.MovingAverage(init.interval ?? 5000);\n this.failureMultiplier = init.failureMultiplier ?? DEFAULT_FAILURE_MULTIPLIER;\n this.timeoutMultiplier = init.timeoutMultiplier ?? DEFAULT_TIMEOUT_MULTIPLIER;\n this.minTimeout = init.minTimeout ?? DEFAULT_MIN_TIMEOUT;\n if (init.metricName != null) {\n this.metric = init.metrics?.registerMetricGroup(init.metricName);\n }\n }\n getTimeoutSignal(options = {}) {\n // calculate timeout for individual peers based on moving average of\n // previous successful requests\n const timeout = Math.max(Math.round(this.next.movingAverage * (options.timeoutFactor ?? this.timeoutMultiplier)), this.minTimeout);\n const sendTimeout = AbortSignal.timeout(timeout);\n const timeoutSignal = (0,any_signal__WEBPACK_IMPORTED_MODULE_0__.anySignal)([options.signal, sendTimeout]);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.setMaxListeners)(Infinity, timeoutSignal, sendTimeout);\n timeoutSignal.start = Date.now();\n timeoutSignal.timeout = timeout;\n return timeoutSignal;\n }\n cleanUp(signal) {\n const time = Date.now() - signal.start;\n if (signal.aborted) {\n this.failure.push(time);\n this.next.push(time * this.failureMultiplier);\n this.metric?.update({\n failureMovingAverage: this.failure.movingAverage,\n failureDeviation: this.failure.deviation,\n failureForecast: this.failure.forecast,\n failureVariance: this.failure.variance,\n failure: time\n });\n }\n else {\n this.success.push(time);\n this.next.push(time);\n this.metric?.update({\n successMovingAverage: this.success.movingAverage,\n successDeviation: this.success.deviation,\n successForecast: this.success.forecast,\n successVariance: this.success.variance,\n success: time\n });\n }\n }\n}\n//# sourceMappingURL=adaptive-timeout.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/adaptive-timeout.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/address-sort.js": +/*!*************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/address-sort.js ***! + \*************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ certifiedAddressesFirst: () => (/* binding */ certifiedAddressesFirst),\n/* harmony export */ circuitRelayAddressesLast: () => (/* binding */ circuitRelayAddressesLast),\n/* harmony export */ defaultAddressSort: () => (/* binding */ defaultAddressSort),\n/* harmony export */ publicAddressesFirst: () => (/* binding */ publicAddressesFirst)\n/* harmony export */ });\n/* harmony import */ var _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr-matcher */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js\");\n/* harmony import */ var _multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multiaddr/is-private.js */ \"./node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js\");\n/**\n * @packageDocumentation\n *\n * Provides strategies to sort a list of multiaddrs.\n *\n * @example\n *\n * ```typescript\n * import { publicAddressesFirst } from '@libp2p/utils/address-sort'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n *\n * const addresses = [\n * multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * multiaddr('/ip4/82.41.53.1/tcp/9000')\n * ].sort(publicAddressesFirst)\n *\n * console.info(addresses)\n * // ['/ip4/82.41.53.1/tcp/9000', '/ip4/127.0.0.1/tcp/9000']\n * ```\n */\n\n\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nfunction publicAddressesFirst(a, b) {\n const isAPrivate = (0,_multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__.isPrivate)(a.multiaddr);\n const isBPrivate = (0,_multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__.isPrivate)(b.multiaddr);\n if (isAPrivate && !isBPrivate) {\n return 1;\n }\n else if (!isAPrivate && isBPrivate) {\n return -1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nfunction certifiedAddressesFirst(a, b) {\n if (a.isCertified && !b.isCertified) {\n return -1;\n }\n else if (!a.isCertified && b.isCertified) {\n return 1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * start of the array.\n */\nfunction circuitRelayAddressesLast(a, b) {\n const isACircuit = _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__.Circuit.exactMatch(a.multiaddr);\n const isBCircuit = _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__.Circuit.exactMatch(b.multiaddr);\n if (isACircuit && !isBCircuit) {\n return 1;\n }\n else if (!isACircuit && isBCircuit) {\n return -1;\n }\n return 0;\n}\nfunction defaultAddressSort(a, b) {\n const publicResult = publicAddressesFirst(a, b);\n if (publicResult !== 0) {\n return publicResult;\n }\n const relayResult = circuitRelayAddressesLast(a, b);\n if (relayResult !== 0) {\n return relayResult;\n }\n const certifiedResult = certifiedAddressesFirst(a, b);\n return certifiedResult;\n}\n//# sourceMappingURL=address-sort.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/address-sort.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/array-equals.js": +/*!*************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/array-equals.js ***! + \*************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ arrayEquals: () => (/* binding */ arrayEquals)\n/* harmony export */ });\n/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nfunction arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/array-equals.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/close-source.js": +/*!*************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/close-source.js ***! + \*************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ closeSource: () => (/* binding */ closeSource)\n/* harmony export */ });\n/* harmony import */ var get_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! get-iterator */ \"./node_modules/get-iterator/dist/src/index.js\");\n/* harmony import */ var _is_promise_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./is-promise.js */ \"./node_modules/@libp2p/utils/dist/src/is-promise.js\");\n\n\nfunction closeSource(source, log) {\n const res = (0,get_iterator__WEBPACK_IMPORTED_MODULE_0__.getIterator)(source).return?.();\n if ((0,_is_promise_js__WEBPACK_IMPORTED_MODULE_1__.isPromise)(res)) {\n res.catch(err => {\n log.error('could not cause iterator to return', err);\n });\n }\n}\n//# sourceMappingURL=close-source.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/close-source.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/close.js": +/*!******************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/close.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ safelyCloseConnectionIfUnused: () => (/* binding */ safelyCloseConnectionIfUnused),\n/* harmony export */ safelyCloseStream: () => (/* binding */ safelyCloseStream)\n/* harmony export */ });\n/**\n * Close the passed stream, falling back to aborting the stream if closing\n * cleanly fails.\n */\nasync function safelyCloseStream(stream, options) {\n try {\n await stream?.close(options);\n }\n catch (err) {\n stream?.abort(err);\n }\n}\n/**\n * These are speculative protocols that are run automatically on connection open\n * so are usually not the reason the connection was opened.\n *\n * Consequently when requested it should be safe to close connections that only\n * have these protocol streams open.\n */\nconst DEFAULT_CLOSABLE_PROTOCOLS = [\n // identify\n '/ipfs/id/1.0.0',\n // identify-push\n '/ipfs/id/push/1.0.0',\n // autonat\n '/libp2p/autonat/1.0.0',\n // dcutr\n '/libp2p/dcutr'\n];\n/**\n * Close the passed connection if it has no streams, or only closable protocol\n * streams, falling back to aborting the connection if closing it cleanly fails.\n */\nasync function safelyCloseConnectionIfUnused(connection, options) {\n const streamProtocols = connection?.streams?.map(stream => stream.protocol) ?? [];\n const closableProtocols = options?.closableProtocols ?? DEFAULT_CLOSABLE_PROTOCOLS;\n // if the connection has protocols not in the closable protocols list, do not\n // close the connection\n if (streamProtocols.filter(proto => proto != null && !closableProtocols.includes(proto)).length > 0) {\n return;\n }\n try {\n await connection?.close(options);\n }\n catch (err) {\n connection?.abort(err);\n }\n}\n//# sourceMappingURL=close.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/close.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/bucket.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/bucket.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Bucket: () => (/* binding */ Bucket)\n/* harmony export */ });\n/* harmony import */ var _fingerprint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fingerprint.js */ \"./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@libp2p/utils/dist/src/filters/utils.js\");\n\n\nclass Bucket {\n contents;\n constructor(size) {\n this.contents = new Array(size).fill(null);\n }\n has(fingerprint) {\n if (!(fingerprint instanceof _fingerprint_js__WEBPACK_IMPORTED_MODULE_0__.Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n return this.contents.some((fp) => {\n return fingerprint.equals(fp);\n });\n }\n add(fingerprint) {\n if (!(fingerprint instanceof _fingerprint_js__WEBPACK_IMPORTED_MODULE_0__.Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n for (let i = 0; i < this.contents.length; i++) {\n if (this.contents[i] == null) {\n this.contents[i] = fingerprint;\n return true;\n }\n }\n return true;\n }\n swap(fingerprint) {\n if (!(fingerprint instanceof _fingerprint_js__WEBPACK_IMPORTED_MODULE_0__.Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const i = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.getRandomInt)(0, this.contents.length - 1);\n const current = this.contents[i];\n this.contents[i] = fingerprint;\n return current;\n }\n remove(fingerprint) {\n if (!(fingerprint instanceof _fingerprint_js__WEBPACK_IMPORTED_MODULE_0__.Fingerprint)) {\n throw new TypeError('Invalid Fingerprint');\n }\n const found = this.contents.findIndex((fp) => {\n return fingerprint.equals(fp);\n });\n if (found > -1) {\n this.contents[found] = null;\n return true;\n }\n else {\n return false;\n }\n }\n}\n//# sourceMappingURL=bucket.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/bucket.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/cuckoo-filter.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/cuckoo-filter.js ***! + \**********************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CuckooFilter: () => (/* binding */ CuckooFilter),\n/* harmony export */ createCuckooFilter: () => (/* binding */ createCuckooFilter),\n/* harmony export */ optimize: () => (/* binding */ optimize)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _bucket_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bucket.js */ \"./node_modules/@libp2p/utils/dist/src/filters/bucket.js\");\n/* harmony import */ var _fingerprint_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fingerprint.js */ \"./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js\");\n/* harmony import */ var _hashes_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes.js */ \"./node_modules/@libp2p/utils/dist/src/filters/hashes.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@libp2p/utils/dist/src/filters/utils.js\");\n\n\n\n\n\nconst maxCuckooCount = 500;\nclass CuckooFilter {\n bucketSize;\n filterSize;\n fingerprintSize;\n buckets;\n count;\n hash;\n seed;\n constructor(init) {\n this.filterSize = init.filterSize;\n this.bucketSize = init.bucketSize ?? 4;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.count = 0;\n this.buckets = [];\n this.hash = init.hash ?? _hashes_js__WEBPACK_IMPORTED_MODULE_1__.fnv1a;\n this.seed = init.seed ?? (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getRandomInt)(0, Math.pow(2, 10));\n }\n add(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n const fingerprint = new _fingerprint_js__WEBPACK_IMPORTED_MODULE_3__.Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n if (this.buckets[j] == null) {\n this.buckets[j] = new _bucket_js__WEBPACK_IMPORTED_MODULE_4__.Bucket(this.bucketSize);\n }\n if (this.buckets[k] == null) {\n this.buckets[k] = new _bucket_js__WEBPACK_IMPORTED_MODULE_4__.Bucket(this.bucketSize);\n }\n if (this.buckets[j].add(fingerprint) || this.buckets[k].add(fingerprint)) {\n this.count++;\n return true;\n }\n const rand = [j, k];\n let i = rand[(0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getRandomInt)(0, rand.length - 1)];\n if (this.buckets[i] == null) {\n this.buckets[i] = new _bucket_js__WEBPACK_IMPORTED_MODULE_4__.Bucket(this.bucketSize);\n }\n for (let n = 0; n < maxCuckooCount; n++) {\n const swapped = this.buckets[i].swap(fingerprint);\n if (swapped == null) {\n continue;\n }\n i = (i ^ swapped.hash()) % this.filterSize;\n if (this.buckets[i] == null) {\n this.buckets[i] = new _bucket_js__WEBPACK_IMPORTED_MODULE_4__.Bucket(this.bucketSize);\n }\n if (this.buckets[i].add(swapped)) {\n this.count++;\n return true;\n }\n else {\n continue;\n }\n }\n return false;\n }\n has(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n const fingerprint = new _fingerprint_js__WEBPACK_IMPORTED_MODULE_3__.Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.has(fingerprint) ?? false;\n if (inJ) {\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n return this.buckets[k]?.has(fingerprint) ?? false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n const fingerprint = new _fingerprint_js__WEBPACK_IMPORTED_MODULE_3__.Fingerprint(item, this.hash, this.seed, this.fingerprintSize);\n const j = this.hash.hash(item, this.seed) % this.filterSize;\n const inJ = this.buckets[j]?.remove(fingerprint) ?? false;\n if (inJ) {\n this.count--;\n return inJ;\n }\n const k = (j ^ fingerprint.hash()) % this.filterSize;\n const inK = this.buckets[k]?.remove(fingerprint) ?? false;\n if (inK) {\n this.count--;\n }\n return inK;\n }\n get reliable() {\n return Math.floor(100 * (this.count / this.filterSize)) <= 90;\n }\n}\n// max load constants, defined in the cuckoo paper\nconst MAX_LOAD = {\n 1: 0.5,\n 2: 0.84,\n 4: 0.95,\n 8: 0.98\n};\nfunction calculateBucketSize(errorRate = 0.001) {\n if (errorRate > 0.002) {\n return 2;\n }\n if (errorRate > 0.00001) {\n return 4;\n }\n return 8;\n}\nfunction optimize(maxItems, errorRate = 0.001) {\n // https://www.eecs.harvard.edu/~michaelm/postscripts/cuckoo-conext2014.pdf\n // Section 5.1 Optimal Bucket Size\n const bucketSize = calculateBucketSize(errorRate);\n const load = MAX_LOAD[bucketSize];\n // https://stackoverflow.com/questions/57555236/how-to-size-a-cuckoo-filter/57617208#57617208\n const filterSize = Math.round(maxItems / load);\n const fingerprintSize = Math.min(Math.ceil(Math.log2(1 / errorRate) + Math.log2(2 * bucketSize)), _fingerprint_js__WEBPACK_IMPORTED_MODULE_3__.MAX_FINGERPRINT_SIZE);\n return {\n filterSize,\n bucketSize,\n fingerprintSize\n };\n}\nfunction createCuckooFilter(maxItems, errorRate = 0.005) {\n const opts = optimize(maxItems, errorRate);\n return new CuckooFilter(opts);\n}\n//# sourceMappingURL=cuckoo-filter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/cuckoo-filter.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js": +/*!********************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js ***! + \********************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Fingerprint: () => (/* binding */ Fingerprint),\n/* harmony export */ MAX_FINGERPRINT_SIZE: () => (/* binding */ MAX_FINGERPRINT_SIZE)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/alloc */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/alloc.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/equals.js\");\n\n\nconst MAX_FINGERPRINT_SIZE = 64;\nclass Fingerprint {\n fp;\n h;\n seed;\n constructor(buf, hash, seed, fingerprintSize = 2) {\n if (fingerprintSize > MAX_FINGERPRINT_SIZE) {\n throw new TypeError('Invalid Fingerprint Size');\n }\n const fnv = hash.hashV(buf, seed);\n const fp = (0,uint8arrays_alloc__WEBPACK_IMPORTED_MODULE_0__.alloc)(fingerprintSize);\n for (let i = 0; i < fp.length; i++) {\n fp[i] = fnv[i];\n }\n if (fp.length === 0) {\n fp[0] = 7;\n }\n this.fp = fp;\n this.h = hash;\n this.seed = seed;\n }\n hash() {\n return this.h.hash(this.fp, this.seed);\n }\n equals(other) {\n if (!(other?.fp instanceof Uint8Array)) {\n return false;\n }\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_1__.equals)(this.fp, other.fp);\n }\n}\n//# sourceMappingURL=fingerprint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/fingerprint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/hashes.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/hashes.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fnv1a: () => (/* binding */ fnv1a),\n/* harmony export */ murmur3: () => (/* binding */ murmur3),\n/* harmony export */ numberToBuffer: () => (/* binding */ numberToBuffer)\n/* harmony export */ });\n/* harmony import */ var _sindresorhus_fnv1a__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @sindresorhus/fnv1a */ \"./node_modules/@sindresorhus/fnv1a/index.js\");\n/* harmony import */ var murmurhash3js_revisited__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! murmurhash3js-revisited */ \"./node_modules/murmurhash3js-revisited/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js\");\n\n\n\nconst murmur3 = {\n hash: (input, seed) => {\n return murmurhash3js_revisited__WEBPACK_IMPORTED_MODULE_0__.x86.hash32(input, seed);\n },\n hashV: (input, seed) => {\n return numberToBuffer(murmur3.hash(input, seed));\n }\n};\nconst fnv1a = {\n hash: (input) => {\n return Number((0,_sindresorhus_fnv1a__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(input, {\n size: 32\n }));\n },\n hashV: (input, seed) => {\n return numberToBuffer(fnv1a.hash(input, seed));\n }\n};\nfunction numberToBuffer(num) {\n let hex = num.toString(16);\n if (hex.length % 2 === 1) {\n hex = `0${hex}`;\n }\n return (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_1__.fromString)(hex, 'base16');\n}\n//# sourceMappingURL=hashes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/hashes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/scalable-cuckoo-filter.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/scalable-cuckoo-filter.js ***! + \*******************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ScalableCuckooFilter: () => (/* binding */ ScalableCuckooFilter),\n/* harmony export */ createScalableCuckooFilter: () => (/* binding */ createScalableCuckooFilter)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _cuckoo_filter_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./cuckoo-filter.js */ \"./node_modules/@libp2p/utils/dist/src/filters/cuckoo-filter.js\");\n/* harmony import */ var _hashes_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes.js */ \"./node_modules/@libp2p/utils/dist/src/filters/hashes.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@libp2p/utils/dist/src/filters/utils.js\");\n\n\n\n\nclass ScalableCuckooFilter {\n filterSize;\n bucketSize;\n fingerprintSize;\n scale;\n filterSeries;\n hash;\n seed;\n constructor(init) {\n this.bucketSize = init.bucketSize ?? 4;\n this.filterSize = init.filterSize ?? (1 << 18) / this.bucketSize;\n this.fingerprintSize = init.fingerprintSize ?? 2;\n this.scale = init.scale ?? 2;\n this.hash = init.hash ?? _hashes_js__WEBPACK_IMPORTED_MODULE_1__.fnv1a;\n this.seed = init.seed ?? (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.getRandomInt)(0, Math.pow(2, 10));\n this.filterSeries = [\n new _cuckoo_filter_js__WEBPACK_IMPORTED_MODULE_3__.CuckooFilter({\n filterSize: this.filterSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n })\n ];\n }\n add(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n if (this.has(item)) {\n return true;\n }\n let current = this.filterSeries.find((cuckoo) => {\n return cuckoo.reliable;\n });\n if (current == null) {\n const curSize = this.filterSize * Math.pow(this.scale, this.filterSeries.length);\n current = new _cuckoo_filter_js__WEBPACK_IMPORTED_MODULE_3__.CuckooFilter({\n filterSize: curSize,\n bucketSize: this.bucketSize,\n fingerprintSize: this.fingerprintSize,\n hash: this.hash,\n seed: this.seed\n });\n this.filterSeries.push(current);\n }\n return current.add(item);\n }\n has(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].has(item)) {\n return true;\n }\n }\n return false;\n }\n remove(item) {\n if (typeof item === 'string') {\n item = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(item);\n }\n for (let i = 0; i < this.filterSeries.length; i++) {\n if (this.filterSeries[i].remove(item)) {\n return true;\n }\n }\n return false;\n }\n get count() {\n return this.filterSeries.reduce((acc, curr) => {\n return acc + curr.count;\n }, 0);\n }\n}\nfunction createScalableCuckooFilter(maxItems, errorRate = 0.001, options) {\n return new ScalableCuckooFilter({\n ...(0,_cuckoo_filter_js__WEBPACK_IMPORTED_MODULE_3__.optimize)(maxItems, errorRate),\n ...(options ?? {})\n });\n}\n//# sourceMappingURL=scalable-cuckoo-filter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/scalable-cuckoo-filter.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/filters/utils.js": +/*!**************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/filters/utils.js ***! + \**************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getRandomInt: () => (/* binding */ getRandomInt)\n/* harmony export */ });\nfunction getRandomInt(min, max) {\n return Math.floor(Math.random() * (max - min)) + min;\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/filters/utils.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/is-promise.js": +/*!***********************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/is-promise.js ***! + \***********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPromise: () => (/* binding */ isPromise)\n/* harmony export */ });\nfunction isPromise(thing) {\n if (thing == null) {\n return false;\n }\n return typeof thing.then === 'function' &&\n typeof thing.catch === 'function' &&\n typeof thing.finally === 'function';\n}\n//# sourceMappingURL=is-promise.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/is-promise.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/moving-average.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/moving-average.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MovingAverage: () => (/* binding */ MovingAverage)\n/* harmony export */ });\n/**\n * Implements exponential moving average. Ported from `moving-average`.\n *\n * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * @see https://www.npmjs.com/package/moving-average\n */\nclass MovingAverage {\n movingAverage;\n variance;\n deviation;\n forecast;\n timespan;\n previousTime;\n constructor(timespan) {\n this.timespan = timespan;\n this.movingAverage = 0;\n this.variance = 0;\n this.deviation = 0;\n this.forecast = 0;\n }\n alpha(t, pt) {\n return 1 - (Math.exp(-(t - pt) / this.timespan));\n }\n push(value, time = Date.now()) {\n if (this.previousTime != null) {\n // calculate moving average\n const a = this.alpha(time, this.previousTime);\n const diff = value - this.movingAverage;\n const incr = a * diff;\n this.movingAverage = a * value + (1 - a) * this.movingAverage;\n // calculate variance & deviation\n this.variance = (1 - a) * (this.variance + diff * incr);\n this.deviation = Math.sqrt(this.variance);\n // calculate forecast\n this.forecast = this.movingAverage + a * diff;\n }\n else {\n this.movingAverage = value;\n }\n this.previousTime = time;\n }\n}\n//# sourceMappingURL=moving-average.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/moving-average.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js ***! + \*********************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPrivate: () => (/* binding */ isPrivate)\n/* harmony export */ });\n/* harmony import */ var _private_ip_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../private-ip.js */ \"./node_modules/@libp2p/utils/dist/src/private-ip.js\");\n\n/**\n * Check if a given multiaddr has a private address.\n */\nfunction isPrivate(ma) {\n try {\n const { address } = ma.nodeAddress();\n return Boolean((0,_private_ip_js__WEBPACK_IMPORTED_MODULE_0__.isPrivateIp)(address));\n }\n catch {\n return true;\n }\n}\n//# sourceMappingURL=is-private.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/peer-queue.js": +/*!***********************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/peer-queue.js ***! + \***********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerQueue: () => (/* binding */ PeerQueue)\n/* harmony export */ });\n/* harmony import */ var _queue_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./queue/index.js */ \"./node_modules/@libp2p/utils/dist/src/queue/index.js\");\n\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nclass PeerQueue extends _queue_index_js__WEBPACK_IMPORTED_MODULE_0__.Queue {\n has(peerId) {\n return this.find(peerId) != null;\n }\n find(peerId) {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId);\n });\n }\n}\n//# sourceMappingURL=peer-queue.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/peer-queue.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/priority-queue.js": +/*!***************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/priority-queue.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PriorityQueue: () => (/* binding */ PriorityQueue)\n/* harmony export */ });\n/* harmony import */ var _queue_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./queue/index.js */ \"./node_modules/@libp2p/utils/dist/src/queue/index.js\");\n\nclass PriorityQueue extends _queue_index_js__WEBPACK_IMPORTED_MODULE_0__.Queue {\n constructor(init = {}) {\n super({\n ...init,\n sort: (a, b) => {\n if (a.options.priority > b.options.priority) {\n return -1;\n }\n if (a.options.priority < b.options.priority) {\n return 1;\n }\n return 0;\n }\n });\n }\n}\n//# sourceMappingURL=priority-queue.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/priority-queue.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/private-ip.js": +/*!***********************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/private-ip.js ***! + \***********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPrivateIp: () => (/* binding */ isPrivateIp)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/is-ip */ \"./node_modules/@chainsafe/is-ip/lib/is-ip.js\");\n/* harmony import */ var netmask__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! netmask */ \"./node_modules/netmask/lib/netmask.js\");\n\n\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n];\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new netmask__WEBPACK_IMPORTED_MODULE_1__.Netmask(ipRange));\nfunction ipv4Check(ipAddr) {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr))\n return true;\n }\n return false;\n}\nfunction isIpv4MappedIpv6(ipAddr) {\n return /^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(ipAddr);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.5.5.2\n */\nfunction ipv4MappedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n if (parts.length < 2) {\n return false;\n }\n const octet34 = parts[parts.length - 1].padStart(4, '0');\n const octet12 = parts[parts.length - 2].padStart(4, '0');\n const ip4 = `${parseInt(octet12.substring(0, 2), 16)}.${parseInt(octet12.substring(2), 16)}.${parseInt(octet34.substring(0, 2), 16)}.${parseInt(octet34.substring(2), 16)}`;\n return ipv4Check(ip4);\n}\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc4291#section-2.2 example 3\n */\nfunction isIpv4EmbeddedIpv6(ipAddr) {\n return /^::ffff:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr);\n}\nfunction ipv4EmbeddedIpv6Check(ipAddr) {\n const parts = ipAddr.split(':');\n const ip4 = parts[parts.length - 1];\n return ipv4Check(ip4);\n}\nfunction ipv6Check(ipAddr) {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr);\n}\nfunction isPrivateIp(ip) {\n if ((0,_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv4)(ip))\n return ipv4Check(ip);\n else if (isIpv4MappedIpv6(ip))\n return ipv4MappedIpv6Check(ip);\n else if (isIpv4EmbeddedIpv6(ip))\n return ipv4EmbeddedIpv6Check(ip);\n else if ((0,_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv6)(ip))\n return ipv6Check(ip);\n else\n return undefined;\n}\n//# sourceMappingURL=private-ip.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/private-ip.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/queue/index.js": +/*!************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/queue/index.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Queue: () => (/* binding */ Queue)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var race_event__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! race-event */ \"./node_modules/race-event/dist/src/index.js\");\n/* harmony import */ var _job_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./job.js */ \"./node_modules/@libp2p/utils/dist/src/queue/job.js\");\n\n\n\n\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nclass Queue extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.TypedEventEmitter {\n concurrency;\n queue;\n pending;\n sort;\n constructor(init = {}) {\n super();\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY;\n this.pending = 0;\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n };\n }\n });\n }\n this.sort = init.sort;\n this.queue = [];\n }\n tryToStartAnother() {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty');\n });\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle');\n });\n }\n return false;\n }\n if (this.pending < this.concurrency) {\n let job;\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j;\n break;\n }\n }\n if (job == null) {\n return false;\n }\n this.safeDispatchEvent('active');\n this.pending++;\n void job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n this.pending--;\n this.tryToStartAnother();\n this.safeDispatchEvent('next');\n });\n return true;\n }\n return false;\n }\n enqueue(job) {\n this.queue.push(job);\n if (this.sort != null) {\n this.queue.sort(this.sort);\n }\n }\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options) {\n options?.signal?.throwIfAborted();\n const job = new _job_js__WEBPACK_IMPORTED_MODULE_3__.Job(fn, options);\n this.enqueue(job);\n this.safeDispatchEvent('add');\n this.tryToStartAnother();\n return job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result });\n this.safeDispatchEvent('success', { detail: { job, result } });\n return result;\n })\n .catch(err => {\n if (job.status === 'queued') {\n // job was aborted before it started - remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n }\n this.safeDispatchEvent('error', { detail: err });\n this.safeDispatchEvent('failure', { detail: { job, error: err } });\n throw err;\n });\n }\n /**\n * Clear the queue\n */\n clear() {\n this.queue.splice(0, this.queue.length);\n }\n /**\n * Abort all jobs in the queue and clear it\n */\n abort() {\n this.queue.forEach(job => {\n job.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.AbortError());\n });\n this.clear();\n }\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty(options) {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'empty', options?.signal);\n }\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan(limit, options) {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'next', options?.signal, {\n filter: () => this.size < limit\n });\n }\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle(options) {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'idle', options?.signal);\n }\n /**\n * Size of the queue including running items\n */\n get size() {\n return this.queue.length;\n }\n /**\n * The number of queued items waiting to run.\n */\n get queued() {\n return this.queue.length - this.pending;\n }\n /**\n * The number of items currently running.\n */\n get running() {\n return this.pending;\n }\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async *toGenerator(options) {\n options?.signal?.throwIfAborted();\n const stream = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({\n objectMode: true\n });\n const cleanup = (err) => {\n if (err != null) {\n this.abort();\n }\n else {\n this.clear();\n }\n stream.end(err);\n };\n const onQueueJobComplete = (evt) => {\n if (evt.detail != null) {\n stream.push(evt.detail);\n }\n };\n const onQueueError = (evt) => {\n cleanup(evt.detail);\n };\n const onQueueIdle = () => {\n cleanup();\n };\n // clear the queue and throw if the query is aborted\n const onSignalAbort = () => {\n cleanup(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Queue aborted', 'ERR_QUEUE_ABORTED'));\n };\n // add listeners\n this.addEventListener('completed', onQueueJobComplete);\n this.addEventListener('error', onQueueError);\n this.addEventListener('idle', onQueueIdle);\n options?.signal?.addEventListener('abort', onSignalAbort);\n try {\n yield* stream;\n }\n finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete);\n this.removeEventListener('error', onQueueError);\n this.removeEventListener('idle', onQueueIdle);\n options?.signal?.removeEventListener('abort', onSignalAbort);\n // empty the queue for when the user has broken out of a loop early\n cleanup();\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/queue/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/queue/job.js": +/*!**********************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/queue/job.js ***! + \**********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Job: () => (/* binding */ Job)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var _recipient_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./recipient.js */ \"./node_modules/@libp2p/utils/dist/src/queue/recipient.js\");\n\n\n\n/**\n * Returns a random string\n */\nfunction randomId() {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`;\n}\nclass Job {\n id;\n fn;\n options;\n recipients;\n status;\n timeline;\n controller;\n constructor(fn, options) {\n this.id = randomId();\n this.status = 'queued';\n this.fn = fn;\n this.options = options;\n this.recipients = [];\n this.timeline = {\n created: Date.now()\n };\n this.controller = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.setMaxListeners)(Infinity, this.controller.signal);\n this.onAbort = this.onAbort.bind(this);\n }\n abort(err) {\n this.controller.abort(err);\n }\n onAbort() {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true);\n }, true);\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.AbortError());\n this.cleanup();\n }\n }\n async join(options = {}) {\n const recipient = new _recipient_js__WEBPACK_IMPORTED_MODULE_3__.JobRecipient(options.signal);\n this.recipients.push(recipient);\n options.signal?.addEventListener('abort', this.onAbort);\n return recipient.deferred.promise;\n }\n async run() {\n this.status = 'running';\n this.timeline.started = Date.now();\n try {\n this.controller.signal.throwIfAborted();\n const result = await (0,race_signal__WEBPACK_IMPORTED_MODULE_0__.raceSignal)(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal);\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result);\n });\n this.status = 'complete';\n }\n catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err);\n });\n this.status = 'errored';\n }\n finally {\n this.timeline.finished = Date.now();\n this.cleanup();\n }\n }\n cleanup() {\n this.recipients.forEach(recipient => {\n recipient.cleanup();\n recipient.signal?.removeEventListener('abort', this.onAbort);\n });\n }\n}\n//# sourceMappingURL=job.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/queue/job.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/queue/recipient.js": +/*!****************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/queue/recipient.js ***! + \****************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ JobRecipient: () => (/* binding */ JobRecipient)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n\n\nclass JobRecipient {\n deferred;\n signal;\n constructor(signal) {\n this.signal = signal;\n this.deferred = (0,p_defer__WEBPACK_IMPORTED_MODULE_0__[\"default\"])();\n this.onAbort = this.onAbort.bind(this);\n this.signal?.addEventListener('abort', this.onAbort);\n }\n onAbort() {\n this.deferred.reject(this.signal?.reason ?? new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.AbortError());\n }\n cleanup() {\n this.signal?.removeEventListener('abort', this.onAbort);\n }\n}\n//# sourceMappingURL=recipient.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/queue/recipient.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/rate-limiter.js": +/*!*************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/rate-limiter.js ***! + \*************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RateLimiter: () => (/* binding */ RateLimiter)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var delay__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! delay */ \"./node_modules/delay/index.js\");\n\n\nclass RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await (0,delay__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nclass MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/rate-limiter.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/dist/src/tracked-map.js": +/*!************************************************************!*\ + !*** ./node_modules/@libp2p/utils/dist/src/tracked-map.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ trackedMap: () => (/* binding */ trackedMap)\n/* harmony export */ });\nclass TrackedMap extends Map {\n metric;\n constructor(init) {\n super();\n const { name, metrics } = init;\n this.metric = metrics.registerMetric(name);\n this.updateComponentMetric();\n }\n set(key, value) {\n super.set(key, value);\n this.updateComponentMetric();\n return this;\n }\n delete(key) {\n const deleted = super.delete(key);\n this.updateComponentMetric();\n return deleted;\n }\n clear() {\n super.clear();\n this.updateComponentMetric();\n }\n updateComponentMetric() {\n this.metric.update(this.size);\n }\n}\nfunction trackedMap(config) {\n const { name, metrics } = config;\n let map;\n if (metrics != null) {\n map = new TrackedMap({ name, metrics });\n }\n else {\n map = new Map();\n }\n return map;\n}\n//# sourceMappingURL=tracked-map.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/dist/src/tracked-map.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ AggregateCodeError: () => (/* binding */ AggregateCodeError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* binding */ ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* binding */ ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* binding */ ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* binding */ ERR_TIMEOUT),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* binding */ InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* binding */ InvalidCryptoTransmissionError),\n/* harmony export */ UnexpectedPeerError: () => (/* binding */ UnexpectedPeerError)\n/* harmony export */ });\n/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nclass AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nclass CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nclass InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nclass InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nconst ERR_TIMEOUT = 'ERR_TIMEOUT';\nconst ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nconst ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nconst ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/errors.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/event-target.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/event-target.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/event-target.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.browser.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.browser.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/** Noop for browser compatibility */\nfunction setMaxListeners() { }\n//# sourceMappingURL=events.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ \"./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.browser.js\");\n\n// create a setMaxListeners that doesn't break browser usage\nconst setMaxListeners = (n, ...eventTargets) => {\n try {\n (0,events__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(n, ...eventTargets);\n }\n catch {\n // swallow error, gulp\n }\n};\n//# sourceMappingURL=events.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/@libp2p/interface/dist/src/events.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base10.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base10.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base10: () => (/* binding */ base10)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base10 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base10.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base16.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base16.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base16: () => (/* binding */ base16),\n/* harmony export */ base16upper: () => (/* binding */ base16upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base16 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nconst base16upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base16.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base2.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base2.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base2: () => (/* binding */ base2)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base2 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base2.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base256emoji.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base256emoji.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base256emoji.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base32.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base32.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base32: () => (/* binding */ base32),\n/* harmony export */ base32hex: () => (/* binding */ base32hex),\n/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),\n/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),\n/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),\n/* harmony export */ base32pad: () => (/* binding */ base32pad),\n/* harmony export */ base32padupper: () => (/* binding */ base32padupper),\n/* harmony export */ base32upper: () => (/* binding */ base32upper),\n/* harmony export */ base32z: () => (/* binding */ base32z)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nconst base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nconst base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nconst base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nconst base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nconst base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nconst base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nconst base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nconst base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base32.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base36.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base36.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base36: () => (/* binding */ base36),\n/* harmony export */ base36upper: () => (/* binding */ base36upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nconst base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base36.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base58.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base58.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base58btc: () => (/* binding */ base58btc),\n/* harmony export */ base58flickr: () => (/* binding */ base58flickr)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nconst base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base58.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base64.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base64.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64pad: () => (/* binding */ base64pad),\n/* harmony export */ base64url: () => (/* binding */ base64url),\n/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nconst base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nconst base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nconst base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base64.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base8.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base8.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base8: () => (/* binding */ base8)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base8 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base8.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/identity.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/identity.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\n\nconst identity = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.from)({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.toString)(buf),\n decode: (str) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.fromString)(str)\n});\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/interface.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/interface.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// Base encoders / decoders just base encode / decode between binary and\n// textual representation. They are unaware of multibase.\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/basics.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/basics.js ***! + \*********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.CID),\n/* harmony export */ bases: () => (/* binding */ bases),\n/* harmony export */ bytes: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.bytes),\n/* harmony export */ codecs: () => (/* binding */ codecs),\n/* harmony export */ digest: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.digest),\n/* harmony export */ hasher: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.hasher),\n/* harmony export */ hashes: () => (/* binding */ hashes),\n/* harmony export */ varint: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.varint)\n/* harmony export */ });\n/* harmony import */ var _bases_base10_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base10.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base10.js\");\n/* harmony import */ var _bases_base16_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base16.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base16.js\");\n/* harmony import */ var _bases_base2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base2.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base2.js\");\n/* harmony import */ var _bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bases/base256emoji.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base256emoji.js\");\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bases_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./bases/base64.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _bases_base8_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bases/base8.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base8.js\");\n/* harmony import */ var _bases_identity_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bases/identity.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/identity.js\");\n/* harmony import */ var _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./codecs/json.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/json.js\");\n/* harmony import */ var _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./codecs/raw.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/raw.js\");\n/* harmony import */ var _hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./hashes/identity.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var _hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./hashes/sha2.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/index.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst bases = { ..._bases_identity_js__WEBPACK_IMPORTED_MODULE_9__, ..._bases_base2_js__WEBPACK_IMPORTED_MODULE_2__, ..._bases_base8_js__WEBPACK_IMPORTED_MODULE_8__, ..._bases_base10_js__WEBPACK_IMPORTED_MODULE_0__, ..._bases_base16_js__WEBPACK_IMPORTED_MODULE_1__, ..._bases_base32_js__WEBPACK_IMPORTED_MODULE_4__, ..._bases_base36_js__WEBPACK_IMPORTED_MODULE_5__, ..._bases_base58_js__WEBPACK_IMPORTED_MODULE_6__, ..._bases_base64_js__WEBPACK_IMPORTED_MODULE_7__, ..._bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ };\nconst hashes = { ..._hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__, ..._hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ };\nconst codecs = { raw: _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__, json: _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ };\n\n//# sourceMappingURL=basics.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/basics.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/block/interface.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/block/interface.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/block/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js ***! + \********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ empty: () => (/* binding */ empty),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ fromHex: () => (/* binding */ fromHex),\n/* harmony export */ fromString: () => (/* binding */ fromString),\n/* harmony export */ isBinary: () => (/* binding */ isBinary),\n/* harmony export */ toHex: () => (/* binding */ toHex),\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\nconst empty = new Uint8Array(0);\nfunction toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nfunction fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nfunction equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nfunction coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nfunction isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nfunction fromString(str) {\n return new TextEncoder().encode(str);\n}\nfunction toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/cid.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/cid.js ***! + \******************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/cid.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/interface.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/interface.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/json.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/json.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nconst name = 'json';\nconst code = 0x0200;\nfunction encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nfunction decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/json.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/raw.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/raw.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n\nconst name = 'raw';\nconst code = 0x55;\nfunction encode(node) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(node);\n}\nfunction decode(data) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(data);\n}\n//# sourceMappingURL=raw.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/raw.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/hasher.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/hasher.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hasher: () => (/* binding */ Hasher),\n/* harmony export */ from: () => (/* binding */ from)\n/* harmony export */ });\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n\nfunction from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nclass Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/hasher.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/identity.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/identity.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n\n\nconst code = 0x0;\nconst name = 'identity';\nconst encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;\nfunction digest(input) {\n return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));\n}\nconst identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/interface.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/interface.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// # Multihash\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/sha2-browser.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha256: () => (/* binding */ sha256),\n/* harmony export */ sha512: () => (/* binding */ sha512)\n/* harmony export */ });\n/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* global crypto */\n\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nconst sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nconst sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/sha2-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/index.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/index.js ***! + \********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),\n/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),\n/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),\n/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/interface.js\");\n/**\n * @packageDocumentation\n *\n * This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.\n *\n * This library provides implementations for most basics and many others can be found in linked repositories.\n *\n * ```TypeScript\n * import { CID } from 'multiformats/cid'\n * import * as json from 'multiformats/codecs/json'\n * import { sha256 } from 'multiformats/hashes/sha2'\n *\n * const bytes = json.encode({ hello: 'world' })\n *\n * const hash = await sha256.digest(bytes)\n * const cid = CID.create(1, json.code, hash)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Creating Blocks\n *\n * ```TypeScript\n * import * as Block from 'multiformats/block'\n * import * as codec from '@ipld/dag-cbor'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * const value = { hello: 'world' }\n *\n * // encode a block\n * let block = await Block.encode({ value, codec, hasher })\n *\n * block.value // { hello: 'world' }\n * block.bytes // Uint8Array\n * block.cid // CID() w/ sha2-256 hash address and dag-cbor codec\n *\n * // you can also decode blocks from their binary state\n * block = await Block.decode({ bytes: block.bytes, codec, hasher })\n *\n * // if you have the cid you can also verify the hash on decode\n * block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })\n * ```\n *\n * ## Multibase Encoders / Decoders / Codecs\n *\n * CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:\n *\n * ```TypeScript\n * import { base64 } from \"multiformats/bases/base64\"\n * cid.toString(base64.encoder)\n * //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'\n * ```\n *\n * Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:\n *\n * ```TypeScript\n * CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * Dual of multibase encoder & decoder is defined as multibase codec and it exposes\n * them as `encoder` and `decoder` properties. For added convenience codecs also\n * implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be\n * used as either or both:\n *\n * ```TypeScript\n * cid.toString(base64)\n * CID.parse(cid.toString(base64), base64)\n * ```\n *\n * **Note:** CID implementation comes bundled with `base32` and `base58btc`\n * multibase codecs so that CIDs can be base serialized to (version specific)\n * default base encoding and parsed without having to supply base encoders/decoders:\n *\n * ```TypeScript\n * const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')\n * v1.toString()\n * //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'\n *\n * const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n * v0.toString()\n * //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'\n * v0.toV1().toString()\n * //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'\n * ```\n *\n * ## Multicodec Encoders / Decoders / Codecs\n *\n * This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).\n * Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.\n * Here is an example implementation of JSON `BlockCodec`.\n *\n * ```TypeScript\n * export const { name, code, encode, decode } = {\n * name: 'json',\n * code: 0x0200,\n * encode: json => new TextEncoder().encode(JSON.stringify(json)),\n * decode: bytes => JSON.parse(new TextDecoder().decode(bytes))\n * }\n * ```\n *\n * ## Multihash Hashers\n *\n * This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:\n *\n * ```TypeScript\n * import * as hasher from 'multiformats/hashes/hasher'\n *\n * const sha256 = hasher.from({\n * // As per multiformats table\n * // https://github.com/multiformats/multicodec/blob/master/table.csv#L9\n * name: 'sha2-256',\n * code: 0x12,\n *\n * encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())\n * })\n *\n * const hash = await sha256.digest(json.encode({ hello: 'world' }))\n * CID.create(1, json.code, hash)\n *\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Traversal\n *\n * This library contains higher-order functions for traversing graphs of data easily.\n *\n * `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.\n *\n * ```TypeScript\n * import { walk } from 'multiformats/traversal'\n * import * as Block from 'multiformats/block'\n * import * as codec from 'multiformats/codecs/json'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * // build a DAG (a single block for this simple example)\n * const value = { hello: 'world' }\n * const block = await Block.encode({ value, codec, hasher })\n * const { cid } = block\n * console.log(cid)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n *\n * // create a loader function that also collects CIDs of blocks in\n * // their traversal order\n * const load = (cid, blocks) => async (cid) => {\n * // fetch a block using its cid\n * // e.g.: const block = await fetchBlockByCID(cid)\n * blocks.push(cid)\n * return block\n * }\n *\n * // collect blocks in this DAG starting from the root `cid`\n * const blocks = []\n * await walk({ cid, load: load(cid, blocks) })\n *\n * console.log(blocks)\n * //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]\n * ```\n *\n * ## Legacy interface\n *\n * [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an\n * [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.\n *\n * ## Implementations\n *\n * By default, no base encodings (other than base32 & base58btc), hash functions,\n * or codec implementations are exposed by `multiformats`, you need to\n * import the ones you need yourself.\n *\n * ### Multibase codecs\n *\n * | bases | import | repo |\n * | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |\n * | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n *\n * Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.\n *\n * ### Multihash hashers\n *\n * | hashes | import | repo |\n * | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |\n * | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |\n * | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |\n * | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |\n * | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |\n * | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |\n *\n * ### IPLD codecs (multicodec)\n *\n * | codec | import | repo |\n * | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |\n * | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |\n * | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |\n * | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |\n * | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |\n */\n\n\n\n\n\n// This way TS will also expose all the types from module\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/interface.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/interface.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _bases_interface_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/bases/interface.js\");\n/* harmony import */ var _hashes_interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/hashes/interface.js\");\n/* harmony import */ var _codecs_interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/codecs/interface.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/link/interface.js\");\n/* harmony import */ var _block_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./block/interface.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/block/interface.js\");\n\n\n\n\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/link/interface.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/link/interface.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */\n/* eslint-disable no-use-before-define */\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/link/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js ***! + \*********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encodeTo: () => (/* binding */ encodeTo),\n/* harmony export */ encodingLength: () => (/* binding */ encodingLength)\n/* harmony export */ });\n/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/varint.js\");\n\nfunction decode(data, offset = 0) {\n const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode(data, offset);\n return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode.bytes];\n}\nfunction encodeTo(int, target, offset = 0) {\n _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encode(int, target, offset);\n return target;\n}\nfunction encodingLength(int) {\n return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/base-x.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/base-x.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);\n//# sourceMappingURL=base-x.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/base-x.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/varint.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/varint.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/vendor/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/alloc.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/alloc.js ***! + \*******************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ alloc: () => (/* binding */ alloc),\n/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)\n/* harmony export */ });\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nfunction alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nfunction allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/alloc.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/equals.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/equals.js ***! + \********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/**\n * Returns true if the two passed Uint8Arrays have the same content\n */\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n//# sourceMappingURL=equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/equals.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fromString: () => (/* binding */ fromString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction fromString(string, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/from-string.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/util/bases.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/util/bases.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@libp2p/utils/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ \"./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/alloc.js\");\n\n\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);\n//# sourceMappingURL=bases.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/utils/node_modules/uint8arrays/dist/src/util/bases.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/websockets/dist/src/constants.js": /*!***************************************************************!*\ !*** ./node_modules/@libp2p/websockets/dist/src/constants.js ***! @@ -7476,7 +11413,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ webSockets: () => (/* binding */ webSockets)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _multiformats_multiaddr_to_uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr-to-uri */ \"./node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js\");\n/* harmony import */ var it_ws_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-ws/client */ \"./node_modules/it-ws/dist/src/client.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var wherearewe__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! wherearewe */ \"./node_modules/wherearewe/src/index.js\");\n/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./filters.js */ \"./node_modules/@libp2p/websockets/dist/src/filters.js\");\n/* harmony import */ var _listener_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./listener.js */ \"./node_modules/@libp2p/websockets/dist/src/listener.browser.js\");\n/* harmony import */ var _socket_to_conn_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./socket-to-conn.js */ \"./node_modules/@libp2p/websockets/dist/src/socket-to-conn.js\");\n/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/9090/ws')\n * await node.dial(ma)\n * ```\n *\n * ## Filters\n *\n * When run in a browser by default this module will only connect to secure web socket addresses.\n *\n * To change this you should pass a filter to the factory function.\n *\n * You can create your own address filters for this transports, or rely in the filters [provided](./src/filters.js).\n *\n * The available filters are:\n *\n * - `filters.all`\n * - Returns all TCP and DNS based addresses, both with `ws` or `wss`.\n * - `filters.dnsWss`\n * - Returns all DNS based addresses with `wss`.\n * - `filters.dnsWsOrWss`\n * - Returns all DNS based addresses, both with `ws` or `wss`.\n *\n * @example Allow dialing insecure WebSockets\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import filters from '@libp2p/websockets/filters'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets({\n * // connect to all sockets, even insecure ones\n * filter: filters.all\n * })\n * ]\n * })\n * ```\n */\n\n\n\n\n\n\n\n\n\nclass WebSockets {\n log;\n init;\n logger;\n constructor(components, init) {\n this.log = components.logger.forComponent('libp2p:websockets');\n this.logger = components.logger;\n this.init = init;\n }\n [Symbol.toStringTag] = '@libp2p/websockets';\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.transportSymbol] = true;\n async dial(ma, options) {\n this.log('dialing %s', ma);\n options = options ?? {};\n const socket = await this._connect(ma, options);\n const maConn = (0,_socket_to_conn_js__WEBPACK_IMPORTED_MODULE_4__.socketToMaConn)(socket, ma, {\n logger: this.logger\n });\n this.log('new outbound connection %s', maConn.remoteAddr);\n const conn = await options.upgrader.upgradeOutbound(maConn);\n this.log('outbound connection %s upgraded', maConn.remoteAddr);\n return conn;\n }\n async _connect(ma, options) {\n if (options?.signal?.aborted === true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.AbortError();\n }\n const cOpts = ma.toOptions();\n this.log('dialing %s:%s', cOpts.host, cOpts.port);\n const errorPromise = (0,p_defer__WEBPACK_IMPORTED_MODULE_6__[\"default\"])();\n const rawSocket = (0,it_ws_client__WEBPACK_IMPORTED_MODULE_1__.connect)((0,_multiformats_multiaddr_to_uri__WEBPACK_IMPORTED_MODULE_0__.multiaddrToUri)(ma), this.init);\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError(`Could not connect to ${ma.toString()}`, 'ERR_CONNECTION_FAILED');\n this.log.error('connection error:', err);\n errorPromise.reject(err);\n });\n if (options.signal == null) {\n await Promise.race([rawSocket.connected(), errorPromise.promise]);\n this.log('connected %s', ma);\n return rawSocket;\n }\n // Allow abort via signal during connect\n let onAbort;\n const abort = new Promise((resolve, reject) => {\n onAbort = () => {\n reject(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.AbortError());\n rawSocket.close().catch(err => {\n this.log.error('error closing raw socket', err);\n });\n };\n // Already aborted?\n if (options?.signal?.aborted === true) {\n onAbort();\n return;\n }\n options?.signal?.addEventListener('abort', onAbort);\n });\n try {\n await Promise.race([abort, errorPromise.promise, rawSocket.connected()]);\n }\n finally {\n if (onAbort != null) {\n options?.signal?.removeEventListener('abort', onAbort);\n }\n }\n this.log('connected %s', ma);\n return rawSocket;\n }\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener(options) {\n return (0,_listener_js__WEBPACK_IMPORTED_MODULE_7__.createListener)({\n logger: this.logger\n }, {\n ...this.init,\n ...options\n });\n }\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n filter(multiaddrs) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs];\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs);\n }\n // Browser\n if (wherearewe__WEBPACK_IMPORTED_MODULE_2__.isBrowser || wherearewe__WEBPACK_IMPORTED_MODULE_2__.isWebWorker) {\n return _filters_js__WEBPACK_IMPORTED_MODULE_8__.wss(multiaddrs);\n }\n return _filters_js__WEBPACK_IMPORTED_MODULE_8__.all(multiaddrs);\n }\n}\nfunction webSockets(init = {}) {\n return (components) => {\n return new WebSockets(components, init);\n };\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ webSockets: () => (/* binding */ webSockets)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _multiformats_multiaddr_to_uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr-to-uri */ \"./node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js\");\n/* harmony import */ var it_ws_client__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-ws/client */ \"./node_modules/it-ws/dist/src/client.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var wherearewe__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! wherearewe */ \"./node_modules/wherearewe/src/index.js\");\n/* harmony import */ var _filters_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./filters.js */ \"./node_modules/@libp2p/websockets/dist/src/filters.js\");\n/* harmony import */ var _listener_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./listener.js */ \"./node_modules/@libp2p/websockets/dist/src/listener.browser.js\");\n/* harmony import */ var _socket_to_conn_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./socket-to-conn.js */ \"./node_modules/@libp2p/websockets/dist/src/socket-to-conn.js\");\n/**\n * @packageDocumentation\n *\n * A [libp2p transport](https://docs.libp2p.io/concepts/transports/overview/) based on [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API).\n *\n * @example\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets()\n * ]\n * //... other config\n * })\n * await node.start()\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/9090/ws')\n * await node.dial(ma)\n * ```\n *\n * ## Filters\n *\n * When run in a browser by default this module will only connect to secure web socket addresses.\n *\n * To change this you should pass a filter to the factory function.\n *\n * You can create your own address filters for this transports, or rely in the filters [provided](./src/filters.js).\n *\n * The available filters are:\n *\n * - `filters.all`\n * - Returns all TCP and DNS based addresses, both with `ws` or `wss`.\n * - `filters.dnsWss`\n * - Returns all DNS based addresses with `wss`.\n * - `filters.dnsWsOrWss`\n * - Returns all DNS based addresses, both with `ws` or `wss`.\n *\n * @example Allow dialing insecure WebSockets\n *\n * ```TypeScript\n * import { createLibp2p } from 'libp2p'\n * import { webSockets } from '@libp2p/websockets'\n * import * as filters from '@libp2p/websockets/filters'\n *\n * const node = await createLibp2p({\n * transports: [\n * webSockets({\n * // connect to all sockets, even insecure ones\n * filter: filters.all\n * })\n * ]\n * })\n * ```\n */\n\n\n\n\n\n\n\n\n\n\nclass WebSockets {\n log;\n init;\n logger;\n metrics;\n components;\n constructor(components, init) {\n this.log = components.logger.forComponent('libp2p:websockets');\n this.logger = components.logger;\n this.components = components;\n this.init = init;\n if (components.metrics != null) {\n this.metrics = {\n dialerEvents: components.metrics.registerCounterGroup('libp2p_websockets_dialer_events_total', {\n label: 'event',\n help: 'Total count of WebSockets dialer events by type'\n })\n };\n }\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.transportSymbol] = true;\n [Symbol.toStringTag] = '@libp2p/websockets';\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.serviceCapabilities] = [\n '@libp2p/transport'\n ];\n async dial(ma, options) {\n this.log('dialing %s', ma);\n options = options ?? {};\n const socket = await this._connect(ma, options);\n const maConn = (0,_socket_to_conn_js__WEBPACK_IMPORTED_MODULE_7__.socketToMaConn)(socket, ma, {\n logger: this.logger,\n metrics: this.metrics?.dialerEvents\n });\n this.log('new outbound connection %s', maConn.remoteAddr);\n const conn = await options.upgrader.upgradeOutbound(maConn, options);\n this.log('outbound connection %s upgraded', maConn.remoteAddr);\n return conn;\n }\n async _connect(ma, options) {\n options?.signal?.throwIfAborted();\n const cOpts = ma.toOptions();\n this.log('dialing %s:%s', cOpts.host, cOpts.port);\n const errorPromise = (0,p_defer__WEBPACK_IMPORTED_MODULE_8__[\"default\"])();\n const rawSocket = (0,it_ws_client__WEBPACK_IMPORTED_MODULE_1__.connect)((0,_multiformats_multiaddr_to_uri__WEBPACK_IMPORTED_MODULE_0__.multiaddrToUri)(ma), this.init);\n rawSocket.socket.addEventListener('error', () => {\n // the WebSocket.ErrorEvent type doesn't actually give us any useful\n // information about what happened\n // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.CodeError(`Could not connect to ${ma.toString()}`, 'ERR_CONNECTION_FAILED');\n this.log.error('connection error:', err);\n this.metrics?.dialerEvents.increment({ error: true });\n errorPromise.reject(err);\n });\n try {\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_2__.CustomProgressEvent('websockets:open-connection'));\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_3__.raceSignal)(Promise.race([rawSocket.connected(), errorPromise.promise]), options.signal);\n }\n catch (err) {\n if (options.signal?.aborted === true) {\n this.metrics?.dialerEvents.increment({ abort: true });\n }\n rawSocket.close()\n .catch(err => {\n this.log.error('error closing raw socket', err);\n });\n throw err;\n }\n this.log('connected %s', ma);\n this.metrics?.dialerEvents.increment({ connect: true });\n return rawSocket;\n }\n /**\n * Creates a Websockets listener. The provided `handler` function will be called\n * anytime a new incoming Connection has been successfully upgraded via\n * `upgrader.upgradeInbound`\n */\n createListener(options) {\n return (0,_listener_js__WEBPACK_IMPORTED_MODULE_10__.createListener)({\n logger: this.logger,\n metrics: this.components.metrics\n }, {\n ...this.init,\n ...options\n });\n }\n /**\n * Takes a list of `Multiaddr`s and returns only valid Websockets addresses.\n * By default, in a browser environment only DNS+WSS multiaddr is accepted,\n * while in a Node.js environment DNS+{WS, WSS} multiaddrs are accepted.\n */\n listenFilter(multiaddrs) {\n multiaddrs = Array.isArray(multiaddrs) ? multiaddrs : [multiaddrs];\n if (this.init?.filter != null) {\n return this.init?.filter(multiaddrs);\n }\n // Browser\n if (wherearewe__WEBPACK_IMPORTED_MODULE_4__.isBrowser || wherearewe__WEBPACK_IMPORTED_MODULE_4__.isWebWorker) {\n return _filters_js__WEBPACK_IMPORTED_MODULE_11__.wss(multiaddrs);\n }\n return _filters_js__WEBPACK_IMPORTED_MODULE_11__.all(multiaddrs);\n }\n /**\n * Filter check for all Multiaddrs that this transport can dial\n */\n dialFilter(multiaddrs) {\n return this.listenFilter(multiaddrs);\n }\n}\nfunction webSockets(init = {}) {\n return (components) => {\n return new WebSockets(components, init);\n };\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/dist/src/index.js?"); /***/ }), @@ -7498,7 +11435,29 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ socketToMaConn: () => (/* binding */ socketToMaConn)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@libp2p/websockets/dist/src/constants.js\");\n\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nfunction socketToMaConn(stream, remoteAddr, options) {\n const log = options.logger.forComponent('libp2p:websockets:maconn');\n const maConn = {\n log,\n async sink(source) {\n try {\n await stream.sink((async function* () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf;\n }\n else {\n yield buf.subarray();\n }\n }\n })());\n }\n catch (err) {\n if (err.type !== 'aborted') {\n log.error(err);\n }\n }\n },\n source: stream.source,\n remoteAddr,\n timeline: { open: Date.now() },\n async close(options = {}) {\n const start = Date.now();\n if (options.signal == null) {\n const signal = AbortSignal.timeout(_constants_js__WEBPACK_IMPORTED_MODULE_0__.CLOSE_TIMEOUT);\n options = {\n ...options,\n signal\n };\n }\n const listener = () => {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s after %dms, destroying it manually', host, port, Date.now() - start);\n this.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'));\n };\n options.signal?.addEventListener('abort', listener);\n try {\n await stream.close();\n }\n catch (err) {\n log.error('error closing WebSocket gracefully', err);\n this.abort(err);\n }\n finally {\n options.signal?.removeEventListener('abort', listener);\n maConn.timeline.close = Date.now();\n }\n },\n abort(err) {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s due to error', host, port, err);\n stream.destroy();\n maConn.timeline.close = Date.now();\n }\n };\n stream.socket.addEventListener('close', () => {\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now();\n }\n }, { once: true });\n return maConn;\n}\n//# sourceMappingURL=socket-to-conn.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/dist/src/socket-to-conn.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ socketToMaConn: () => (/* binding */ socketToMaConn)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@libp2p/websockets/dist/src/constants.js\");\n\n\n// Convert a stream into a MultiaddrConnection\n// https://github.com/libp2p/interface-transport#multiaddrconnection\nfunction socketToMaConn(stream, remoteAddr, options) {\n const log = options.logger.forComponent('libp2p:websockets:maconn');\n const metrics = options.metrics;\n const metricPrefix = options.metricPrefix ?? '';\n const maConn = {\n log,\n async sink(source) {\n try {\n await stream.sink((async function* () {\n for await (const buf of source) {\n if (buf instanceof Uint8Array) {\n yield buf;\n }\n else {\n yield buf.subarray();\n }\n }\n })());\n }\n catch (err) {\n if (err.type !== 'aborted') {\n log.error(err);\n }\n }\n },\n source: stream.source,\n remoteAddr,\n timeline: { open: Date.now() },\n async close(options = {}) {\n const start = Date.now();\n if (options.signal == null) {\n const signal = AbortSignal.timeout(_constants_js__WEBPACK_IMPORTED_MODULE_0__.CLOSE_TIMEOUT);\n options = {\n ...options,\n signal\n };\n }\n const listener = () => {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s after %dms, destroying it manually', host, port, Date.now() - start);\n this.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('Socket close timeout', 'ERR_SOCKET_CLOSE_TIMEOUT'));\n };\n options.signal?.addEventListener('abort', listener);\n try {\n await stream.close();\n }\n catch (err) {\n log.error('error closing WebSocket gracefully', err);\n this.abort(err);\n }\n finally {\n options.signal?.removeEventListener('abort', listener);\n maConn.timeline.close = Date.now();\n }\n },\n abort(err) {\n const { host, port } = maConn.remoteAddr.toOptions();\n log('timeout closing stream to %s:%s due to error', host, port, err);\n stream.destroy();\n maConn.timeline.close = Date.now();\n // ws WebSocket.terminate does not accept an Error arg to emit an 'error'\n // event on destroy like other node streams so we can't update a metric\n // with an event listener\n // https://github.com/websockets/ws/issues/1752#issuecomment-622380981\n metrics?.increment({ [`${metricPrefix}error`]: true });\n }\n };\n stream.socket.addEventListener('close', () => {\n metrics?.increment({ [`${metricPrefix}close`]: true });\n // In instances where `close` was not explicitly called,\n // such as an iterable stream ending, ensure we have set the close\n // timeline\n if (maConn.timeline.close == null) {\n maConn.timeline.close = Date.now();\n }\n }, { once: true });\n return maConn;\n}\n//# sourceMappingURL=socket-to-conn.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/dist/src/socket-to-conn.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/connection/index.js": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/connection/index.js ***! + \*****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ connectionSymbol: () => (/* binding */ connectionSymbol),\n/* harmony export */ isConnection: () => (/* binding */ isConnection)\n/* harmony export */ });\nconst connectionSymbol = Symbol.for('@libp2p/connection');\nfunction isConnection(other) {\n return other != null && Boolean(other[connectionSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/connection/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/content-routing/index.js": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/content-routing/index.js ***! + \**********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ contentRoutingSymbol: () => (/* binding */ contentRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * ContentRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { contentRoutingSymbol, ContentRouting } from '@libp2p/content-routing'\n *\n * class MyContentRouter implements ContentRouting {\n * get [contentRoutingSymbol] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst contentRoutingSymbol = Symbol.for('@libp2p/content-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/content-routing/index.js?"); /***/ }), @@ -7513,6 +11472,127 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/event-target.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/event-target.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/event-target.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.browser.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.browser.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/** Noop for browser compatibility */\nfunction setMaxListeners() { }\n//# sourceMappingURL=events.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.browser.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ setMaxListeners: () => (/* binding */ setMaxListeners)\n/* harmony export */ });\n/* harmony import */ var events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! events */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.browser.js\");\n\n// create a setMaxListeners that doesn't break browser usage\nconst setMaxListeners = (n, ...eventTargets) => {\n try {\n (0,events__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(n, ...eventTargets);\n }\n catch {\n // swallow error, gulp\n }\n};\n//# sourceMappingURL=events.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/index.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/index.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AbortError),\n/* harmony export */ AggregateCodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AggregateCodeError),\n/* harmony export */ CodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.CodeError),\n/* harmony export */ CustomEvent: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.CustomEvent),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_TIMEOUT),\n/* harmony export */ Ed25519: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.Ed25519),\n/* harmony export */ FaultTolerance: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.FaultTolerance),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoTransmissionError),\n/* harmony export */ KEEP_ALIVE: () => (/* reexport safe */ _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__.KEEP_ALIVE),\n/* harmony export */ RSA: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.RSA),\n/* harmony export */ StrictNoSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictNoSign),\n/* harmony export */ StrictSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.TopicValidatorResult),\n/* harmony export */ TypedEventEmitter: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.TypedEventEmitter),\n/* harmony export */ UnexpectedPeerError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.UnexpectedPeerError),\n/* harmony export */ connectionSymbol: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.connectionSymbol),\n/* harmony export */ contentRoutingSymbol: () => (/* reexport safe */ _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__.contentRoutingSymbol),\n/* harmony export */ isConnection: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.isConnection),\n/* harmony export */ isPeerId: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.isPeerId),\n/* harmony export */ isStartable: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.isStartable),\n/* harmony export */ isTransport: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.isTransport),\n/* harmony export */ peerDiscoverySymbol: () => (/* reexport safe */ _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__.peerDiscoverySymbol),\n/* harmony export */ peerIdSymbol: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.peerIdSymbol),\n/* harmony export */ peerRoutingSymbol: () => (/* reexport safe */ _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__.peerRoutingSymbol),\n/* harmony export */ secp256k1: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.secp256k1),\n/* harmony export */ serviceCapabilities: () => (/* binding */ serviceCapabilities),\n/* harmony export */ serviceDependencies: () => (/* binding */ serviceDependencies),\n/* harmony export */ setMaxListeners: () => (/* reexport safe */ _events_js__WEBPACK_IMPORTED_MODULE_11__.setMaxListeners),\n/* harmony export */ start: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.start),\n/* harmony export */ stop: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.stop),\n/* harmony export */ transportSymbol: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.transportSymbol)\n/* harmony export */ });\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/connection/index.js\");\n/* harmony import */ var _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./content-routing/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _keys_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/keys/index.js\");\n/* harmony import */ var _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peer-discovery/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./peer-id/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./peer-routing/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./peer-store/tags.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./pubsub/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/pubsub/index.js\");\n/* harmony import */ var _transport_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./transport/index.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _event_target_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./event-target.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _startable_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./startable.js */ \"./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/startable.js\");\n/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nconst serviceDependencies = Symbol.for('@libp2p/service-dependencies');\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/keys/index.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/keys/index.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519: () => (/* binding */ Ed25519),\n/* harmony export */ RSA: () => (/* binding */ RSA),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\nconst Ed25519 = 'Ed25519';\nconst RSA = 'RSA';\nconst secp256k1 = 'secp256k1';\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/keys/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js ***! + \*********************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ peerDiscoverySymbol: () => (/* binding */ peerDiscoverySymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerDiscovery instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerDiscovery, PeerDiscovery } from '@libp2p/peer-discovery'\n *\n * class MyPeerDiscoverer implements PeerDiscovery {\n * get [peerDiscovery] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst peerDiscoverySymbol = Symbol.for('@libp2p/peer-discovery');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-id/index.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-id/index.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPeerId: () => (/* binding */ isPeerId),\n/* harmony export */ peerIdSymbol: () => (/* binding */ peerIdSymbol)\n/* harmony export */ });\nconst peerIdSymbol = Symbol.for('@libp2p/peer-id');\nfunction isPeerId(other) {\n return other != null && Boolean(other[peerIdSymbol]);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-id/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-routing/index.js": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-routing/index.js ***! + \*******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ peerRoutingSymbol: () => (/* binding */ peerRoutingSymbol)\n/* harmony export */ });\n/**\n * Any object that implements this Symbol as a property should return a\n * PeerRouting instance as the property value, similar to how\n * `Symbol.Iterable` can be used to return an `Iterable` from an `Iterator`.\n *\n * @example\n *\n * ```TypeScript\n * import { peerRouting, PeerRouting } from '@libp2p/peer-routing'\n *\n * class MyPeerRouter implements PeerRouting {\n * get [peerRouting] () {\n * return this\n * }\n *\n * // ...other methods\n * }\n * ```\n */\nconst peerRoutingSymbol = Symbol.for('@libp2p/peer-routing');\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-routing/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-store/tags.js": +/*!****************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-store/tags.js ***! + \****************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ KEEP_ALIVE: () => (/* binding */ KEEP_ALIVE)\n/* harmony export */ });\nconst KEEP_ALIVE = 'keep-alive';\n//# sourceMappingURL=tags.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/peer-store/tags.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/pubsub/index.js": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/pubsub/index.js ***! + \*************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ StrictNoSign: () => (/* binding */ StrictNoSign),\n/* harmony export */ StrictSign: () => (/* binding */ StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* binding */ TopicValidatorResult)\n/* harmony export */ });\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nconst StrictSign = 'StrictSign';\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nconst StrictNoSign = 'StrictNoSign';\nvar TopicValidatorResult;\n(function (TopicValidatorResult) {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n TopicValidatorResult[\"Accept\"] = \"accept\";\n /**\n * The message is neither delivered nor forwarded to the network\n */\n TopicValidatorResult[\"Ignore\"] = \"ignore\";\n /**\n * The message is considered invalid, and it should be rejected\n */\n TopicValidatorResult[\"Reject\"] = \"reject\";\n})(TopicValidatorResult || (TopicValidatorResult = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/pubsub/index.js?"); + +/***/ }), + +/***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/startable.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/startable.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isStartable: () => (/* binding */ isStartable),\n/* harmony export */ start: () => (/* binding */ start),\n/* harmony export */ stop: () => (/* binding */ stop)\n/* harmony export */ });\nfunction isStartable(obj) {\n return obj != null && typeof obj.start === 'function' && typeof obj.stop === 'function';\n}\nasync function start(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStart != null) {\n await s.beforeStart();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.start();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStart != null) {\n await s.afterStart();\n }\n }));\n}\nasync function stop(...objs) {\n const startables = [];\n for (const obj of objs) {\n if (isStartable(obj)) {\n startables.push(obj);\n }\n }\n await Promise.all(startables.map(async (s) => {\n if (s.beforeStop != null) {\n await s.beforeStop();\n }\n }));\n await Promise.all(startables.map(async (s) => {\n await s.stop();\n }));\n await Promise.all(startables.map(async (s) => {\n if (s.afterStop != null) {\n await s.afterStop();\n }\n }));\n}\n//# sourceMappingURL=startable.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/startable.js?"); + +/***/ }), + /***/ "./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/transport/index.js": /*!****************************************************************************************************!*\ !*** ./node_modules/@libp2p/websockets/node_modules/@libp2p/interface/dist/src/transport/index.js ***! @@ -7564,7 +11644,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_QUERY_CONCURRENCY: () => (/* binding */ DEFAULT_QUERY_CONCURRENCY),\n/* harmony export */ dnsJsonOverHttps: () => (/* binding */ dnsJsonOverHttps)\n/* harmony export */ });\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! p-queue */ \"./node_modules/p-queue/dist/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var _utils_get_types_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/get-types.js */ \"./node_modules/@multiformats/dns/dist/src/utils/get-types.js\");\n/* harmony import */ var _utils_to_dns_response_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/to-dns-response.js */ \"./node_modules/@multiformats/dns/dist/src/utils/to-dns-response.js\");\n/* eslint-env browser */\n\n\n\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nconst DEFAULT_QUERY_CONCURRENCY = 4;\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nfunction dnsJsonOverHttps(url, init = {}) {\n const httpQueue = new p_queue__WEBPACK_IMPORTED_MODULE_3__[\"default\"]({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n });\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams();\n searchParams.set('name', fqdn);\n (0,_utils_get_types_js__WEBPACK_IMPORTED_MODULE_1__.getTypes)(options.types).forEach(type => {\n searchParams.append('type', type.toString());\n });\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('dns:query', { detail: fqdn }));\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`);\n }\n const response = (0,_utils_to_dns_response_js__WEBPACK_IMPORTED_MODULE_2__.toDNSResponse)(await res.json());\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('dns:response', { detail: response }));\n return response;\n }, {\n signal: options.signal\n });\n if (response == null) {\n throw new Error('No DNS response received');\n }\n return response;\n };\n}\n//# sourceMappingURL=dns-json-over-https.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/dist/src/resolvers/dns-json-over-https.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_QUERY_CONCURRENCY: () => (/* binding */ DEFAULT_QUERY_CONCURRENCY),\n/* harmony export */ dnsJsonOverHttps: () => (/* binding */ dnsJsonOverHttps)\n/* harmony export */ });\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! p-queue */ \"./node_modules/p-queue/dist/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index.js */ \"./node_modules/@multiformats/dns/dist/src/index.js\");\n/* harmony import */ var _utils_get_types_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/get-types.js */ \"./node_modules/@multiformats/dns/dist/src/utils/get-types.js\");\n/* harmony import */ var _utils_to_dns_response_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/to-dns-response.js */ \"./node_modules/@multiformats/dns/dist/src/utils/to-dns-response.js\");\n/* eslint-env browser */\n\n\n\n\n\n/**\n * Browsers limit concurrent connections per host (~6), we don't want to exhaust\n * the limit so this value controls how many DNS queries can be in flight at\n * once.\n */\nconst DEFAULT_QUERY_CONCURRENCY = 4;\n/**\n * Uses the RFC 8427 'application/dns-json' content-type to resolve DNS queries.\n *\n * Supports and server that uses the same schema as Google's DNS over HTTPS\n * resolver.\n *\n * This resolver needs fewer dependencies than the regular DNS-over-HTTPS\n * resolver so can result in a smaller bundle size and consequently is preferred\n * for browser use.\n *\n * @see https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/make-api-requests/dns-json/\n * @see https://github.com/curl/curl/wiki/DNS-over-HTTPS#publicly-available-servers\n * @see https://dnsprivacy.org/public_resolvers/\n * @see https://datatracker.ietf.org/doc/html/rfc8427\n */\nfunction dnsJsonOverHttps(url, init = {}) {\n const httpQueue = new p_queue__WEBPACK_IMPORTED_MODULE_4__[\"default\"]({\n concurrency: init.queryConcurrency ?? DEFAULT_QUERY_CONCURRENCY\n });\n return async (fqdn, options = {}) => {\n const searchParams = new URLSearchParams();\n searchParams.set('name', fqdn);\n (0,_utils_get_types_js__WEBPACK_IMPORTED_MODULE_2__.getTypes)(options.types).forEach(type => {\n // We pass record type as a string to the server because cloudflare DNS bug. see https://github.com/ipfs/helia/issues/474\n searchParams.append('type', _index_js__WEBPACK_IMPORTED_MODULE_1__.RecordType[type]);\n });\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('dns:query', { detail: fqdn }));\n // query DNS-JSON over HTTPS server\n const response = await httpQueue.add(async () => {\n const res = await fetch(`${url}?${searchParams}`, {\n headers: {\n accept: 'application/dns-json'\n },\n signal: options?.signal\n });\n if (res.status !== 200) {\n throw new Error(`Unexpected HTTP status: ${res.status} - ${res.statusText}`);\n }\n const response = (0,_utils_to_dns_response_js__WEBPACK_IMPORTED_MODULE_3__.toDNSResponse)(await res.json());\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('dns:response', { detail: response }));\n return response;\n }, {\n signal: options.signal\n });\n if (response == null) {\n throw new Error('No DNS response received');\n }\n return response;\n };\n}\n//# sourceMappingURL=dns-json-over-https.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/dist/src/resolvers/dns-json-over-https.js?"); /***/ }), @@ -7608,7 +11688,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -7652,7 +11732,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -7773,7 +11853,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -7817,7 +11897,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/dns/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -7982,7 +12062,18 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Circuit: () => (/* binding */ Circuit),\n/* harmony export */ DNS: () => (/* binding */ DNS),\n/* harmony export */ DNS4: () => (/* binding */ DNS4),\n/* harmony export */ DNS6: () => (/* binding */ DNS6),\n/* harmony export */ DNSADDR: () => (/* binding */ DNSADDR),\n/* harmony export */ HTTP: () => (/* binding */ HTTP),\n/* harmony export */ HTTPS: () => (/* binding */ HTTPS),\n/* harmony export */ IP: () => (/* binding */ IP),\n/* harmony export */ IP4: () => (/* binding */ IP4),\n/* harmony export */ IP6: () => (/* binding */ IP6),\n/* harmony export */ IP_OR_DOMAIN: () => (/* binding */ IP_OR_DOMAIN),\n/* harmony export */ P2P: () => (/* binding */ P2P),\n/* harmony export */ QUIC: () => (/* binding */ QUIC),\n/* harmony export */ QUICV1: () => (/* binding */ QUICV1),\n/* harmony export */ TCP: () => (/* binding */ TCP),\n/* harmony export */ UDP: () => (/* binding */ UDP),\n/* harmony export */ WebRTC: () => (/* binding */ WebRTC),\n/* harmony export */ WebRTCDirect: () => (/* binding */ WebRTCDirect),\n/* harmony export */ WebSockets: () => (/* binding */ WebSockets),\n/* harmony export */ WebSocketsSecure: () => (/* binding */ WebSocketsSecure),\n/* harmony export */ WebTransport: () => (/* binding */ WebTransport)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/is-ip */ \"./node_modules/@chainsafe/is-ip/lib/is-ip.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base64.js\");\n/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\n\n\n\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma) => {\n return ma.toString().split('/').slice(1);\n};\nconst func = (fn) => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false;\n }\n if (fn(vals[0])) {\n return vals.slice(1);\n }\n return false;\n },\n pattern: 'fn'\n };\n};\nconst literal = (str) => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n };\n};\nconst string = () => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n };\n};\nconst number = () => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n };\n};\nconst peerId = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false;\n }\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__.base58btc.decode(`z${vals[1]}`);\n }\n catch (err) {\n return false;\n }\n }\n else {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/p2p/{peerid}'\n };\n};\nconst certhash = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'certhash') {\n return false;\n }\n try {\n multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_3__.base64url.decode(vals[1]);\n }\n catch {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/certhash/{certhash}'\n };\n};\nconst optional = (matcher) => {\n return {\n match: (vals) => {\n const result = matcher.match(vals);\n if (result === false) {\n return vals;\n }\n return result;\n },\n pattern: `optional(${matcher.pattern})`\n };\n};\nconst or = (...matchers) => {\n return {\n match: (vals) => {\n let matches;\n for (const matcher of matchers) {\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n continue;\n }\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result;\n }\n }\n if (matches == null) {\n return false;\n }\n return matches;\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nconst and = (...matchers) => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n return false;\n }\n vals = result;\n }\n return vals;\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nfunction fmt(...matchers) {\n function match(ma) {\n let parts = toParts(ma);\n for (const matcher of matchers) {\n const result = matcher.match(parts);\n if (result === false) {\n return false;\n }\n parts = result;\n }\n return parts;\n }\n function matches(ma) {\n const result = match(ma);\n return result !== false;\n }\n function exactMatch(ma) {\n const result = match(ma);\n if (result === false) {\n return false;\n }\n return result.length === 0;\n }\n return {\n matches,\n exactMatch\n };\n}\n/**\n * DNS matchers\n */\nconst _DNS4 = and(literal('dns4'), string());\nconst _DNS6 = and(literal('dns6'), string());\nconst _DNSADDR = and(literal('dnsaddr'), string());\nconst _DNS = and(literal('dns'), string());\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nconst DNS4 = fmt(_DNS4);\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nconst DNS6 = fmt(_DNS6);\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * ```\n */\nconst DNSADDR = fmt(_DNSADDR);\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nconst DNS = fmt(or(_DNS, _DNSADDR, _DNS4, _DNS6));\nconst _IP4 = and(literal('ip4'), func(_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv4));\nconst _IP6 = and(literal('ip6'), func(_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv6));\nconst _IP = or(_IP4, _IP6);\nconst _IP_OR_DOMAIN = or(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nconst IP_OR_DOMAIN = fmt(_IP_OR_DOMAIN);\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nconst IP4 = fmt(_IP4);\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nconst IP6 = fmt(_IP6);\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nconst IP = fmt(_IP);\nconst _TCP = and(_IP_OR_DOMAIN, literal('tcp'), number());\nconst _UDP = and(_IP_OR_DOMAIN, literal('udp'), number());\nconst TCP_OR_UDP = or(_TCP, _UDP);\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nconst TCP = fmt(_TCP);\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nconst UDP = fmt(_UDP);\nconst _QUIC = and(_UDP, literal('quic'));\nconst _QUICV1 = and(_UDP, literal('quic-v1'));\nconst QUIC_V0_OR_V1 = or(_QUIC, _QUICV1);\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nconst QUIC = fmt(_QUIC);\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nconst QUICV1 = fmt(_QUICV1);\nconst _WEB = or(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUICV1);\nconst _WebSockets = or(and(_WEB, literal('ws'), optional(peerId())));\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nconst WebSockets = fmt(_WebSockets);\nconst _WebSocketsSecure = or(and(_WEB, literal('wss'), optional(peerId())), and(_WEB, literal('tls'), literal('ws'), optional(peerId())));\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nconst WebSocketsSecure = fmt(_WebSocketsSecure);\nconst _WebRTCDirect = and(TCP_OR_UDP, literal('webrtc-direct'), certhash(), optional(certhash()), optional(peerId()));\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nconst WebRTCDirect = fmt(_WebRTCDirect);\nconst _WebTransport = and(_QUICV1, literal('webtransport'), certhash(), certhash(), optional(peerId()));\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nconst WebTransport = fmt(_WebTransport);\nconst _P2P = or(_WebSockets, _WebSocketsSecure, and(_TCP, optional(peerId())), and(QUIC_V0_OR_V1, optional(peerId())), and(_IP_OR_DOMAIN, optional(peerId())), _WebRTCDirect, _WebTransport, peerId());\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nconst P2P = fmt(_P2P);\nconst _Circuit = and(_P2P, literal('p2p-circuit'), peerId());\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nconst Circuit = fmt(_Circuit);\nconst _WebRTC = or(and(_P2P, literal('p2p-circuit'), literal('webrtc'), peerId()), and(_P2P, literal('webrtc'), optional(peerId())), literal('webrtc'));\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nconst WebRTC = fmt(_WebRTC);\nconst _HTTP = or(and(_IP_OR_DOMAIN, literal('tcp'), number(), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('http'), optional(peerId())));\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nconst HTTP = fmt(_HTTP);\nconst _HTTPS = or(and(_IP_OR_DOMAIN, literal('tcp'), or(and(literal('443'), literal('http')), and(number(), literal('https'))), optional(peerId())), and(_IP_OR_DOMAIN, literal('tls'), literal('http'), optional(peerId())), and(_IP_OR_DOMAIN, literal('https'), optional(peerId())));\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nconst HTTPS = fmt(_HTTPS);\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Circuit: () => (/* binding */ Circuit),\n/* harmony export */ DNS: () => (/* binding */ DNS),\n/* harmony export */ DNS4: () => (/* binding */ DNS4),\n/* harmony export */ DNS6: () => (/* binding */ DNS6),\n/* harmony export */ DNSADDR: () => (/* binding */ DNSADDR),\n/* harmony export */ HTTP: () => (/* binding */ HTTP),\n/* harmony export */ HTTPS: () => (/* binding */ HTTPS),\n/* harmony export */ IP: () => (/* binding */ IP),\n/* harmony export */ IP4: () => (/* binding */ IP4),\n/* harmony export */ IP6: () => (/* binding */ IP6),\n/* harmony export */ IP_OR_DOMAIN: () => (/* binding */ IP_OR_DOMAIN),\n/* harmony export */ Memory: () => (/* binding */ Memory),\n/* harmony export */ P2P: () => (/* binding */ P2P),\n/* harmony export */ QUIC: () => (/* binding */ QUIC),\n/* harmony export */ QUICV1: () => (/* binding */ QUICV1),\n/* harmony export */ TCP: () => (/* binding */ TCP),\n/* harmony export */ UDP: () => (/* binding */ UDP),\n/* harmony export */ WebRTC: () => (/* binding */ WebRTC),\n/* harmony export */ WebRTCDirect: () => (/* binding */ WebRTCDirect),\n/* harmony export */ WebSockets: () => (/* binding */ WebSockets),\n/* harmony export */ WebSocketsSecure: () => (/* binding */ WebSocketsSecure),\n/* harmony export */ WebTransport: () => (/* binding */ WebTransport)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/is-ip */ \"./node_modules/@chainsafe/is-ip/lib/is-ip.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js\");\n/**\n * @packageDocumentation\n *\n * This module exports various matchers that can be used to infer the type of a\n * passed multiaddr.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org')\n *\n * DNS.matches(ma) // true - this is a multiaddr with a DNS address at the start\n * ```\n *\n * @example\n *\n * The default matching behaviour ignores any subsequent tuples in the multiaddr.\n * If you want stricter matching you can use `.exactMatch`:\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS, Circuit } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/dnsaddr/example.org/p2p/QmFoo/p2p-circuit/p2p/QmBar')\n *\n * DNS.exactMatch(ma) // false - this address has extra tuples after the DNS component\n * Circuit.matches(ma) // true\n * Circuit.exactMatch(ma) // true - the extra tuples are circuit relay related\n * ```\n */\n\n\n/**\n * DNS matchers\n */\nconst _DNS4 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('dns4'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)());\nconst _DNS6 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('dns6'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)());\nconst _DNSADDR = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('dnsaddr'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)());\nconst _DNS = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('dns'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)());\n/**\n * Matches dns4 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS4 } from '@multiformats/multiaddr-matcher'\n *\n * DNS4.matches(multiaddr('/dns4/example.org')) // true\n * ```\n */\nconst DNS4 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_DNS4, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\n/**\n * Matches dns6 addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS6 } from '@multiformats/multiaddr-matcher'\n *\n * DNS6.matches(multiaddr('/dns6/example.org')) // true\n * ```\n */\nconst DNS6 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_DNS6, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\n/**\n * Matches dnsaddr addresses.\n *\n * Use {@link DNS DNS} instead to match any type of DNS address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNSADDR } from '@multiformats/multiaddr-matcher'\n *\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNSADDR.matches(multiaddr('/dnsaddr/example.org/p2p/Qmfoo')) // true\n * ```\n */\nconst DNSADDR = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_DNSADDR, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\n/**\n * Matches any dns address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { DNS } from '@multiformats/multiaddr-matcher'\n *\n * DNS.matches(multiaddr('/dnsaddr/example.org')) // true\n * DNS.matches(multiaddr('/dns4/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org')) // true\n * DNS.matches(multiaddr('/dns6/example.org/p2p/Qmfoo')) // true\n * ```\n */\nconst DNS = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_DNS, _DNSADDR, _DNS4, _DNS6), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\nconst _IP4 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('ip4'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.func)(_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv4));\nconst _IP6 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('ip6'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.func)(_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv6));\nconst _IP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_IP4, _IP6);\nconst _IP_OR_DOMAIN = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_IP, _DNS, _DNS4, _DNS6, _DNSADDR);\n/**\n * A matcher for addresses that start with IP or DNS tuples.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP_OR_DOMAIN } from '@multiformats/multiaddr-matcher'\n *\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/ip4/123.123.123.123/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/dns/example.com/p2p/QmFoo')) // true\n * IP_OR_DOMAIN.matches(multiaddr('/p2p/QmFoo')) // false\n * ```\n */\nconst IP_OR_DOMAIN = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_IP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_DNS, _DNSADDR, _DNS4, _DNS6), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()))));\n/**\n * Matches ip4 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP4 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip4/123.123.123.123')\n *\n * IP4.matches(ma) // true\n * ```\n */\nconst IP4 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_IP4);\n/**\n * Matches ip6 addresses.\n *\n * Use {@link IP IP} instead to match any ip4/ip6 address.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP6 } from '@multiformats/multiaddr-matcher'\n *\n * const ma = multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')\n *\n * IP6.matches(ma) // true\n * ```\n */\nconst IP6 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_IP6);\n/**\n * Matches ip4 or ip6 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { IP } from '@multiformats/multiaddr-matcher'\n *\n * IP.matches(multiaddr('/ip4/123.123.123.123')) // true\n * IP.matches(multiaddr('/ip6/fe80::1cc1:a3b8:322f:cf22')) // true\n * ```\n */\nconst IP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_IP);\nconst _TCP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('tcp'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.number)());\nconst _UDP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('udp'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.number)());\n/**\n * Matches TCP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { TCP } from '@multiformats/multiaddr-matcher'\n *\n * TCP.matches(multiaddr('/ip4/123.123.123.123/tcp/1234')) // true\n * ```\n */\nconst TCP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_TCP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches UDP addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { UDP } from '@multiformats/multiaddr-matcher'\n *\n * UDP.matches(multiaddr('/ip4/123.123.123.123/udp/1234')) // true\n * ```\n */\nconst UDP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_UDP);\nconst _QUIC = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_UDP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('quic'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\nconst _QUICV1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_UDP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('quic-v1'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\nconst QUIC_V0_OR_V1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_QUIC, _QUICV1);\n/**\n * Matches QUIC addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUIC } from '@multiformats/multiaddr-matcher'\n *\n * QUIC.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic')) // true\n * ```\n */\nconst QUIC = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_QUIC);\n/**\n * Matches QUICv1 addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { QUICV1 } from '@multiformats/multiaddr-matcher'\n *\n * QUICV1.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1')) // true\n * ```\n */\nconst QUICV1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_QUICV1);\nconst _WEB = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_IP_OR_DOMAIN, _TCP, _UDP, _QUIC, _QUICV1);\nconst _WebSockets = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_WEB, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('ws'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSockets } from '@multiformats/multiaddr-matcher'\n *\n * WebSockets.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/ws')) // true\n * ```\n */\nconst WebSockets = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_WebSockets);\nconst _WebSocketsSecure = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_WEB, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('wss'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_WEB, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('tls'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('sni'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('ws'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches secure WebSocket addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebSocketsSecure } from '@multiformats/multiaddr-matcher'\n *\n * WebSocketsSecure.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/wss')) // true\n * ```\n */\nconst WebSocketsSecure = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_WebSocketsSecure);\nconst _WebRTCDirect = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_UDP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('webrtc-direct'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.certhash)()), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.certhash)()), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\n/**\n * Matches WebRTC-direct addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo/webrtc-direct/certhash/u....')) // true\n * ```\n */\nconst WebRTCDirect = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_WebRTCDirect);\nconst _WebTransport = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_QUICV1, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('webtransport'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.certhash)()), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.certhash)()), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)()));\n/**\n * Matches WebTransport addresses.\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTCDirect } from '@multiformats/multiaddr-matcher'\n *\n * WebRTCDirect.matches(multiaddr('/ip4/123.123.123.123/udp/1234/quic-v1/webtransport/certhash/u..../certhash/u..../p2p/QmFoo')) // true\n * ```\n */\nconst WebTransport = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_WebTransport);\nconst _P2P = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)(_WebSockets, _WebSocketsSecure, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_TCP, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(QUIC_V0_OR_V1, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), _WebRTCDirect, _WebTransport, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)());\n/**\n * Matches peer addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { P2P } from '@multiformats/multiaddr-matcher'\n *\n * P2P.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmFoo')) // true\n * ```\n */\nconst P2P = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_P2P);\nconst _Circuit = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_P2P, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('p2p-circuit'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)());\n/**\n * Matches circuit relay addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Circuit } from '@multiformats/multiaddr-matcher'\n *\n * Circuit.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/p2p/QmTarget')) // true\n * ```\n */\nconst Circuit = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_Circuit);\nconst _WebRTC = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_P2P, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('p2p-circuit'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('webrtc'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_P2P, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('webrtc'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('webrtc'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches WebRTC addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { WebRTC } from '@multiformats/multiaddr-matcher'\n *\n * WebRTC.matches(multiaddr('/ip4/123.123.123.123/tcp/1234/p2p/QmRelay/p2p-circuit/webrtc/p2p/QmTarget')) // true\n * ```\n */\nconst WebRTC = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_WebRTC);\nconst _HTTP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('tcp'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.number)(), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('http'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('http'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches HTTP addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/http')) // true\n * ```\n */\nconst HTTP = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_HTTP);\nconst _HTTPS = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('tcp'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('443'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('http')), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.number)(), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('https'))), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('tls'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('http'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)(_IP_OR_DOMAIN, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('https'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches HTTPS addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { HTTP } from '@multiformats/multiaddr-matcher'\n *\n * HTTP.matches(multiaddr('/dns/example.org/tls/http')) // true\n * ```\n */\nconst HTTPS = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_HTTPS);\nconst _Memory = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.or)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.and)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.literal)('memory'), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string)(), (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.optional)((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.peerId)())));\n/**\n * Matches Memory addresses\n *\n * @example\n *\n * ```ts\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { Memory } from '@multiformats/multiaddr-matcher'\n *\n * Memory.matches(multiaddr('/memory/0xDEADBEEF')) // true\n * ```\n */\nconst Memory = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fmt)(_Memory);\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js": +/*!************************************************************************!*\ + !*** ./node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js ***! + \************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ and: () => (/* binding */ and),\n/* harmony export */ certhash: () => (/* binding */ certhash),\n/* harmony export */ fmt: () => (/* binding */ fmt),\n/* harmony export */ func: () => (/* binding */ func),\n/* harmony export */ literal: () => (/* binding */ literal),\n/* harmony export */ number: () => (/* binding */ number),\n/* harmony export */ optional: () => (/* binding */ optional),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ peerId: () => (/* binding */ peerId),\n/* harmony export */ string: () => (/* binding */ string)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base64.js\");\n\n\n/**\n * Split a multiaddr into path components\n */\nconst toParts = (ma) => {\n return ma.toString().split('/').slice(1);\n};\nconst func = (fn) => {\n return {\n match: (vals) => {\n if (vals.length < 1) {\n return false;\n }\n if (fn(vals[0])) {\n return vals.slice(1);\n }\n return false;\n },\n pattern: 'fn'\n };\n};\nconst literal = (str) => {\n return {\n match: (vals) => func((val) => val === str).match(vals),\n pattern: str\n };\n};\nconst string = () => {\n return {\n match: (vals) => func((val) => typeof val === 'string').match(vals),\n pattern: '{string}'\n };\n};\nconst number = () => {\n return {\n match: (vals) => func((val) => !isNaN(parseInt(val))).match(vals),\n pattern: '{number}'\n };\n};\nconst peerId = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'p2p' && vals[0] !== 'ipfs') {\n return false;\n }\n // Q is RSA, 1 is Ed25519 or Secp256k1\n if (vals[1].startsWith('Q') || vals[1].startsWith('1')) {\n try {\n multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${vals[1]}`);\n }\n catch (err) {\n return false;\n }\n }\n else {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/p2p/{peerid}'\n };\n};\nconst certhash = () => {\n return {\n match: (vals) => {\n if (vals.length < 2) {\n return false;\n }\n if (vals[0] !== 'certhash') {\n return false;\n }\n try {\n multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_1__.base64url.decode(vals[1]);\n }\n catch {\n return false;\n }\n return vals.slice(2);\n },\n pattern: '/certhash/{certhash}'\n };\n};\nconst optional = (matcher) => {\n return {\n match: (vals) => {\n const result = matcher.match(vals);\n if (result === false) {\n return vals;\n }\n return result;\n },\n pattern: `optional(${matcher.pattern})`\n };\n};\nconst or = (...matchers) => {\n return {\n match: (vals) => {\n let matches;\n for (const matcher of matchers) {\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n continue;\n }\n // choose greediest matcher\n if (matches == null || result.length < matches.length) {\n matches = result;\n }\n }\n if (matches == null) {\n return false;\n }\n return matches;\n },\n pattern: `or(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nconst and = (...matchers) => {\n return {\n match: (vals) => {\n for (const matcher of matchers) {\n // pass what's left of the array\n const result = matcher.match(vals);\n // no match\n if (result === false) {\n return false;\n }\n vals = result;\n }\n return vals;\n },\n pattern: `and(${matchers.map(m => m.pattern).join(', ')})`\n };\n};\nfunction fmt(...matchers) {\n function match(ma) {\n let parts = toParts(ma);\n for (const matcher of matchers) {\n const result = matcher.match(parts);\n if (result === false) {\n return false;\n }\n parts = result;\n }\n return parts;\n }\n function matches(ma) {\n const result = match(ma);\n return result !== false;\n }\n function exactMatch(ma) {\n const result = match(ma);\n if (result === false) {\n return false;\n }\n return result.length === 0;\n }\n return {\n matchers,\n matches,\n exactMatch\n };\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-matcher/dist/src/utils.js?"); /***/ }), @@ -7993,7 +12084,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-matcher/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -8048,7 +12139,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ multiaddrToUri: () => (/* binding */ multiaddrToUri)\n/* harmony export */ });\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\n\nconst ASSUME_HTTP_CODES = [\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('tcp').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dnsaddr').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns4').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns6').code\n];\nfunction extractSNI(ma) {\n let sniProtoCode;\n try {\n sniProtoCode = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('sni').code;\n }\n catch (e) {\n // No SNI protocol in multiaddr\n return null;\n }\n for (const [proto, value] of ma) {\n if (proto === sniProtoCode && value !== undefined) {\n return value;\n }\n }\n return null;\n}\nfunction hasTLS(ma) {\n return ma.some(([proto, _]) => proto === (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('tls').code);\n}\nfunction interpretNext(headProtoCode, headProtoVal, restMa) {\n const interpreter = interpreters[(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(headProtoCode).name];\n if (interpreter === undefined) {\n throw new Error(`Can't interpret protocol ${(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(headProtoCode).name}`);\n }\n const restVal = interpreter(headProtoVal, restMa);\n if (headProtoCode === (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('ip6').code) {\n return `[${restVal}]`;\n }\n return restVal;\n}\nconst interpreters = {\n ip4: (value, restMa) => value,\n ip6: (value, restMa) => {\n if (restMa.length === 0) {\n return value;\n }\n return `[${value}]`;\n },\n tcp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n udp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n dnsaddr: (value, restMa) => value,\n dns4: (value, restMa) => value,\n dns6: (value, restMa) => value,\n dns: (value, restMa) => value,\n ipfs: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/ipfs/${value}`;\n },\n p2p: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p/${value}`;\n },\n http: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `https://${sni}`;\n }\n const protocol = maHasTLS ? 'https://' : 'http://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n tls: (value, restMa) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n sni: (value, restMa) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n https: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `https://${baseVal}`;\n },\n ws: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n if (maHasTLS && sni !== null) {\n return `wss://${sni}`;\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://';\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n wss: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `wss://${baseVal}`;\n },\n 'p2p-websocket-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-websocket-star`;\n },\n 'p2p-webrtc-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-star`;\n },\n 'p2p-webrtc-direct': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-direct`;\n }\n};\nfunction multiaddrToUri(input, opts) {\n const ma = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(input);\n const parts = ma.stringTuples();\n const head = parts.pop();\n if (head === undefined) {\n throw new Error('Unexpected end of multiaddr');\n }\n const protocol = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(head[0]);\n const interpreter = interpreters[protocol.name];\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`);\n }\n let uri = interpreter(head[1] ?? '', parts);\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '');\n if (head[1] === '443') {\n uri = `https://${uri}`;\n }\n else {\n uri = `http://${uri}`;\n }\n }\n if (uri.startsWith('http://') || uri.startsWith('https://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString();\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1);\n }\n }\n return uri;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ multiaddrToUri: () => (/* binding */ multiaddrToUri)\n/* harmony export */ });\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * This module allows easy conversion of Multiaddrs to string URIs.\n *\n * @example Converting multiaddrs to string URIs\n *\n * ```js\n * import { multiaddrToUri } from '@multiformats/multiaddr-to-uri'\n *\n * console.log(multiaddrToUri('/dnsaddr/protocol.ai/https'))\n * // -> https://protocol.ai\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080'))\n * // -> http://127.0.0.1:8080\n *\n * console.log(multiaddrToUri('/ip4/127.0.0.1/tcp/8080', { assumeHttp: false }))\n * // -> tcp://127.0.0.1:8080\n * ```\n *\n * Note:\n *\n * - When `/tcp` is the last (terminating) protocol HTTP is assumed by default (implicit `assumeHttp: true`)\n * - this means produced URIs will start with `http://` instead of `tcp://`\n * - passing `{ assumeHttp: false }` disables this behavior\n * - Might be lossy - e.g. a DNSv6 multiaddr\n * - Can throw if the passed multiaddr:\n * - is not a valid multiaddr\n * - is not supported as a URI e.g. circuit\n */\n\nconst ASSUME_HTTP_CODES = [\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('tcp').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dnsaddr').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns4').code,\n (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('dns6').code\n];\nfunction extractSNI(ma) {\n return extractTuple('sni', ma)?.[1];\n}\nfunction extractPort(ma) {\n const port = extractTuple('tcp', ma)?.[1];\n if (port == null) {\n return '';\n }\n return `:${port}`;\n}\nfunction extractTuple(name, ma) {\n let code;\n try {\n code = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(name).code;\n }\n catch (e) {\n // No support for protocol in multiaddr\n return;\n }\n for (const [proto, value] of ma) {\n if (proto === code && value != null) {\n return [proto, value];\n }\n }\n}\nfunction hasTLS(ma) {\n return ma.some(([proto, _]) => proto === (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('tls').code);\n}\nfunction interpretNext(headProtoCode, headProtoVal, restMa) {\n const interpreter = interpreters[(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(headProtoCode).name];\n if (interpreter == null) {\n throw new Error(`Can't interpret protocol ${(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(headProtoCode).name}`);\n }\n const restVal = interpreter(headProtoVal, restMa);\n if (headProtoCode === (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)('ip6').code) {\n return `[${restVal}]`;\n }\n return restVal;\n}\nconst interpreters = {\n ip4: (value, restMa) => value,\n ip6: (value, restMa) => {\n if (restMa.length === 0) {\n return value;\n }\n return `[${value}]`;\n },\n tcp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `tcp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n udp: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `udp://${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}:${value}`;\n },\n dnsaddr: (value, restMa) => value,\n dns4: (value, restMa) => value,\n dns6: (value, restMa) => value,\n dns: (value, restMa) => value,\n ipfs: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/ipfs/${value}`;\n },\n p2p: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p/${value}`;\n },\n http: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n const port = extractPort(restMa);\n if (maHasTLS && sni != null) {\n return `https://${sni}${port}`;\n }\n const protocol = maHasTLS ? 'https://' : 'http://';\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n 'http-path': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n const baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n const decodedValue = decodeURIComponent(value);\n return `${baseVal}/${decodedValue}`;\n },\n tls: (value, restMa) => {\n // Noop, the parent context knows that it's tls. We don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n sni: (value, restMa) => {\n // Noop, the parent context uses the sni information, we don't need to do\n // anything here\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n },\n https: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `https://${baseVal}`;\n },\n ws: (value, restMa) => {\n const maHasTLS = hasTLS(restMa);\n const sni = extractSNI(restMa);\n const port = extractPort(restMa);\n if (maHasTLS && sni != null) {\n return `wss://${sni}${port}`;\n }\n const protocol = maHasTLS ? 'wss://' : 'ws://';\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `${protocol}${baseVal}`;\n },\n wss: (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n let baseVal = interpretNext(tailProto[0], tailProto[1] ?? '', restMa);\n // We are reinterpreting the base as http, so we need to remove the tcp:// if it's there\n baseVal = baseVal.replace('tcp://', '');\n return `wss://${baseVal}`;\n },\n 'p2p-websocket-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-websocket-star`;\n },\n 'p2p-webrtc-star': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-star`;\n },\n 'p2p-webrtc-direct': (value, restMa) => {\n const tailProto = restMa.pop();\n if (tailProto == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n return `${interpretNext(tailProto[0], tailProto[1] ?? '', restMa)}/p2p-webrtc-direct`;\n }\n};\nfunction multiaddrToUri(input, opts) {\n const ma = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(input);\n const parts = ma.stringTuples();\n const head = parts.pop();\n if (head == null) {\n throw new Error('Unexpected end of multiaddr');\n }\n const protocol = (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.protocols)(head[0]);\n const interpreter = interpreters[protocol.name];\n if (interpreter == null) {\n throw new Error(`No interpreter found for ${protocol.name}`);\n }\n let uri = interpreter(head[1] ?? '', parts);\n if (opts?.assumeHttp !== false && ASSUME_HTTP_CODES.includes(head[0])) {\n // strip any declared protocol\n uri = uri.replace(/^.*:\\/\\//, '');\n if (head[1] === '443') {\n uri = `https://${uri}`;\n }\n else {\n uri = `http://${uri}`;\n }\n }\n if (uri.startsWith('http://') || uri.startsWith('https://') || uri.startsWith('ws://') || uri.startsWith('wss://')) {\n // this will strip default ports while keeping paths intact\n uri = new URL(uri).toString();\n // strip trailing slash, e.g. http://127.0.0.1/ -> http://127.0.0.1\n if (uri.endsWith('/')) {\n uri = uri.substring(0, uri.length - 1);\n }\n }\n return uri;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr-to-uri/dist/src/index.js?"); /***/ }), @@ -8070,7 +12161,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ convert: () => (/* binding */ convert),\n/* harmony export */ convertToBytes: () => (/* binding */ convertToBytes),\n/* harmony export */ convertToIpNet: () => (/* binding */ convertToIpNet),\n/* harmony export */ convertToString: () => (/* binding */ convertToString)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_netmask__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/netmask */ \"./node_modules/@chainsafe/netmask/dist/src/index.js\");\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _ip_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ip.js */ \"./node_modules/@multiformats/multiaddr/dist/src/ip.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n/**\n * @packageDocumentation\n *\n * Provides methods for converting\n */\n\n\n\n\n\n\n\n\n\n\n\n\nconst ip4Protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ip4');\nconst ip6Protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ip6');\nconst ipcidrProtocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ipcidr');\nfunction convert(proto, a) {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a);\n }\n else {\n return convertToBytes(proto, a);\n }\n}\n/**\n * Convert [code,Uint8Array] to string\n */\nfunction convertToString(proto, buf) {\n const protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)(proto);\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf);\n case 42: // ipv6zone\n return bytes2str(buf);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString();\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf);\n case 421: // ipfs\n return bytes2mh(buf);\n case 444: // onion\n return bytes2onion(buf);\n case 445: // onion3\n return bytes2onion(buf);\n case 466: // certhash\n return bytes2mb(buf);\n default:\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(buf, 'base16'); // no clue. convert to hex\n }\n}\nfunction convertToBytes(proto, str) {\n const protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)(proto);\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str);\n case 41: // ipv6\n return ip2bytes(str);\n case 42: // ipv6zone\n return str2bytes(str);\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10));\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str);\n case 421: // ipfs\n return mh2bytes(str);\n case 444: // onion\n return onion2bytes(str);\n case 445: // onion3\n return onion32bytes(str);\n case 466: // certhash\n return mb2bytes(str);\n default:\n return (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__.fromString)(str, 'base16'); // no clue. convert from hex\n }\n}\nfunction convertToIpNet(multiaddr) {\n let mask;\n let addr;\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value;\n }\n if (code === ipcidrProtocol.code) {\n mask = value;\n }\n });\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr');\n }\n return new _chainsafe_netmask__WEBPACK_IMPORTED_MODULE_0__.IpNet(addr, mask);\n}\nconst decoders = Object.values(multiformats_basics__WEBPACK_IMPORTED_MODULE_3__.bases).map((c) => c.decoder);\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1]);\n decoders.slice(2).forEach((d) => (acc = acc.or(d)));\n return acc;\n})();\nfunction ip2bytes(ipString) {\n if (!_ip_js__WEBPACK_IMPORTED_MODULE_10__.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return _ip_js__WEBPACK_IMPORTED_MODULE_10__.toBytes(ipString);\n}\nfunction bytes2ip(ipBuff) {\n const ipString = _ip_js__WEBPACK_IMPORTED_MODULE_10__.toString(ipBuff, 0, ipBuff.length);\n if (ipString == null) {\n throw new Error('ipBuff is required');\n }\n if (!_ip_js__WEBPACK_IMPORTED_MODULE_10__.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ipString;\n}\nfunction port2bytes(port) {\n const buf = new ArrayBuffer(2);\n const view = new DataView(buf);\n view.setUint16(0, port);\n return new Uint8Array(buf);\n}\nfunction bytes2port(buf) {\n const view = new DataView(buf.buffer);\n return view.getUint16(buf.byteOffset);\n}\nfunction str2bytes(str) {\n const buf = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__.fromString)(str);\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(buf.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, buf], size.length + buf.length);\n}\nfunction bytes2str(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n buf = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (buf.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(buf);\n}\nfunction mh2bytes(hash) {\n let mh;\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_5__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__.base58btc.decode(`z${hash}`)).bytes;\n }\n else {\n mh = multiformats_cid__WEBPACK_IMPORTED_MODULE_4__.CID.parse(hash).multihash.bytes;\n }\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(mh.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, mh], size.length + mh.length);\n}\nfunction mb2bytes(mbstr) {\n const mb = anybaseDecoder.decode(mbstr);\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(mb.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, mb], size.length + mb.length);\n}\nfunction bytes2mb(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n const hash = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (hash.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return 'u' + (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(hash, 'base64url');\n}\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n const address = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (address.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(address, 'base58btc');\n}\nfunction onion2bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode('b' + addr[0]);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([buf, portBuf], buf.length + portBuf.length);\n}\nfunction onion32bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode(`b${addr[0]}`);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([buf, portBuf], buf.length + portBuf.length);\n}\nfunction bytes2onion(buf) {\n const addrBytes = buf.slice(0, buf.length - 2);\n const portBytes = buf.slice(buf.length - 2);\n const addr = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(addrBytes, 'base32');\n const port = bytes2port(portBytes);\n return `${addr}:${port}`;\n}\n//# sourceMappingURL=convert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/convert.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ convert: () => (/* binding */ convert),\n/* harmony export */ convertToBytes: () => (/* binding */ convertToBytes),\n/* harmony export */ convertToIpNet: () => (/* binding */ convertToIpNet),\n/* harmony export */ convertToString: () => (/* binding */ convertToString)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_netmask__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/netmask */ \"./node_modules/@chainsafe/netmask/dist/src/index.js\");\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _ip_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./ip.js */ \"./node_modules/@multiformats/multiaddr/dist/src/ip.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n\n\n\n\n\n\n\n\n\n\n\n\nconst ip4Protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ip4');\nconst ip6Protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ip6');\nconst ipcidrProtocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)('ipcidr');\nfunction convert(proto, a) {\n if (a instanceof Uint8Array) {\n return convertToString(proto, a);\n }\n else {\n return convertToBytes(proto, a);\n }\n}\n/**\n * Convert [code,Uint8Array] to string\n */\n// eslint-disable-next-line complexity\nfunction convertToString(proto, buf) {\n const protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)(proto);\n switch (protocol.code) {\n case 4: // ipv4\n case 41: // ipv6\n return bytes2ip(buf);\n case 42: // ipv6zone\n return bytes2str(buf);\n case 43: // ipcidr\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(buf, 'base10');\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return bytes2port(buf).toString();\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return bytes2str(buf);\n case 421: // ipfs\n return bytes2mh(buf);\n case 444: // onion\n return bytes2onion(buf);\n case 445: // onion3\n return bytes2onion(buf);\n case 466: // certhash\n return bytes2mb(buf);\n case 481: // http-path\n return globalThis.encodeURIComponent(bytes2str(buf));\n default:\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(buf, 'base16'); // no clue. convert to hex\n }\n}\n// eslint-disable-next-line complexity\nfunction convertToBytes(proto, str) {\n const protocol = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_11__.getProtocol)(proto);\n switch (protocol.code) {\n case 4: // ipv4\n return ip2bytes(str);\n case 41: // ipv6\n return ip2bytes(str);\n case 42: // ipv6zone\n return str2bytes(str);\n case 43: // ipcidr\n return (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__.fromString)(str, 'base10');\n case 6: // tcp\n case 273: // udp\n case 33: // dccp\n case 132: // sctp\n return port2bytes(parseInt(str, 10));\n case 53: // dns\n case 54: // dns4\n case 55: // dns6\n case 56: // dnsaddr\n case 400: // unix\n case 449: // sni\n case 777: // memory\n return str2bytes(str);\n case 421: // ipfs\n return mh2bytes(str);\n case 444: // onion\n return onion2bytes(str);\n case 445: // onion3\n return onion32bytes(str);\n case 466: // certhash\n return mb2bytes(str);\n case 481: // http-path\n return str2bytes(globalThis.decodeURIComponent(str));\n default:\n return (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__.fromString)(str, 'base16'); // no clue. convert from hex\n }\n}\nfunction convertToIpNet(multiaddr) {\n let mask;\n let addr;\n multiaddr.stringTuples().forEach(([code, value]) => {\n if (code === ip4Protocol.code || code === ip6Protocol.code) {\n addr = value;\n }\n if (code === ipcidrProtocol.code) {\n mask = value;\n }\n });\n if (mask == null || addr == null) {\n throw new Error('Invalid multiaddr');\n }\n return new _chainsafe_netmask__WEBPACK_IMPORTED_MODULE_0__.IpNet(addr, mask);\n}\nconst decoders = Object.values(multiformats_basics__WEBPACK_IMPORTED_MODULE_3__.bases).map((c) => c.decoder);\nconst anybaseDecoder = (function () {\n let acc = decoders[0].or(decoders[1]);\n decoders.slice(2).forEach((d) => (acc = acc.or(d)));\n return acc;\n})();\nfunction ip2bytes(ipString) {\n if (!_ip_js__WEBPACK_IMPORTED_MODULE_10__.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return _ip_js__WEBPACK_IMPORTED_MODULE_10__.toBytes(ipString);\n}\nfunction bytes2ip(ipBuff) {\n const ipString = _ip_js__WEBPACK_IMPORTED_MODULE_10__.toString(ipBuff, 0, ipBuff.length);\n if (ipString == null) {\n throw new Error('ipBuff is required');\n }\n if (!_ip_js__WEBPACK_IMPORTED_MODULE_10__.isIP(ipString)) {\n throw new Error('invalid ip address');\n }\n return ipString;\n}\nfunction port2bytes(port) {\n const buf = new ArrayBuffer(2);\n const view = new DataView(buf);\n view.setUint16(0, port);\n return new Uint8Array(buf);\n}\nfunction bytes2port(buf) {\n const view = new DataView(buf.buffer);\n return view.getUint16(buf.byteOffset);\n}\nfunction str2bytes(str) {\n const buf = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_8__.fromString)(str);\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(buf.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, buf], size.length + buf.length);\n}\nfunction bytes2str(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n buf = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (buf.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(buf);\n}\nfunction mh2bytes(hash) {\n let mh;\n if (hash[0] === 'Q' || hash[0] === '1') {\n mh = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_5__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__.base58btc.decode(`z${hash}`)).bytes;\n }\n else {\n mh = multiformats_cid__WEBPACK_IMPORTED_MODULE_4__.CID.parse(hash).multihash.bytes;\n }\n // the address is a varint prefixed multihash string representation\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(mh.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, mh], size.length + mh.length);\n}\nfunction mb2bytes(mbstr) {\n const mb = anybaseDecoder.decode(mbstr);\n const size = Uint8Array.from(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encode(mb.length));\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([size, mb], size.length + mb.length);\n}\nfunction bytes2mb(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n const hash = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (hash.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return 'u' + (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(hash, 'base64url');\n}\n/**\n * Converts bytes to bas58btc string\n */\nfunction bytes2mh(buf) {\n const size = uint8_varint__WEBPACK_IMPORTED_MODULE_6__.decode(buf);\n const address = buf.slice(uint8_varint__WEBPACK_IMPORTED_MODULE_6__.encodingLength(size));\n if (address.length !== size) {\n throw new Error('inconsistent lengths');\n }\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(address, 'base58btc');\n}\nfunction onion2bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 16) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode('b' + addr[0]);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([buf, portBuf], buf.length + portBuf.length);\n}\nfunction onion32bytes(str) {\n const addr = str.split(':');\n if (addr.length !== 2) {\n throw new Error(`failed to parse onion addr: [\"'${addr.join('\", \"')}'\"]' does not contain a port number`);\n }\n if (addr[0].length !== 56) {\n throw new Error(`failed to parse onion addr: ${addr[0]} not a Tor onion3 address.`);\n }\n // onion addresses do not include the multibase prefix, add it before decoding\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode(`b${addr[0]}`);\n // onion port number\n const port = parseInt(addr[1], 10);\n if (port < 1 || port > 65536) {\n throw new Error('Port number is not in range(1, 65536)');\n }\n const portBuf = port2bytes(port);\n return (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_7__.concat)([buf, portBuf], buf.length + portBuf.length);\n}\nfunction bytes2onion(buf) {\n const addrBytes = buf.slice(0, buf.length - 2);\n const portBytes = buf.slice(buf.length - 2);\n const addr = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_9__.toString)(addrBytes, 'base32');\n const port = bytes2port(portBytes);\n return `${addr}:${port}`;\n}\n//# sourceMappingURL=convert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/convert.js?"); /***/ }), @@ -8092,7 +12183,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MultiaddrFilter: () => (/* reexport safe */ _filter_multiaddr_filter_js__WEBPACK_IMPORTED_MODULE_2__.MultiaddrFilter),\n/* harmony export */ fromNodeAddress: () => (/* binding */ fromNodeAddress),\n/* harmony export */ isMultiaddr: () => (/* binding */ isMultiaddr),\n/* harmony export */ isName: () => (/* binding */ isName),\n/* harmony export */ multiaddr: () => (/* binding */ multiaddr),\n/* harmony export */ protocols: () => (/* reexport safe */ _protocols_table_js__WEBPACK_IMPORTED_MODULE_1__.getProtocol),\n/* harmony export */ resolvers: () => (/* binding */ resolvers)\n/* harmony export */ });\n/* harmony import */ var _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./multiaddr.js */ \"./node_modules/@multiformats/multiaddr/dist/src/multiaddr.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n/* harmony import */ var _filter_multiaddr_filter_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./filter/multiaddr-filter.js */ \"./node_modules/@multiformats/multiaddr/dist/src/filter/multiaddr-filter.js\");\n/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * const addr = multiaddr(\"/ip4/127.0.0.1/udp/1234\")\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddr } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddr)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(await ma.resolve(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\n\n/**\n * All configured {@link Resolver}s\n */\nconst resolvers = new Map();\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nfunction fromNodeAddress(addr, transport) {\n if (addr == null) {\n throw new Error('requires node address object');\n }\n if (transport == null) {\n throw new Error('requires transport protocol');\n }\n let ip;\n let host = addr.address;\n switch (addr.family) {\n case 4:\n ip = 'ip4';\n break;\n case 6:\n ip = 'ip6';\n if (host.includes('%')) {\n const parts = host.split('%');\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr');\n }\n host = parts[0];\n const zone = parts[1];\n ip = `/ip6zone/${zone}/ip6`;\n }\n break;\n default:\n throw Error('Invalid addr family, should be 4 or 6.');\n }\n return new _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.Multiaddr('/' + [ip, host, transport, addr.port].join('/'));\n}\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nfunction isName(addr) {\n if (!isMultiaddr(addr)) {\n return false;\n }\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable);\n}\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nfunction isMultiaddr(value) {\n return Boolean(value?.[_multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.symbol]);\n}\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nfunction multiaddr(addr) {\n return new _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.Multiaddr(addr);\n}\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MultiaddrFilter: () => (/* reexport safe */ _filter_multiaddr_filter_js__WEBPACK_IMPORTED_MODULE_2__.MultiaddrFilter),\n/* harmony export */ fromNodeAddress: () => (/* binding */ fromNodeAddress),\n/* harmony export */ isMultiaddr: () => (/* binding */ isMultiaddr),\n/* harmony export */ isName: () => (/* binding */ isName),\n/* harmony export */ multiaddr: () => (/* binding */ multiaddr),\n/* harmony export */ protocols: () => (/* reexport safe */ _protocols_table_js__WEBPACK_IMPORTED_MODULE_1__.getProtocol),\n/* harmony export */ resolvers: () => (/* binding */ resolvers)\n/* harmony export */ });\n/* harmony import */ var _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./multiaddr.js */ \"./node_modules/@multiformats/multiaddr/dist/src/multiaddr.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n/* harmony import */ var _filter_multiaddr_filter_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./filter/multiaddr-filter.js */ \"./node_modules/@multiformats/multiaddr/dist/src/filter/multiaddr-filter.js\");\n/**\n * @packageDocumentation\n *\n * A standard way to represent addresses that\n *\n * - support any standard network protocol\n * - are self-describing\n * - have a binary packed format\n * - have a nice string representation\n * - encapsulate well\n *\n * @example\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const addr = multiaddr('/ip4/127.0.0.1/udp/1234')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234)\n *\n * addr.bytes\n * // \n *\n * addr.toString()\n * // '/ip4/127.0.0.1/udp/1234'\n *\n * addr.protos()\n * // [\n * // {code: 4, name: 'ip4', size: 32},\n * // {code: 273, name: 'udp', size: 16}\n * // ]\n *\n * // gives you an object that is friendly with what Node.js core modules expect for addresses\n * addr.nodeAddress()\n * // {\n * // family: 4,\n * // port: 1234,\n * // address: \"127.0.0.1\"\n * // }\n *\n * addr.encapsulate('/sctp/5678')\n * // Multiaddr(/ip4/127.0.0.1/udp/1234/sctp/5678)\n * ```\n *\n * ## Resolving DNSADDR addresses\n *\n * [DNSADDR](https://github.com/multiformats/multiaddr/blob/master/protocols/DNSADDR.md) is a spec that allows storing a TXT DNS record that contains a Multiaddr.\n *\n * To resolve DNSADDR addresses, call the `.resolve()` function the multiaddr, optionally passing a `DNS` resolver.\n *\n * DNSADDR addresses can resolve to multiple multiaddrs, since there is no limit to the number of TXT records that can be stored.\n *\n * @example Resolving DNSADDR Multiaddrs\n *\n * ```TypeScript\n * import { multiaddr, resolvers } from '@multiformats/multiaddr'\n * import { dnsaddrResolver } from '@multiformats/multiaddr/resolvers'\n *\n * resolvers.set('dnsaddr', dnsaddrResolver)\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n *\n * // resolve with a 5s timeout\n * const resolved = await ma.resolve({\n * signal: AbortSignal.timeout(5000)\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n *\n * @example Using a custom DNS resolver to resolve DNSADDR Multiaddrs\n *\n * See the docs for [@multiformats/dns](https://www.npmjs.com/package/@multiformats/dns) for a full breakdown of how to specify multiple resolvers or resolvers that can be used for specific TLDs.\n *\n * ```TypeScript\n * import { multiaddr } from '@multiformats/multiaddr'\n * import { dns } from '@multiformats/dns'\n * import { dnsJsonOverHttps } from '@multiformats/dns/resolvers'\n *\n * const resolver = dns({\n * resolvers: {\n * '.': dnsJsonOverHttps('https://cloudflare-dns.com/dns-query')\n * }\n * })\n *\n * const ma = multiaddr('/dnsaddr/bootstrap.libp2p.io')\n * const resolved = await ma.resolve({\n * dns: resolver\n * })\n *\n * console.info(resolved)\n * // [Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...'), Multiaddr('/ip4/147.75...')...]\n * ```\n */\n\n\n/**\n * All configured {@link Resolver}s\n */\nconst resolvers = new Map();\n\n/**\n * Creates a Multiaddr from a node-friendly address object\n *\n * @example\n * ```js\n * import { fromNodeAddress } from '@multiformats/multiaddr'\n *\n * fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n */\nfunction fromNodeAddress(addr, transport) {\n if (addr == null) {\n throw new Error('requires node address object');\n }\n if (transport == null) {\n throw new Error('requires transport protocol');\n }\n let ip;\n let host = addr.address;\n switch (addr.family) {\n case 4:\n ip = 'ip4';\n break;\n case 6:\n ip = 'ip6';\n if (host.includes('%')) {\n const parts = host.split('%');\n if (parts.length !== 2) {\n throw Error('Multiple ip6 zones in multiaddr');\n }\n host = parts[0];\n const zone = parts[1];\n ip = `/ip6zone/${zone}/ip6`;\n }\n break;\n default:\n throw Error('Invalid addr family, should be 4 or 6.');\n }\n return new _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.Multiaddr('/' + [ip, host, transport, addr.port].join('/'));\n}\n/**\n * Returns if something is a {@link Multiaddr} that is a resolvable name\n *\n * @example\n *\n * ```js\n * import { isName, multiaddr } from '@multiformats/multiaddr'\n *\n * isName(multiaddr('/ip4/127.0.0.1'))\n * // false\n * isName(multiaddr('/dns/ipfs.io'))\n * // true\n * ```\n */\nfunction isName(addr) {\n if (!isMultiaddr(addr)) {\n return false;\n }\n // if a part of the multiaddr is resolvable, then return true\n return addr.protos().some((proto) => proto.resolvable);\n}\n/**\n * Check if object is a {@link Multiaddr} instance\n *\n * @example\n *\n * ```js\n * import { isMultiaddr, multiaddr } from '@multiformats/multiaddr'\n *\n * isMultiaddr(5)\n * // false\n * isMultiaddr(multiaddr('/ip4/127.0.0.1'))\n * // true\n * ```\n */\nfunction isMultiaddr(value) {\n return Boolean(value?.[_multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.symbol]);\n}\n/**\n * A function that takes a {@link MultiaddrInput} and returns a {@link Multiaddr}\n *\n * @example\n * ```js\n * import { multiaddr } from '@libp2p/multiaddr'\n *\n * multiaddr('/ip4/127.0.0.1/tcp/4001')\n * // Multiaddr(/ip4/127.0.0.1/tcp/4001)\n * ```\n *\n * @param {MultiaddrInput} [addr] - If String or Uint8Array, needs to adhere to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format)\n */\nfunction multiaddr(addr) {\n return new _multiaddr_js__WEBPACK_IMPORTED_MODULE_0__.Multiaddr(addr);\n}\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/index.js?"); /***/ }), @@ -8114,7 +12205,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Multiaddr: () => (/* binding */ Multiaddr),\n/* harmony export */ symbol: () => (/* binding */ symbol)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@multiformats/multiaddr/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./codec.js */ \"./node_modules/@multiformats/multiaddr/dist/src/codec.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a Multiaddr in JavaScript\n *\n * @example\n *\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * const ma = multiaddr('/ip4/127.0.0.1/tcp/1234')\n * ```\n */\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');\nconst DNS_CODES = [\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns4').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns6').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dnsaddr').code\n];\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass Multiaddr {\n bytes;\n #string;\n #tuples;\n #stringTuples;\n #path;\n [symbol] = true;\n constructor(addr) {\n // default\n if (addr == null) {\n addr = '';\n }\n let parts;\n if (addr instanceof Uint8Array) {\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.bytesToMultiaddrParts)(addr);\n }\n else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`);\n }\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.stringToMultiaddrParts)(addr);\n }\n else if ((0,_index_js__WEBPACK_IMPORTED_MODULE_6__.isMultiaddr)(addr)) { // Multiaddr\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.bytesToMultiaddrParts)(addr.bytes);\n }\n else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr');\n }\n this.bytes = parts.bytes;\n this.#string = parts.string;\n this.#tuples = parts.tuples;\n this.#stringTuples = parts.stringTuples;\n this.#path = parts.path;\n }\n toString() {\n return this.#string;\n }\n toJSON() {\n return this.toString();\n }\n toOptions() {\n let family;\n let transport;\n let host;\n let port;\n let zone = '';\n const tcp = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('tcp');\n const udp = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('udp');\n const ip4 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip4');\n const ip6 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip6');\n const dns6 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns6');\n const ip6zone = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip6zone');\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`;\n }\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name;\n port = 443;\n host = `${value ?? ''}${zone}`;\n family = code === dns6.code ? 6 : 4;\n }\n if (code === tcp.code || code === udp.code) {\n transport = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name;\n port = parseInt(value ?? '');\n }\n if (code === ip4.code || code === ip6.code) {\n transport = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name;\n host = `${value ?? ''}${zone}`;\n family = code === ip6.code ? 6 : 4;\n }\n }\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".');\n }\n const opts = {\n family,\n host,\n transport,\n port\n };\n return opts;\n }\n protos() {\n return this.#tuples.map(([code]) => Object.assign({}, (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code)));\n }\n protoCodes() {\n return this.#tuples.map(([code]) => code);\n }\n protoNames() {\n return this.#tuples.map(([code]) => (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name);\n }\n tuples() {\n return this.#tuples;\n }\n stringTuples() {\n return this.#stringTuples;\n }\n encapsulate(addr) {\n addr = new Multiaddr(addr);\n return new Multiaddr(this.toString() + addr.toString());\n }\n decapsulate(addr) {\n const addrString = addr.toString();\n const s = this.toString();\n const i = s.lastIndexOf(addrString);\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);\n }\n return new Multiaddr(s.slice(0, i));\n }\n decapsulateCode(code) {\n const tuples = this.tuples();\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr((0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.tuplesToBytes)(tuples.slice(0, i)));\n }\n }\n return this;\n }\n getPeerId() {\n try {\n let tuples = [];\n this.stringTuples().forEach(([code, name]) => {\n if (code === _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.names.p2p.code) {\n tuples.push([code, name]);\n }\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.names['p2p-circuit'].code) {\n tuples = [];\n }\n });\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop();\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1];\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__.toString)(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${peerIdStr}`), 'base58btc');\n }\n // try to parse peer id as CID\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__.toString)(multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.parse(peerIdStr).multihash.bytes, 'base58btc');\n }\n return null;\n }\n catch (e) {\n return null;\n }\n }\n getPath() {\n return this.#path;\n }\n equals(addr) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(this.bytes, addr.bytes);\n }\n async resolve(options) {\n const resolvableProto = this.protos().find((p) => p.resolvable);\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this];\n }\n const resolver = _index_js__WEBPACK_IMPORTED_MODULE_6__.resolvers.get(resolvableProto.name);\n if (resolver == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError(`no available resolver for ${resolvableProto.name}`, 'ERR_NO_AVAILABLE_RESOLVER');\n }\n const result = await resolver(this, options);\n return result.map(str => (0,_index_js__WEBPACK_IMPORTED_MODULE_6__.multiaddr)(str));\n }\n nodeAddress() {\n const options = this.toOptions();\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`);\n }\n return {\n family: options.family,\n address: options.host,\n port: options.port\n };\n }\n isThinWaistAddress(addr) {\n const protos = (addr ?? this).protos();\n if (protos.length !== 2) {\n return false;\n }\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false;\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false;\n }\n return true;\n }\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect]() {\n return `Multiaddr(${this.#string})`;\n }\n}\n//# sourceMappingURL=multiaddr.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/multiaddr.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Multiaddr: () => (/* binding */ Multiaddr),\n/* harmony export */ symbol: () => (/* binding */ symbol)\n/* harmony export */ });\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@multiformats/multiaddr/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _codec_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./codec.js */ \"./node_modules/@multiformats/multiaddr/dist/src/codec.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst symbol = Symbol.for('@multiformats/js-multiaddr/multiaddr');\nconst DNS_CODES = [\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns4').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns6').code,\n (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dnsaddr').code\n];\nclass NoAvailableResolverError extends Error {\n constructor(message = 'No available resolver') {\n super(message);\n this.name = 'NoAvailableResolverError';\n }\n}\n/**\n * Creates a {@link Multiaddr} from a {@link MultiaddrInput}\n */\nclass Multiaddr {\n bytes;\n #string;\n #tuples;\n #stringTuples;\n #path;\n [symbol] = true;\n constructor(addr) {\n // default\n if (addr == null) {\n addr = '';\n }\n let parts;\n if (addr instanceof Uint8Array) {\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.bytesToMultiaddrParts)(addr);\n }\n else if (typeof addr === 'string') {\n if (addr.length > 0 && addr.charAt(0) !== '/') {\n throw new Error(`multiaddr \"${addr}\" must start with a \"/\"`);\n }\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.stringToMultiaddrParts)(addr);\n }\n else if ((0,_index_js__WEBPACK_IMPORTED_MODULE_6__.isMultiaddr)(addr)) { // Multiaddr\n parts = (0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.bytesToMultiaddrParts)(addr.bytes);\n }\n else {\n throw new Error('addr must be a string, Buffer, or another Multiaddr');\n }\n this.bytes = parts.bytes;\n this.#string = parts.string;\n this.#tuples = parts.tuples;\n this.#stringTuples = parts.stringTuples;\n this.#path = parts.path;\n }\n toString() {\n return this.#string;\n }\n toJSON() {\n return this.toString();\n }\n toOptions() {\n let family;\n let transport;\n let host;\n let port;\n let zone = '';\n const tcp = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('tcp');\n const udp = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('udp');\n const ip4 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip4');\n const ip6 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip6');\n const dns6 = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('dns6');\n const ip6zone = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)('ip6zone');\n for (const [code, value] of this.stringTuples()) {\n if (code === ip6zone.code) {\n zone = `%${value ?? ''}`;\n }\n // default to https when protocol & port are omitted from DNS addrs\n if (DNS_CODES.includes(code)) {\n transport = tcp.name;\n port = 443;\n host = `${value ?? ''}${zone}`;\n family = code === dns6.code ? 6 : 4;\n }\n if (code === tcp.code || code === udp.code) {\n transport = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name;\n port = parseInt(value ?? '');\n }\n if (code === ip4.code || code === ip6.code) {\n transport = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name;\n host = `${value ?? ''}${zone}`;\n family = code === ip6.code ? 6 : 4;\n }\n }\n if (family == null || transport == null || host == null || port == null) {\n throw new Error('multiaddr must have a valid format: \"/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}\".');\n }\n const opts = {\n family,\n host,\n transport,\n port\n };\n return opts;\n }\n protos() {\n return this.#tuples.map(([code]) => Object.assign({}, (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code)));\n }\n protoCodes() {\n return this.#tuples.map(([code]) => code);\n }\n protoNames() {\n return this.#tuples.map(([code]) => (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.getProtocol)(code).name);\n }\n tuples() {\n return this.#tuples.map(([code, value]) => {\n if (value == null) {\n return [code];\n }\n return [code, value];\n });\n }\n stringTuples() {\n return this.#stringTuples.map(([code, value]) => {\n if (value == null) {\n return [code];\n }\n return [code, value];\n });\n }\n encapsulate(addr) {\n addr = new Multiaddr(addr);\n return new Multiaddr(this.toString() + addr.toString());\n }\n decapsulate(addr) {\n const addrString = addr.toString();\n const s = this.toString();\n const i = s.lastIndexOf(addrString);\n if (i < 0) {\n throw new Error(`Address ${this.toString()} does not contain subaddress: ${addr.toString()}`);\n }\n return new Multiaddr(s.slice(0, i));\n }\n decapsulateCode(code) {\n const tuples = this.tuples();\n for (let i = tuples.length - 1; i >= 0; i--) {\n if (tuples[i][0] === code) {\n return new Multiaddr((0,_codec_js__WEBPACK_IMPORTED_MODULE_4__.tuplesToBytes)(tuples.slice(0, i)));\n }\n }\n return this;\n }\n getPeerId() {\n try {\n let tuples = [];\n this.stringTuples().forEach(([code, name]) => {\n if (code === _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.names.p2p.code) {\n tuples.push([code, name]);\n }\n // if this is a p2p-circuit address, return the target peer id if present\n // not the peer id of the relay\n if (code === _protocols_table_js__WEBPACK_IMPORTED_MODULE_5__.names['p2p-circuit'].code) {\n tuples = [];\n }\n });\n // Get the last ipfs tuple ['p2p', 'peerid string']\n const tuple = tuples.pop();\n if (tuple?.[1] != null) {\n const peerIdStr = tuple[1];\n // peer id is base58btc encoded string but not multibase encoded so add the `z`\n // prefix so we can validate that it is correctly encoded\n if (peerIdStr[0] === 'Q' || peerIdStr[0] === '1') {\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__.toString)(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${peerIdStr}`), 'base58btc');\n }\n // try to parse peer id as CID\n return (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_3__.toString)(multiformats_cid__WEBPACK_IMPORTED_MODULE_1__.CID.parse(peerIdStr).multihash.bytes, 'base58btc');\n }\n return null;\n }\n catch (e) {\n return null;\n }\n }\n getPath() {\n return this.#path;\n }\n equals(addr) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(this.bytes, addr.bytes);\n }\n async resolve(options) {\n const resolvableProto = this.protos().find((p) => p.resolvable);\n // Multiaddr is not resolvable?\n if (resolvableProto == null) {\n return [this];\n }\n const resolver = _index_js__WEBPACK_IMPORTED_MODULE_6__.resolvers.get(resolvableProto.name);\n if (resolver == null) {\n throw new NoAvailableResolverError(`no available resolver for ${resolvableProto.name}`);\n }\n const result = await resolver(this, options);\n return result.map(str => (0,_index_js__WEBPACK_IMPORTED_MODULE_6__.multiaddr)(str));\n }\n nodeAddress() {\n const options = this.toOptions();\n if (options.transport !== 'tcp' && options.transport !== 'udp') {\n throw new Error(`multiaddr must have a valid format - no protocol with name: \"${options.transport}\". Must have a valid transport protocol: \"{tcp, udp}\"`);\n }\n return {\n family: options.family,\n address: options.host,\n port: options.port\n };\n }\n isThinWaistAddress(addr) {\n const protos = (addr ?? this).protos();\n if (protos.length !== 2) {\n return false;\n }\n if (protos[0].code !== 4 && protos[0].code !== 41) {\n return false;\n }\n if (protos[1].code !== 6 && protos[1].code !== 273) {\n return false;\n }\n return true;\n }\n /**\n * Returns Multiaddr as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```js\n * import { multiaddr } from '@multiformats/multiaddr'\n *\n * console.info(multiaddr('/ip4/127.0.0.1/tcp/4001'))\n * // 'Multiaddr(/ip4/127.0.0.1/tcp/4001)'\n * ```\n */\n [inspect]() {\n return `Multiaddr(${this.#string})`;\n }\n}\n//# sourceMappingURL=multiaddr.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/multiaddr.js?"); /***/ }), @@ -8125,7 +12216,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ codes: () => (/* binding */ codes),\n/* harmony export */ createProtocol: () => (/* binding */ createProtocol),\n/* harmony export */ getProtocol: () => (/* binding */ getProtocol),\n/* harmony export */ names: () => (/* binding */ names),\n/* harmony export */ table: () => (/* binding */ table)\n/* harmony export */ });\nconst V = -1;\nconst names = {};\nconst codes = {};\nconst table = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [777, V, 'memory']\n];\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row);\n codes[proto.code] = proto;\n names[proto.name] = proto;\n});\nfunction createProtocol(code, size, name, resolvable, path) {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n };\n}\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nfunction getProtocol(proto) {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto];\n }\n throw new Error(`no protocol with code: ${proto}`);\n }\n else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto];\n }\n throw new Error(`no protocol with name: ${proto}`);\n }\n throw new Error(`invalid protocol id type: ${typeof proto}`);\n}\n//# sourceMappingURL=protocols-table.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ codes: () => (/* binding */ codes),\n/* harmony export */ createProtocol: () => (/* binding */ createProtocol),\n/* harmony export */ getProtocol: () => (/* binding */ getProtocol),\n/* harmony export */ names: () => (/* binding */ names),\n/* harmony export */ table: () => (/* binding */ table)\n/* harmony export */ });\nconst V = -1;\nconst names = {};\nconst codes = {};\nconst table = [\n [4, 32, 'ip4'],\n [6, 16, 'tcp'],\n [33, 16, 'dccp'],\n [41, 128, 'ip6'],\n [42, V, 'ip6zone'],\n [43, 8, 'ipcidr'],\n [53, V, 'dns', true],\n [54, V, 'dns4', true],\n [55, V, 'dns6', true],\n [56, V, 'dnsaddr', true],\n [132, 16, 'sctp'],\n [273, 16, 'udp'],\n [275, 0, 'p2p-webrtc-star'],\n [276, 0, 'p2p-webrtc-direct'],\n [277, 0, 'p2p-stardust'],\n [280, 0, 'webrtc-direct'],\n [281, 0, 'webrtc'],\n [290, 0, 'p2p-circuit'],\n [301, 0, 'udt'],\n [302, 0, 'utp'],\n [400, V, 'unix', false, true],\n // `ipfs` is added before `p2p` for legacy support.\n // All text representations will default to `p2p`, but `ipfs` will\n // still be supported\n [421, V, 'ipfs'],\n // `p2p` is the preferred name for 421, and is now the default\n [421, V, 'p2p'],\n [443, 0, 'https'],\n [444, 96, 'onion'],\n [445, 296, 'onion3'],\n [446, V, 'garlic64'],\n [448, 0, 'tls'],\n [449, V, 'sni'],\n [460, 0, 'quic'],\n [461, 0, 'quic-v1'],\n [465, 0, 'webtransport'],\n [466, V, 'certhash'],\n [477, 0, 'ws'],\n [478, 0, 'wss'],\n [479, 0, 'p2p-websocket-star'],\n [480, 0, 'http'],\n [481, V, 'http-path'],\n [777, V, 'memory']\n];\n// populate tables\ntable.forEach(row => {\n const proto = createProtocol(...row);\n codes[proto.code] = proto;\n names[proto.name] = proto;\n});\nfunction createProtocol(code, size, name, resolvable, path) {\n return {\n code,\n size,\n name,\n resolvable: Boolean(resolvable),\n path: Boolean(path)\n };\n}\n/**\n * For the passed proto string or number, return a {@link Protocol}\n *\n * @example\n *\n * ```js\n * import { protocol } from '@multiformats/multiaddr'\n *\n * console.info(protocol(4))\n * // { code: 4, size: 32, name: 'ip4', resolvable: false, path: false }\n * ```\n */\nfunction getProtocol(proto) {\n if (typeof proto === 'number') {\n if (codes[proto] != null) {\n return codes[proto];\n }\n throw new Error(`no protocol with code: ${proto}`);\n }\n else if (typeof proto === 'string') {\n if (names[proto] != null) {\n return names[proto];\n }\n throw new Error(`no protocol with name: ${proto}`);\n }\n throw new Error(`invalid protocol id type: ${typeof proto}`);\n}\n//# sourceMappingURL=protocols-table.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js?"); /***/ }), @@ -8136,7 +12227,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ dnsaddrResolver: () => (/* binding */ dnsaddrResolver)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@multiformats/multiaddr/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _multiformats_dns__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/dns */ \"./node_modules/@multiformats/dns/dist/src/index.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index.js */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n\n\n\n\nconst MAX_RECURSIVE_DEPTH = 32;\nconst { code: dnsaddrCode } = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_2__.getProtocol)('dnsaddr');\nconst dnsaddrResolver = async function dnsaddrResolver(ma, options = {}) {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH;\n if (recursionLimit === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Max recursive depth reached', 'ERR_MAX_RECURSIVE_DEPTH_REACHED');\n }\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? [];\n const resolver = options?.dns ?? (0,_multiformats_dns__WEBPACK_IMPORTED_MODULE_0__.dns)();\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n _multiformats_dns__WEBPACK_IMPORTED_MODULE_0__.RecordType.TXT\n ]\n });\n const peerId = ma.getPeerId();\n const output = [];\n for (const answer of result.Answer) {\n const addr = answer.data.split('=')[1];\n if (addr == null) {\n continue;\n }\n if (peerId != null && !addr.includes(peerId)) {\n continue;\n }\n const ma = (0,_index_js__WEBPACK_IMPORTED_MODULE_1__.multiaddr)(addr);\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n });\n output.push(...resolved.map(ma => ma.toString()));\n }\n else {\n output.push(ma.toString());\n }\n }\n return output;\n};\n//# sourceMappingURL=dnsaddr.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/resolvers/dnsaddr.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ dnsaddrResolver: () => (/* binding */ dnsaddrResolver)\n/* harmony export */ });\n/* harmony import */ var _multiformats_dns__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/dns */ \"./node_modules/@multiformats/dns/dist/src/index.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index.js */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _protocols_table_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../protocols-table.js */ \"./node_modules/@multiformats/multiaddr/dist/src/protocols-table.js\");\n\n\n\nconst MAX_RECURSIVE_DEPTH = 32;\nconst { code: dnsaddrCode } = (0,_protocols_table_js__WEBPACK_IMPORTED_MODULE_2__.getProtocol)('dnsaddr');\nclass RecursionLimitError extends Error {\n constructor(message = 'Max recursive depth reached') {\n super(message);\n this.name = 'RecursionLimitError';\n }\n}\nconst dnsaddrResolver = async function dnsaddrResolver(ma, options = {}) {\n const recursionLimit = options.maxRecursiveDepth ?? MAX_RECURSIVE_DEPTH;\n if (recursionLimit === 0) {\n throw new RecursionLimitError('Max recursive depth reached');\n }\n const [, hostname] = ma.stringTuples().find(([proto]) => proto === dnsaddrCode) ?? [];\n const resolver = options?.dns ?? (0,_multiformats_dns__WEBPACK_IMPORTED_MODULE_0__.dns)();\n const result = await resolver.query(`_dnsaddr.${hostname}`, {\n signal: options?.signal,\n types: [\n _multiformats_dns__WEBPACK_IMPORTED_MODULE_0__.RecordType.TXT\n ]\n });\n const peerId = ma.getPeerId();\n const output = [];\n for (const answer of result.Answer) {\n const addr = answer.data\n .replace(/[\"']/g, '')\n .trim()\n .split('=')[1];\n if (addr == null) {\n continue;\n }\n if (peerId != null && !addr.includes(peerId)) {\n continue;\n }\n const ma = (0,_index_js__WEBPACK_IMPORTED_MODULE_1__.multiaddr)(addr);\n if (addr.startsWith('/dnsaddr')) {\n const resolved = await ma.resolve({\n ...options,\n maxRecursiveDepth: recursionLimit - 1\n });\n output.push(...resolved.map(ma => ma.toString()));\n }\n else {\n output.push(ma.toString());\n }\n }\n return output;\n};\n//# sourceMappingURL=dnsaddr.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/dist/src/resolvers/dnsaddr.js?"); /***/ }), @@ -8151,17 +12242,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@multiformats/multiaddr/node_modules/@libp2p/interface/dist/src/errors.js": -/*!************************************************************************************************!*\ - !*** ./node_modules/@multiformats/multiaddr/node_modules/@libp2p/interface/dist/src/errors.js ***! - \************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ AggregateCodeError: () => (/* binding */ AggregateCodeError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* binding */ ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* binding */ ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* binding */ ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* binding */ ERR_TIMEOUT),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* binding */ InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* binding */ InvalidCryptoTransmissionError),\n/* harmony export */ UnexpectedPeerError: () => (/* binding */ UnexpectedPeerError)\n/* harmony export */ });\n/**\n * When this error is thrown it means an operation was aborted,\n * usually in response to the `abort` event being emitted by an\n * AbortSignal.\n */\nclass AbortError extends Error {\n code;\n type;\n constructor(message = 'The operation was aborted') {\n super(message);\n this.name = 'AbortError';\n this.code = AbortError.code;\n this.type = AbortError.type;\n }\n static code = 'ABORT_ERR';\n static type = 'aborted';\n}\nclass CodeError extends Error {\n code;\n props;\n constructor(message, code, props) {\n super(message);\n this.code = code;\n this.name = props?.name ?? 'CodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass AggregateCodeError extends AggregateError {\n code;\n props;\n constructor(errors, message, code, props) {\n super(errors, message);\n this.code = code;\n this.name = props?.name ?? 'AggregateCodeError';\n this.props = props ?? {}; // eslint-disable-line @typescript-eslint/consistent-type-assertions\n }\n}\nclass UnexpectedPeerError extends Error {\n code;\n constructor(message = 'Unexpected Peer') {\n super(message);\n this.name = 'UnexpectedPeerError';\n this.code = UnexpectedPeerError.code;\n }\n static code = 'ERR_UNEXPECTED_PEER';\n}\nclass InvalidCryptoExchangeError extends Error {\n code;\n constructor(message = 'Invalid crypto exchange') {\n super(message);\n this.name = 'InvalidCryptoExchangeError';\n this.code = InvalidCryptoExchangeError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_EXCHANGE';\n}\nclass InvalidCryptoTransmissionError extends Error {\n code;\n constructor(message = 'Invalid crypto transmission') {\n super(message);\n this.name = 'InvalidCryptoTransmissionError';\n this.code = InvalidCryptoTransmissionError.code;\n }\n static code = 'ERR_INVALID_CRYPTO_TRANSMISSION';\n}\n// Error codes\nconst ERR_TIMEOUT = 'ERR_TIMEOUT';\nconst ERR_INVALID_PARAMETERS = 'ERR_INVALID_PARAMETERS';\nconst ERR_NOT_FOUND = 'ERR_NOT_FOUND';\nconst ERR_INVALID_MESSAGE = 'ERR_INVALID_MESSAGE';\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/@libp2p/interface/dist/src/errors.js?"); - -/***/ }), - /***/ "./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js": /*!***********************************************************************************************!*\ !*** ./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js ***! @@ -8169,7 +12249,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -8213,7 +12293,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -8334,7 +12414,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -8378,7 +12458,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@multiformats/multiaddr/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -8631,7 +12711,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createCurve: () => (/* binding */ createCurve),\n/* harmony export */ getHash: () => (/* binding */ getHash)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/hmac */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstract/weierstrass.js */ \"./node_modules/@noble/curves/esm/abstract/weierstrass.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n// connects noble-curves to noble-hashes\nfunction getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => (0,_noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__.hmac)(hash, key, (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...msgs)),\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes,\n };\n}\nfunction createCurve(curveDef, defHash) {\n const create = (hash) => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__.weierstrass)({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/_shortw_utils.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createCurve: () => (/* binding */ createCurve),\n/* harmony export */ getHash: () => (/* binding */ getHash)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/hmac */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./abstract/weierstrass.js */ \"./node_modules/@noble/curves/esm/abstract/weierstrass.js\");\n/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n/** connects noble-curves to noble-hashes */\nfunction getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => (0,_noble_hashes_hmac__WEBPACK_IMPORTED_MODULE_0__.hmac)(hash, key, (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.concatBytes)(...msgs)),\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_1__.randomBytes,\n };\n}\nfunction createCurve(curveDef, defHash) {\n const create = (hash) => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_2__.weierstrass)({ ...curveDef, ...getHash(hash) });\n return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/_shortw_utils.js?"); /***/ }), @@ -8642,7 +12722,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ validateBasic: () => (/* binding */ validateBasic),\n/* harmony export */ wNAF: () => (/* binding */ wNAF)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\n\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nfunction wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nfunction validateBasic(curve) {\n (0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.validateField)(curve.Fp);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject)(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...(0,_modular_js__WEBPACK_IMPORTED_MODULE_0__.nLength)(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/curve.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ pippenger: () => (/* binding */ pippenger),\n/* harmony export */ precomputeMSMUnsafe: () => (/* binding */ precomputeMSMUnsafe),\n/* harmony export */ validateBasic: () => (/* binding */ validateBasic),\n/* harmony export */ wNAF: () => (/* binding */ wNAF)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction constTimeNegate(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\n}\nfunction validateW(W, bits) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, bits) {\n validateW(W, bits);\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap(); // This allows use make points immutable (nothing changes inside)\nfunction getW(P) {\n return pointWindowSizes.get(P) || 1;\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nfunction wNAF(c, bits) {\n return {\n constTimeNegate,\n hasPrecomputes(elm) {\n return getW(elm) !== 1;\n },\n // non-const time multiplication ladder\n unsafeLadder(elm, n, p = c.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param elm Point instance\n * @param W window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = calcWOpts(W, bits);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n /**\n * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @param acc accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {\n const { windows, windowSize } = calcWOpts(W, bits);\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n if (n === _0n)\n break; // No need to go over empty scalar\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n if (wbits === 0)\n continue;\n let curr = precomputes[offset + Math.abs(wbits) - 1]; // -1 because we skip zero\n if (wbits < 0)\n curr = curr.negate();\n // NOTE: by re-using acc, we can save a lot of additions in case of MSM\n acc = acc.add(curr);\n }\n return acc;\n },\n getPrecomputes(W, P, transform) {\n // Calculate precomputes on a first run, reuse them after\n let comp = pointPrecomputes.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1)\n pointPrecomputes.set(P, transform(comp));\n }\n return comp;\n },\n wNAFCached(P, n, transform) {\n const W = getW(P);\n return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n },\n wNAFCachedUnsafe(P, n, transform, prev) {\n const W = getW(P);\n if (W === 1)\n return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n },\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n setWindowSize(P, W) {\n validateW(W, bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n },\n };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster with precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nfunction pippenger(c, fieldN, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n const wbits = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bitLen)(BigInt(points.length));\n const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; // in bits\n const MASK = (1 << windowSize) - 1;\n const buckets = new Array(MASK + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < scalars.length; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & BigInt(MASK));\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nfunction precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = BigInt((1 << windowSize) - 1);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\nfunction validateBasic(curve) {\n (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.validateField)(curve.Fp);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...(0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.nLength)(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/curve.js?"); /***/ }), @@ -8653,7 +12733,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ twistedEdwards: () => (/* binding */ twistedEdwards)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./curve.js */ \"./node_modules/@noble/curves/esm/abstract/curve.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y²\n\n\n\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nfunction twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n, max) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n, max) {\n // n in [1..max-1]\n if (inRange(n, max))\n return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map();\n function isPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n if (!in0MaskRange(ex))\n throw new Error('x required');\n if (!in0MaskRange(ey))\n throw new Error('y required');\n if (!in0MaskRange(ez))\n throw new Error('z required');\n if (!in0MaskRange(et))\n throw new Error('t required');\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y))\n throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n const { a, d } = CURVE;\n if (this.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar) {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n)\n return I;\n if (this.equals(I) || n === _1n)\n return this;\n if (this.equals(G))\n return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n }\n else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215)\n assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else\n assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.wNAF)(Point, nByteLength * 8);\n function modN(a) {\n return (0,_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(_utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = nByteLength;\n key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(R, _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(s, Fp.BYTES));\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('result', res, nByteLength * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.\n msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/edwards.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ twistedEdwards: () => (/* binding */ twistedEdwards)\n/* harmony export */ });\n/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./curve.js */ \"./node_modules/@noble/curves/esm/abstract/curve.js\");\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\nfunction validateOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(curve, {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n }, {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n });\n // Set defaults\n return Object.freeze({ ...opts });\n}\n/**\n * Creates Twisted Edwards curve with EdDSA signatures.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h\n * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })\n */\nfunction twistedEdwards(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER, prehash: prehash, hash: cHash, randomBytes, nByteLength, h: cofactor, } = CURVE;\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n const Fn = (0,_modular_js__WEBPACK_IMPORTED_MODULE_2__.Field)(CURVE.n, CURVE.nBitLength);\n // sqrt(u/v)\n const uvRatio = CURVE.uvRatio ||\n ((u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes); // NOOP\n const domain = CURVE.domain ||\n ((data, ctx, phflag) => {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.abool)('phflag', phflag);\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n // 0 <= n < MASK\n // Coordinates larger than Fp.ORDER are allowed for zip215\n function aCoordinate(title, n) {\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.aInRange('coordinate ' + title, n, _0n, MASK);\n }\n function assertPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ExtendedPoint expected');\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n const toAffineMemo = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.memoized)((p, iz) => {\n const { ex: x, ey: y, ez: z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n const assertValidMemo = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.memoized)((p) => {\n const { a, d } = CURVE;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return true;\n });\n // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n aCoordinate('x', ex);\n aCoordinate('y', ey);\n aCoordinate('z', ez);\n aCoordinate('t', et);\n Object.freeze(this);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n aCoordinate('x', x);\n aCoordinate('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.pippenger)(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity() {\n assertValidMemo(this);\n }\n // Compare one point to another.\n equals(other) {\n assertPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n assertPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n)\n return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n // Constant-time multiplication.\n multiply(scalar) {\n const n = scalar;\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.aInRange('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L\n const { p, f } = this.wNAF(n);\n return Point.normalizeZ([p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n // Accepts optional accumulator to merge with multiply (important for sparse scalars)\n multiplyUnsafe(scalar, acc = Point.ZERO) {\n const n = scalar;\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.aInRange('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L\n if (n === _0n)\n return I;\n if (this.is0() || n === _1n)\n return this;\n return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.multiplyUnsafe(cofactor).is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n clearCofactor() {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex, zip215 = false) {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex, len); // copy hex to a new array\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.abool)('zip215', zip215);\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.aInRange('pointHex.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes() {\n const { x, y } = this.toAffine();\n const bytes = _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n const { BASE: G, ZERO: I } = Point;\n const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.wNAF)(Point, nByteLength * 8);\n function modN(a) {\n return (0,_modular_js__WEBPACK_IMPORTED_MODULE_2__.mod)(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash) {\n return modN(_utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(hash));\n }\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key) {\n const len = Fp.BYTES;\n key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey) {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context = new Uint8Array(), ...msgs) {\n const msg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('context', context), !!prehash)));\n }\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg, privKey, options = {}) {\n msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.aInRange('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l\n const res = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(R, _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesLE(s, Fp.BYTES));\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('result', res, Fp.BYTES * 2); // 64-byte signature\n }\n const verifyOpts = VERIFY_DEFAULT;\n /**\n * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n * An extended group equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.\n msg = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('message', msg);\n publicKey = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('publicKey', publicKey, len);\n if (zip215 !== undefined)\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.abool)('zip215', zip215);\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const s = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberLE(sig.slice(len, 2 * len));\n let A, R, SB;\n try {\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder())\n return false;\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Extended group equation\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: () => randomBytes(Fp.BYTES),\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n//# sourceMappingURL=edwards.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/edwards.js?"); /***/ }), @@ -8664,7 +12744,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createHasher: () => (/* binding */ createHasher),\n/* harmony export */ expand_message_xmd: () => (/* binding */ expand_message_xmd),\n/* harmony export */ expand_message_xof: () => (/* binding */ expand_message_xof),\n/* harmony export */ hash_to_field: () => (/* binding */ hash_to_field),\n/* harmony export */ isogenyMap: () => (/* binding */ isogenyMap)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n if (value < 0 || value >= 1 << (8 * length)) {\n throw new Error(`bad I2OSP call: value=${value} length=${length}`);\n }\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\nfunction anum(item) {\n if (!Number.isSafeInteger(item))\n throw new Error('number expected');\n}\n// Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1\nfunction expand_message_xmd(msg, DST, lenInBytes, H) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (ell > 255)\n throw new Error('Invalid xmd length');\n const DST_prime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...args));\n }\n const pseudo_random_bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n// Produces a uniformly random byte string using an extendable-output function (XOF) H.\n// 1. The collision resistance of H MUST be at least k bits.\n// 2. H MUST be an XOF that has been proved indifferentiable from\n// a random oracle under a reasonable cryptographic assumption.\n// https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2\nfunction expand_message_xof(msg, DST, lenInBytes, k, H) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F\n * https://www.rfc-editor.org/rfc/rfc9380#section-5.2\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nfunction hash_to_field(msg, count, options) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nfunction isogenyMap(field, map) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x, y };\n };\n}\nfunction createHasher(Point, mapToCurve, def) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg, options) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg, options) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/hash-to-curve.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createHasher: () => (/* binding */ createHasher),\n/* harmony export */ expand_message_xmd: () => (/* binding */ expand_message_xmd),\n/* harmony export */ expand_message_xof: () => (/* binding */ expand_message_xof),\n/* harmony export */ hash_to_field: () => (/* binding */ hash_to_field),\n/* harmony export */ isogenyMap: () => (/* binding */ isogenyMap)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE)\nfunction i2osp(value, length) {\n anum(value);\n anum(length);\n if (value < 0 || value >= 1 << (8 * length))\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\nfunction anum(item) {\n if (!Number.isSafeInteger(item))\n throw new Error('number expected');\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.\n * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).\n */\nfunction expand_message_xmd(msg, DST, lenInBytes, H) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(DST, i2osp(DST.length, 1));\n const Z_pad = i2osp(0, r_in_bytes);\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(b_0, i2osp(1, 1), DST_prime));\n for (let i = 1; i <= ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...args));\n }\n const pseudo_random_bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes)(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).\n */\nfunction expand_message_xof(msg, DST, lenInBytes, k, H) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(DST);\n anum(lenInBytes);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // DST = H('H2C-OVERSIZE-DST-' || a_very_long_DST, Math.ceil((lenInBytes * k) / 8));\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).\n * @param msg a byte string containing the message to hash\n * @param count the number of elements of F to output\n * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above\n * @returns [u_0, ..., u_(count - 1)], a list of field elements.\n */\nfunction hash_to_field(msg, count, options) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(options, {\n DST: 'stringOrUint8Array',\n p: 'bigint',\n m: 'isSafeInteger',\n k: 'isSafeInteger',\n hash: 'hash',\n });\n const { p, k, m, hash, expand, DST: _DST } = options;\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(msg);\n anum(count);\n const DST = typeof _DST === 'string' ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(_DST) : _DST;\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\nfunction isogenyMap(field, map) {\n // Make same order as in spec\n const COEFF = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n x = field.div(xNum, xDen); // xNum / xDen\n y = field.mul(y, field.div(yNum, yDen)); // y * (yNum / yDev)\n return { x: x, y: y };\n };\n}\n/** Creates hash-to-curve methods from EC Point and mapToCurve function. */\nfunction createHasher(Point, mapToCurve, def) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n return {\n // Encodes byte string to elliptic curve.\n // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n hashToCurve(msg, options) {\n const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options });\n const u0 = Point.fromAffine(mapToCurve(u[0]));\n const u1 = Point.fromAffine(mapToCurve(u[1]));\n const P = u0.add(u1).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Encodes byte string to elliptic curve.\n // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3\n encodeToCurve(msg, options) {\n const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options });\n const P = Point.fromAffine(mapToCurve(u[0])).clearCofactor();\n P.assertValidity();\n return P;\n },\n // Same as encodeToCurve, but without hash\n mapToCurve(scalars) {\n if (!Array.isArray(scalars))\n throw new Error('mapToCurve: expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('mapToCurve: expected array of bigints');\n const P = Point.fromAffine(mapToCurve(scalars)).clearCofactor();\n P.assertValidity();\n return P;\n },\n };\n}\n//# sourceMappingURL=hash-to-curve.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/hash-to-curve.js?"); /***/ }), @@ -8675,7 +12755,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Field: () => (/* binding */ Field),\n/* harmony export */ FpDiv: () => (/* binding */ FpDiv),\n/* harmony export */ FpInvertBatch: () => (/* binding */ FpInvertBatch),\n/* harmony export */ FpIsSquare: () => (/* binding */ FpIsSquare),\n/* harmony export */ FpPow: () => (/* binding */ FpPow),\n/* harmony export */ FpSqrt: () => (/* binding */ FpSqrt),\n/* harmony export */ FpSqrtEven: () => (/* binding */ FpSqrtEven),\n/* harmony export */ FpSqrtOdd: () => (/* binding */ FpSqrtOdd),\n/* harmony export */ getFieldBytesLength: () => (/* binding */ getFieldBytesLength),\n/* harmony export */ getMinHashLength: () => (/* binding */ getMinHashLength),\n/* harmony export */ hashToPrivateScalar: () => (/* binding */ hashToPrivateScalar),\n/* harmony export */ invert: () => (/* binding */ invert),\n/* harmony export */ isNegativeLE: () => (/* binding */ isNegativeLE),\n/* harmony export */ mapHashToField: () => (/* binding */ mapHashToField),\n/* harmony export */ mod: () => (/* binding */ mod),\n/* harmony export */ nLength: () => (/* binding */ nLength),\n/* harmony export */ pow: () => (/* binding */ pow),\n/* harmony export */ pow2: () => (/* binding */ pow2),\n/* harmony export */ tonelliShanks: () => (/* binding */ tonelliShanks),\n/* harmony export */ validateField: () => (/* binding */ validateField)\n/* harmony export */ });\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nfunction mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nfunction pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nfunction pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nfunction invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nfunction tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nfunction FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nconst isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nfunction validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nfunction FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nfunction FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nfunction FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nfunction FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nfunction nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nfunction Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bitMask)(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(num, BYTES) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(bytes) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(bytes);\n },\n });\n return Object.freeze(f);\n}\nfunction FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nfunction FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nfunction hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(hash) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nfunction getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nfunction getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nfunction mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(key) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(reduced, fieldLen) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/modular.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Field: () => (/* binding */ Field),\n/* harmony export */ FpDiv: () => (/* binding */ FpDiv),\n/* harmony export */ FpInvertBatch: () => (/* binding */ FpInvertBatch),\n/* harmony export */ FpIsSquare: () => (/* binding */ FpIsSquare),\n/* harmony export */ FpLegendre: () => (/* binding */ FpLegendre),\n/* harmony export */ FpPow: () => (/* binding */ FpPow),\n/* harmony export */ FpSqrt: () => (/* binding */ FpSqrt),\n/* harmony export */ FpSqrtEven: () => (/* binding */ FpSqrtEven),\n/* harmony export */ FpSqrtOdd: () => (/* binding */ FpSqrtOdd),\n/* harmony export */ getFieldBytesLength: () => (/* binding */ getFieldBytesLength),\n/* harmony export */ getMinHashLength: () => (/* binding */ getMinHashLength),\n/* harmony export */ hashToPrivateScalar: () => (/* binding */ hashToPrivateScalar),\n/* harmony export */ invert: () => (/* binding */ invert),\n/* harmony export */ isNegativeLE: () => (/* binding */ isNegativeLE),\n/* harmony export */ mapHashToField: () => (/* binding */ mapHashToField),\n/* harmony export */ mod: () => (/* binding */ mod),\n/* harmony export */ nLength: () => (/* binding */ nLength),\n/* harmony export */ pow: () => (/* binding */ pow),\n/* harmony export */ pow2: () => (/* binding */ pow2),\n/* harmony export */ tonelliShanks: () => (/* binding */ tonelliShanks),\n/* harmony export */ validateField: () => (/* binding */ validateField)\n/* harmony export */ });\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// prettier-ignore\nconst _9n = /* @__PURE__ */ BigInt(9), _16n = /* @__PURE__ */ BigInt(16);\n// Calculates a modulo b\nfunction mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @todo use field version && remove\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nfunction pow(num, power, modulo) {\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (modulo <= _0n)\n throw new Error('invalid modulus');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nfunction pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nfunction invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nfunction tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) {\n // Crash instead of infinity loop, we cannot reasonable count until P.\n if (Z > 1000)\n throw new Error('Cannot find square root: likely non-prime P');\n }\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n/**\n * Square root for a finite field. It will try to check if optimizations are applicable and fall back to 4:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nfunction FpSqrt(P) {\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nconst isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nfunction validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nfunction FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nfunction FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nfunction FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n/**\n * Legendre symbol.\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n */\nfunction FpLegendre(order) {\n const legendreConst = (order - _1n) / _2n; // Integer arithmetic\n return (f, x) => f.pow(x, legendreConst);\n}\n// This function returns True whenever the value x is a square in the field F.\nfunction FpIsSquare(f) {\n const legendre = FpLegendre(f.ORDER);\n return (x) => {\n const p = legendre(f, x);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nfunction nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nfunction Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n let sqrtP; // cached sqrtP\n const f = Object.freeze({\n ORDER,\n isLE,\n BITS,\n BYTES,\n MASK: (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bitMask)(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt ||\n ((n) => {\n if (!sqrtP)\n sqrtP = FpSqrt(ORDER);\n return sqrtP(f, n);\n }),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(num, BYTES) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(bytes) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(bytes);\n },\n });\n return Object.freeze(f);\n}\nfunction FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nfunction FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nfunction hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(hash) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nfunction getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nfunction getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nfunction mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(key) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE)(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(reduced, fieldLen) : (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE)(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/modular.js?"); /***/ }), @@ -8686,7 +12766,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ montgomery: () => (/* binding */ montgomery)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nfunction montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.pow)(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // Accepts 0 as well\n function assertFieldElement(n) {\n if (typeof n === 'bigint' && _0n <= n && n < P)\n return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU, scalar) {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(u);\n }\n function decodeScalar(n) {\n const bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/montgomery.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ montgomery: () => (/* binding */ montgomery)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction validateOpts(curve) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject)(curve, {\n a: 'bigint',\n }, {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n });\n // Set defaults\n return Object.freeze({ ...curve });\n}\n// Uses only one coordinate instead of two\nfunction montgomery(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.mod)(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x) => (0,_modular_js__WEBPACK_IMPORTED_MODULE_1__.pow)(x, P - BigInt(2), P));\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap, x_2, x_3) {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(u, scalar) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange)('u', u, _0n, P);\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange)('scalar', scalar, _0n, P);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n function encodeUCoordinate(u) {\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesLE)(modP(u), montgomeryBytes);\n }\n function decodeUCoordinate(uEnc) {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32)\n u[31] &= 127; // 0b0111_1111\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(u);\n }\n function decodeScalar(n) {\n const bytes = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen) {\n let valid = '' + montgomeryBytes + ' or ' + fieldLen;\n throw new Error('invalid scalar, expected ' + valid + ' bytes, got ' + len);\n }\n return (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberLE)(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar, u) {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n)\n throw new Error('invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar) {\n return scalarMult(scalar, GuBytes);\n }\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey, publicKey) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey) => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n//# sourceMappingURL=montgomery.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/montgomery.js?"); /***/ }), @@ -8697,7 +12777,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ abytes: () => (/* binding */ abytes),\n/* harmony export */ bitGet: () => (/* binding */ bitGet),\n/* harmony export */ bitLen: () => (/* binding */ bitLen),\n/* harmony export */ bitMask: () => (/* binding */ bitMask),\n/* harmony export */ bitSet: () => (/* binding */ bitSet),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ bytesToNumberBE: () => (/* binding */ bytesToNumberBE),\n/* harmony export */ bytesToNumberLE: () => (/* binding */ bytesToNumberLE),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createHmacDrbg: () => (/* binding */ createHmacDrbg),\n/* harmony export */ ensureBytes: () => (/* binding */ ensureBytes),\n/* harmony export */ equalBytes: () => (/* binding */ equalBytes),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ hexToNumber: () => (/* binding */ hexToNumber),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ numberToBytesBE: () => (/* binding */ numberToBytesBE),\n/* harmony export */ numberToBytesLE: () => (/* binding */ numberToBytesLE),\n/* harmony export */ numberToHexUnpadded: () => (/* binding */ numberToHexUnpadded),\n/* harmony export */ numberToVarBytesBE: () => (/* binding */ numberToVarBytesBE),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ validateObject: () => (/* binding */ validateObject)\n/* harmony export */ });\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nfunction bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nfunction numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nfunction numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nfunction numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nfunction ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nfunction equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nfunction bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nfunction bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nfunction bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nconst bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nfunction createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nfunction validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/utils.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ aInRange: () => (/* binding */ aInRange),\n/* harmony export */ abool: () => (/* binding */ abool),\n/* harmony export */ abytes: () => (/* binding */ abytes),\n/* harmony export */ bitGet: () => (/* binding */ bitGet),\n/* harmony export */ bitLen: () => (/* binding */ bitLen),\n/* harmony export */ bitMask: () => (/* binding */ bitMask),\n/* harmony export */ bitSet: () => (/* binding */ bitSet),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ bytesToNumberBE: () => (/* binding */ bytesToNumberBE),\n/* harmony export */ bytesToNumberLE: () => (/* binding */ bytesToNumberLE),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createHmacDrbg: () => (/* binding */ createHmacDrbg),\n/* harmony export */ ensureBytes: () => (/* binding */ ensureBytes),\n/* harmony export */ equalBytes: () => (/* binding */ equalBytes),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ hexToNumber: () => (/* binding */ hexToNumber),\n/* harmony export */ inRange: () => (/* binding */ inRange),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ memoized: () => (/* binding */ memoized),\n/* harmony export */ notImplemented: () => (/* binding */ notImplemented),\n/* harmony export */ numberToBytesBE: () => (/* binding */ numberToBytesBE),\n/* harmony export */ numberToBytesLE: () => (/* binding */ numberToBytesLE),\n/* harmony export */ numberToHexUnpadded: () => (/* binding */ numberToHexUnpadded),\n/* harmony export */ numberToVarBytesBE: () => (/* binding */ numberToVarBytesBE),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ validateObject: () => (/* binding */ validateObject)\n/* harmony export */ });\n/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nfunction abytes(item) {\n if (!isBytes(item))\n throw new Error('Uint8Array expected');\n}\nfunction abool(title, value) {\n if (typeof value !== 'boolean')\n throw new Error(title + ' boolean expected, got ' + value);\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nfunction numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\nfunction hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nfunction bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nfunction bytesToNumberLE(bytes) {\n abytes(bytes);\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nfunction numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nfunction numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nfunction numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nfunction ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n }\n }\n else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(title + ' must be hex string or Uint8Array');\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// Compares 2 u8a-s in kinda constant time\nfunction equalBytes(a, b) {\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nfunction inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nfunction aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nfunction bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nfunction bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nfunction bitSet(n, pos, value) {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nconst bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nfunction createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nfunction validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error('invalid validator function');\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nconst notImplemented = () => {\n throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nfunction memoized(fn) {\n const map = new WeakMap();\n return (arg, ...args) => {\n const val = map.get(arg);\n if (val !== undefined)\n return val;\n const computed = fn(arg, ...args);\n map.set(arg, computed);\n return computed;\n };\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/utils.js?"); /***/ }), @@ -8708,7 +12788,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DER: () => (/* binding */ DER),\n/* harmony export */ SWUFpSqrtRatio: () => (/* binding */ SWUFpSqrtRatio),\n/* harmony export */ mapToCurveSimpleSWU: () => (/* binding */ mapToCurveSimpleSWU),\n/* harmony export */ weierstrass: () => (/* binding */ weierstrass),\n/* harmony export */ weierstrassPoints: () => (/* binding */ weierstrassPoints)\n/* harmony export */ });\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./curve.js */ \"./node_modules/@noble/curves/esm/abstract/curve.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\n\n\n\n\nfunction validatePointOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = _utils_js__WEBPACK_IMPORTED_MODULE_1__;\nconst DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.abytes(data);\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nfunction weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (_utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(key))\n key = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_0__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_1__.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nfunction weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToHex(_utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = _modular_js__WEBPACK_IMPORTED_MODULE_2__.getMinHashLength(CURVE.n);\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = _utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = _utils_js__WEBPACK_IMPORTED_MODULE_1__.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return _utils_js__WEBPACK_IMPORTED_MODULE_1__.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);\n if (prehash)\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('extraEntropy', e)); // check for being bytes\n }\n const seed = _utils_js__WEBPACK_IMPORTED_MODULE_1__.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = _utils_js__WEBPACK_IMPORTED_MODULE_1__.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('msgHash', msgHash);\n publicKey = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.ensureBytes)('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || _utils_js__WEBPACK_IMPORTED_MODULE_1__.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nfunction SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nfunction mapToCurveSimpleSWU(Fp, opts) {\n _modular_js__WEBPACK_IMPORTED_MODULE_2__.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/weierstrass.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DER: () => (/* binding */ DER),\n/* harmony export */ DERErr: () => (/* binding */ DERErr),\n/* harmony export */ SWUFpSqrtRatio: () => (/* binding */ SWUFpSqrtRatio),\n/* harmony export */ mapToCurveSimpleSWU: () => (/* binding */ mapToCurveSimpleSWU),\n/* harmony export */ weierstrass: () => (/* binding */ weierstrass),\n/* harmony export */ weierstrassPoints: () => (/* binding */ weierstrassPoints)\n/* harmony export */ });\n/* harmony import */ var _curve_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./curve.js */ \"./node_modules/@noble/curves/esm/abstract/curve.js\");\n/* harmony import */ var _modular_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\nfunction validateSigVerOpts(opts) {\n if (opts.lowS !== undefined)\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abool)('lowS', opts.lowS);\n if (opts.prehash !== undefined)\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abool)('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_1__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('invalid endomorphism, can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('invalid endomorphism, expected beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = _utils_js__WEBPACK_IMPORTED_MODULE_0__;\nclass DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nconst DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = DER;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length & 1)\n throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = _utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 128)\n throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? _utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToHexUnpadded((len.length / 2) | 128) : '';\n const t = _utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag, data) {\n const { Err: E } = DER;\n let pos = 0;\n if (tag < 0 || tag > 256)\n throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n let length = 0;\n if (!isLong)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 127;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num) {\n const { Err: E } = DER;\n if (num < _0n)\n throw new E('integer: negative integers are not allowed');\n let hex = _utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = DER;\n if (data[0] & 128)\n throw new E('invalid signature integer: negative');\n if (data[0] === 0x00 && !(data[1] & 128))\n throw new E('invalid signature integer: unnecessary leading zero');\n return b2n(data);\n },\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.abytes(data);\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nfunction weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const Fn = _modular_js__WEBPACK_IMPORTED_MODULE_2__.Field(CURVE.n, CURVE.nBitLength);\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.inRange(num, _1n, CURVE.n);\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (_utils_js__WEBPACK_IMPORTED_MODULE_0__.isBytes(key))\n key = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('invalid private key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);\n }\n if (wrapPrivateKey)\n num = _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(num, N); // disabled by default, enabled for BLS\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('private key', num, _1n, N); // num in range [1..N-1]\n return num;\n }\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n // Memoized toAffine / validity check. They are heavy. Points are immutable.\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n const toAffineMemo = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.memoized)((p, iz) => {\n const { px: x, py: y, pz: z } = p;\n // Fast-path for normalized points\n if (Fp.eql(z, Fp.ONE))\n return { x, y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n });\n // NOTE: on exception this will crash 'cached' and no value will be set.\n // Otherwise true will be return\n const assertValidMemo = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.memoized)((p) => {\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is invalid representation of ZERO.\n if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n return true;\n });\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n Object.freeze(this);\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // Multiscalar Multiplication\n static msm(points, scalars) {\n return (0,_curve_js__WEBPACK_IMPORTED_MODULE_1__.pippenger)(Point, Fn, points, scalars);\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n wnaf.setWindowSize(this, windowSize);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n assertValidMemo(this);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, n, Point.normalizeZ);\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(sc) {\n const { endo, n: N } = CURVE;\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('scalar', sc, _0n, N);\n const I = Point.ZERO;\n if (sc === _0n)\n return I;\n if (this.is0() || sc === _1n)\n return this;\n // Case a: no endomorphism. Case b: has precomputes.\n if (!endo || wnaf.hasPrecomputes(this))\n return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n // Case c: endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n const { endo, n: N } = CURVE;\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('scalar', scalar, _1n, N);\n let point, fake; // Fake point is used to const-time mult\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n return toAffineMemo(this, iz);\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abool)('isCompressed', isCompressed);\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abool)('isCompressed', isCompressed);\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = (0,_curve_js__WEBPACK_IMPORTED_MODULE_1__.wNAF)(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = (0,_curve_js__WEBPACK_IMPORTED_MODULE_1__.validateBasic)(curve);\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nfunction weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function modN(a) {\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = _utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes;\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.abool)('isCompressed', isCompressed);\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE(tail);\n if (!_utils_js__WEBPACK_IMPORTED_MODULE_0__.inRange(x, _1n, Fp.ORDER))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n }\n catch (sqrtError) {\n const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('Point is not on curve' + suffix);\n }\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n const cl = compressedLen;\n const ul = uncompressedLen;\n throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);\n }\n },\n });\n const numToNByteStr = (num) => _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToHex(_utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('r', this.r, _1n, CURVE_ORDER); // r in [1..N]\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('s', this.s, _1n, CURVE_ORDER); // s in [1..N]\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = _modular_js__WEBPACK_IMPORTED_MODULE_2__.getMinHashLength(CURVE.n);\n return _modular_js__WEBPACK_IMPORTED_MODULE_2__.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = _utils_js__WEBPACK_IMPORTED_MODULE_0__.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // Our custom check \"just in case\"\n if (bytes.length > 8192)\n throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = _utils_js__WEBPACK_IMPORTED_MODULE_0__.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n _utils_js__WEBPACK_IMPORTED_MODULE_0__.aInRange('num < 2^' + CURVE.nBitLength, num, _0n, ORDER_MASK);\n // works with order, can have different size than numToField!\n return _utils_js__WEBPACK_IMPORTED_MODULE_0__.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('msgHash', msgHash);\n validateSigVerOpts(opts);\n if (prehash)\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null && ent !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push((0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('extraEntropy', e)); // check for being bytes\n }\n const seed = _utils_js__WEBPACK_IMPORTED_MODULE_0__.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = _utils_js__WEBPACK_IMPORTED_MODULE_0__.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('msgHash', msgHash);\n publicKey = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.ensureBytes)('publicKey', publicKey);\n const { lowS, prehash, format } = opts;\n // Verify opts, deduce signature format\n validateSigVerOpts(opts);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n if (format !== undefined && format !== 'compact' && format !== 'der')\n throw new Error('format must be compact or der');\n const isHex = typeof sg === 'string' || _utils_js__WEBPACK_IMPORTED_MODULE_0__.isBytes(sg);\n const isObj = !isHex &&\n !format &&\n typeof sg === 'object' &&\n sg !== null &&\n typeof sg.r === 'bigint' &&\n typeof sg.s === 'bigint';\n if (!isHex && !isObj)\n throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n let _sig = undefined;\n let P;\n try {\n if (isObj)\n _sig = new Signature(sg.r, sg.s);\n if (isHex) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n if (format !== 'compact')\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n }\n if (!_sig && format !== 'der')\n _sig = Signature.fromCompact(sg);\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n return false;\n }\n if (!_sig)\n return false;\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nfunction SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nfunction mapToCurveSimpleSWU(Fp, opts) {\n _modular_js__WEBPACK_IMPORTED_MODULE_2__.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/abstract/weierstrass.js?"); /***/ }), @@ -8719,7 +12799,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ED25519_TORSION_SUBGROUP: () => (/* binding */ ED25519_TORSION_SUBGROUP),\n/* harmony export */ RistrettoPoint: () => (/* binding */ RistrettoPoint),\n/* harmony export */ ed25519: () => (/* binding */ ed25519),\n/* harmony export */ ed25519ctx: () => (/* binding */ ed25519ctx),\n/* harmony export */ ed25519ph: () => (/* binding */ ed25519ph),\n/* harmony export */ edwardsToMontgomery: () => (/* binding */ edwardsToMontgomery),\n/* harmony export */ edwardsToMontgomeryPriv: () => (/* binding */ edwardsToMontgomeryPriv),\n/* harmony export */ edwardsToMontgomeryPub: () => (/* binding */ edwardsToMontgomeryPub),\n/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),\n/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),\n/* harmony export */ hashToRistretto255: () => (/* binding */ hashToRistretto255),\n/* harmony export */ hash_to_ristretto255: () => (/* binding */ hash_to_ristretto255),\n/* harmony export */ x25519: () => (/* binding */ x25519)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/@noble/hashes/esm/sha512.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/edwards.js */ \"./node_modules/@noble/curves/esm/abstract/edwards.js\");\n/* harmony import */ var _abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./abstract/montgomery.js */ \"./node_modules/@noble/curves/esm/abstract/montgomery.js\");\n/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ \"./node_modules/@noble/curves/esm/abstract/hash-to-curve.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\n\n\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\nfunction ed25519_pow_2_252_3(x) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b4, _1n, P) * x) % P; // x^31\n const b10 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b5, _5n, P) * b5) % P;\n const b20 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b10, _10n, P) * b10) % P;\n const b40 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b20, _20n, P) * b20) % P;\n const b80 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b40, _40n, P) * b40) % P;\n const b160 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b80, _80n, P) * b80) % P;\n const b240 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b160, _80n, P) * b80) % P;\n const b250 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * v * v, P); // v³\n const v7 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))\n x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nconst ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(ED25519_P, undefined, true);\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n};\nconst ed25519 = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)(ed25519Defaults);\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.concatBytes)((0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nconst ed25519ctx = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nconst ed25519ph = /* @__PURE__ */ (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n});\nconst x25519 = /* @__PURE__ */ (() => (0,_abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__.montgomery)({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nfunction edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nconst edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nfunction edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n}))();\nconst hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nconst encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToNumberLE)(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!(0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!(0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.equalBytes)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32), hex) || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))\n s = mod(-s);\n return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32); // 11\n }\n toHex() {\n return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToHex)(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nconst RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nconst hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)(d) : d;\n const uniform_bytes = (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.expand_message_xmd)(msg, DST, 64, _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nconst hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/ed25519.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ED25519_TORSION_SUBGROUP: () => (/* binding */ ED25519_TORSION_SUBGROUP),\n/* harmony export */ RistrettoPoint: () => (/* binding */ RistrettoPoint),\n/* harmony export */ ed25519: () => (/* binding */ ed25519),\n/* harmony export */ ed25519ctx: () => (/* binding */ ed25519ctx),\n/* harmony export */ ed25519ph: () => (/* binding */ ed25519ph),\n/* harmony export */ edwardsToMontgomery: () => (/* binding */ edwardsToMontgomery),\n/* harmony export */ edwardsToMontgomeryPriv: () => (/* binding */ edwardsToMontgomeryPriv),\n/* harmony export */ edwardsToMontgomeryPub: () => (/* binding */ edwardsToMontgomeryPub),\n/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),\n/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),\n/* harmony export */ hashToRistretto255: () => (/* binding */ hashToRistretto255),\n/* harmony export */ hash_to_ristretto255: () => (/* binding */ hash_to_ristretto255),\n/* harmony export */ x25519: () => (/* binding */ x25519)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/sha512 */ \"./node_modules/@noble/hashes/esm/sha512.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/edwards.js */ \"./node_modules/@noble/curves/esm/abstract/edwards.js\");\n/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ \"./node_modules/@noble/curves/esm/abstract/hash-to-curve.js\");\n/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./abstract/montgomery.js */ \"./node_modules/@noble/curves/esm/abstract/montgomery.js\");\n/* harmony import */ var _abstract_curve_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./abstract/curve.js */ \"./node_modules/@noble/curves/esm/abstract/curve.js\");\n/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\n\n\n\n\nconst ED25519_P = BigInt('57896044618658097711785492504343953926634992332820282019728792003956564819949');\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _5n = BigInt(5), _8n = BigInt(8);\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b4, _1n, P) * x) % P; // x^31\n const b10 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b5, _5n, P) * b5) % P;\n const b20 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b10, _10n, P) * b10) % P;\n const b40 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b20, _20n, P) * b20) % P;\n const b80 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b40, _40n, P) * b40) % P;\n const b160 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b80, _80n, P) * b80) % P;\n const b240 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b160, _80n, P) * b80) % P;\n const b250 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// sqrt(u/v)\nfunction uvRatio(u, v) {\n const P = ED25519_P;\n const v3 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * v * v, P); // v³\n const v7 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))\n x = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n// Just in case\nconst ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\nconst Fp = /* @__PURE__ */ (() => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(ED25519_P, undefined, true))();\nconst ed25519Defaults = /* @__PURE__ */ (() => ({\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field 𝔽p over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: _8n,\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/√v\n uvRatio,\n}))();\n/**\n * ed25519 curve with EdDSA signatures.\n * @example\n * import { ed25519 } from '@noble/curves/ed25519';\n * const priv = ed25519.utils.randomPrivateKey();\n * const pub = ed25519.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = ed25519.sign(msg, priv);\n * ed25519.verify(sig, msg, pub); // Default mode: follows ZIP215\n * ed25519.verify(sig, msg, pub, { zip215: false }); // RFC8032 / FIPS 186-5\n */\nconst ed25519 = /* @__PURE__ */ (() => (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)(ed25519Defaults))();\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.concatBytes)((0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nconst ed25519ctx = /* @__PURE__ */ (() => (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)({\n ...ed25519Defaults,\n domain: ed25519_domain,\n}))();\nconst ed25519ph = /* @__PURE__ */ (() => (0,_abstract_edwards_js__WEBPACK_IMPORTED_MODULE_3__.twistedEdwards)(Object.assign({}, ed25519Defaults, {\n domain: ed25519_domain,\n prehash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n})))();\n/**\n * ECDH using curve25519 aka x25519.\n * @example\n * import { x25519 } from '@noble/curves/ed25519';\n * const priv = 'a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4';\n * const pub = 'e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c';\n * x25519.getSharedSecret(priv, pub) === x25519.scalarMult(priv, pub); // aliases\n * x25519.getPublicKey(priv) === x25519.scalarMultBase(priv);\n * x25519.getPublicKey(x25519.utils.randomPrivateKey());\n */\nconst x25519 = /* @__PURE__ */ (() => (0,_abstract_montgomery_js__WEBPACK_IMPORTED_MODULE_4__.montgomery)({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x) => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes: _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.randomBytes,\n}))();\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nfunction edwardsToMontgomeryPub(edwardsPub) {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nconst edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nfunction edwardsToMontgomeryPriv(edwardsPriv) {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\nconst ELL2_C1 = /* @__PURE__ */ (() => (Fp.ORDER + _3n) / _8n)(); // 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (Fp.ORDER - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.FpSqrtEven)(Fp, Fp.neg(BigInt(486664))))(); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\nconst htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(ed25519.ExtendedPoint, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512,\n}))();\nconst hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nconst encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\nfunction assertRstPoint(other) {\n if (!(other instanceof RistPoint))\n throw new Error('RistrettoPoint expected');\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// Calculates 1/√(number)\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes) => ed25519.CURVE.Fp.create((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToNumberLE)(bytes) & MAX_255B);\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!(0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint {\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(ep) {\n this.ep = ep;\n }\n static fromAffine(ap) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex) {\n hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n hex = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.ensureBytes)('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!(0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.equalBytes)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32), hex) || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))\n throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t, P) || y === _0n)\n throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n static msm(points, scalars) {\n const Fn = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(ed25519.CURVE.n, ed25519.CURVE.nBitLength);\n return (0,_abstract_curve_js__WEBPACK_IMPORTED_MODULE_7__.pippenger)(RistPoint, Fn, points, scalars);\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes() {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D; // 7\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(x * zInv, P))\n y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.isNegativeLE)(s, P))\n s = mod(-s);\n return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.numberToBytesLE)(s, 32); // 11\n }\n toHex() {\n return (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_6__.bytesToHex)(this.toRawBytes());\n }\n toString() {\n return this.toHex();\n }\n // Compare one point to another.\n equals(other) {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n add(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n subtract(other) {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return new RistPoint(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return new RistPoint(this.ep.double());\n }\n negate() {\n return new RistPoint(this.ep.negate());\n }\n}\nconst RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE)\n RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO)\n RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nconst hashToRistretto255 = (msg, options) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_2__.utf8ToBytes)(d) : d;\n const uniform_bytes = (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.expand_message_xmd)(msg, DST, 64, _noble_hashes_sha512__WEBPACK_IMPORTED_MODULE_1__.sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nconst hash_to_ristretto255 = hashToRistretto255; // legacy\n//# sourceMappingURL=ed25519.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/ed25519.js?"); /***/ }), @@ -8730,7 +12810,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),\n/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),\n/* harmony export */ schnorr: () => (/* binding */ schnorr),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/@noble/hashes/esm/sha256.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/weierstrass.js */ \"./node_modules/@noble/curves/esm/abstract/weierstrass.js\");\n/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ \"./node_modules/@noble/curves/esm/abstract/hash-to-curve.js\");\n/* harmony import */ var _shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_shortw_utils.js */ \"./node_modules/@noble/curves/esm/_shortw_utils.js\");\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\n\n\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b3, _3n, P) * b3) % P;\n const b9 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b6, _3n, P) * b3) % P;\n const b11 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b9, _2n, P) * b2) % P;\n const b22 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b11, _11n, P) * b11) % P;\n const b44 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b22, _22n, P) * b22) % P;\n const b88 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b44, _44n, P) * b44) % P;\n const b176 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b88, _88n, P) * b88) % P;\n const b220 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b176, _44n, P) * b44) % P;\n const b223 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b220, _3n, P) * b3) % P;\n const t1 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b223, _23n, P) * b22) % P;\n const t2 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t1, _6n, P) * b2) % P;\n const root = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\nconst secp256k1 = (0,_shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__.createCurve)({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(k - c1 * a1 - c2 * a2, n);\n let k2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE)(n, 32);\nconst modP = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1P);\nconst modN = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n if (!fe(x))\n throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__.randomBytes)(32)) {\n const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('signature', signature, 64);\n const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);\n const pub = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('publicKey', publicKey, 32);\n try {\n const P = lift_x((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r))\n return false;\n const s = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE)(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\nconst schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE,\n bytesToNumberBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE,\n taggedHash,\n mod: _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.isogenyMap)(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__.mapToCurveSimpleSWU)(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256,\n}))();\nconst hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nconst encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/secp256k1.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ encodeToCurve: () => (/* binding */ encodeToCurve),\n/* harmony export */ hashToCurve: () => (/* binding */ hashToCurve),\n/* harmony export */ schnorr: () => (/* binding */ schnorr),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/@noble/hashes/esm/sha256.js\");\n/* harmony import */ var _noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @noble/hashes/utils */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_shortw_utils.js */ \"./node_modules/@noble/curves/esm/_shortw_utils.js\");\n/* harmony import */ var _abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./abstract/hash-to-curve.js */ \"./node_modules/@noble/curves/esm/abstract/hash-to-curve.js\");\n/* harmony import */ var _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstract/modular.js */ \"./node_modules/@noble/curves/esm/abstract/modular.js\");\n/* harmony import */ var _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./abstract/utils.js */ \"./node_modules/@noble/curves/esm/abstract/utils.js\");\n/* harmony import */ var _abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./abstract/weierstrass.js */ \"./node_modules/@noble/curves/esm/abstract/weierstrass.js\");\n/**\n * NIST secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Seems to be rigid (not backdoored)\n * [as per discussion](https://bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975).\n *\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * [See explanation](https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n\n\n\n\n\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b3, _3n, P) * b3) % P;\n const b9 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b6, _3n, P) * b3) % P;\n const b11 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b9, _2n, P) * b2) % P;\n const b22 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b11, _11n, P) * b11) % P;\n const b44 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b22, _22n, P) * b22) % P;\n const b88 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b44, _44n, P) * b44) % P;\n const b176 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b88, _88n, P) * b88) % P;\n const b220 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b176, _44n, P) * b44) % P;\n const b223 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b220, _3n, P) * b3) % P;\n const t1 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(b223, _23n, P) * b22) % P;\n const t2 = ((0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t1, _6n, P) * b2) % P;\n const root = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.pow2)(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.Field)(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n/**\n * secp256k1 short weierstrass curve and ECDSA signatures over it.\n *\n * @example\n * import { secp256k1 } from '@noble/curves/secp256k1';\n *\n * const priv = secp256k1.utils.randomPrivateKey();\n * const pub = secp256k1.getPublicKey(priv);\n * const msg = new Uint8Array(32).fill(1); // message hash (not message) in ecdsa\n * const sig = secp256k1.sign(msg, priv); // `{prehash: true}` option is available\n * const isValid = secp256k1.verify(sig, msg, pub) === true;\n */\nconst secp256k1 = (0,_shortw_utils_js__WEBPACK_IMPORTED_MODULE_1__.createCurve)({\n a: BigInt(0), // equation params: a, b\n b: BigInt(7),\n Fp: Fpk1, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n endo: {\n // Endomorphism, see above\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(k - c1 * a1 - c2 * a2, n);\n let k2 = (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)((0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.concatBytes)(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE)(n, 32);\nconst modP = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1P);\nconst modN = (x) => (0,_abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod)(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.aInRange)('x', x, _1n, secp256k1P); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\nconst num = _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE;\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = (0,_noble_hashes_utils__WEBPACK_IMPORTED_MODULE_4__.randomBytes)(32)) {\n const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ num(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(num(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('signature', signature, 64);\n const m = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('message', message);\n const pub = (0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.ensureBytes)('publicKey', publicKey, 32);\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!(0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.inRange)(r, _1n, secp256k1P))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!(0,_abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.inRange)(s, _1n, secp256k1N))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\n/**\n * Schnorr signatures over secp256k1.\n * https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n * @example\n * import { schnorr } from '@noble/curves/secp256k1';\n * const priv = schnorr.utils.randomPrivateKey();\n * const pub = schnorr.getPublicKey(priv);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, priv);\n * const isValid = schnorr.verify(sig, msg, pub);\n */\nconst schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.numberToBytesBE,\n bytesToNumberBE: _abstract_utils_js__WEBPACK_IMPORTED_MODULE_3__.bytesToNumberBE,\n taggedHash,\n mod: _abstract_modular_js__WEBPACK_IMPORTED_MODULE_0__.mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.isogenyMap)(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => (0,_abstract_weierstrass_js__WEBPACK_IMPORTED_MODULE_6__.mapToCurveSimpleSWU)(Fpk1, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => (0,_abstract_hash_to_curve_js__WEBPACK_IMPORTED_MODULE_5__.createHasher)(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256,\n}))();\n/** secp256k1 hash-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nconst hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\n/** secp256k1 encode-to-curve from [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). */\nconst encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/curves/esm/secp256k1.js?"); /***/ }), @@ -8752,7 +12832,7 @@ eval("var crypto__WEBPACK_IMPORTED_MODULE_0___namespace_cache;\n__webpack_requir /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bool: () => (/* binding */ bool),\n/* harmony export */ bytes: () => (/* binding */ bytes),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ exists: () => (/* binding */ exists),\n/* harmony export */ hash: () => (/* binding */ hash),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ number: () => (/* binding */ number),\n/* harmony export */ output: () => (/* binding */ output)\n/* harmony export */ });\nfunction number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nconst assert = { number, bool, bytes, hash, exists, output };\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (assert);\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_assert.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ abytes: () => (/* binding */ abytes),\n/* harmony export */ aexists: () => (/* binding */ aexists),\n/* harmony export */ ahash: () => (/* binding */ ahash),\n/* harmony export */ anumber: () => (/* binding */ anumber),\n/* harmony export */ aoutput: () => (/* binding */ aoutput)\n/* harmony export */ });\n/**\n * Assertion helpers\n * @module\n */\nfunction anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n// copied from utils\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_assert.js?"); /***/ }), @@ -8763,7 +12843,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Chi: () => (/* binding */ Chi),\n/* harmony export */ HashMD: () => (/* binding */ HashMD),\n/* harmony export */ Maj: () => (/* binding */ Maj)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nclass HashMD extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(this.buffer);\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n const { view, buffer, blockLen } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.output)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_md.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Chi: () => (/* binding */ Chi),\n/* harmony export */ HashMD: () => (/* binding */ HashMD),\n/* harmony export */ Maj: () => (/* binding */ Maj),\n/* harmony export */ setBigUint64: () => (/* binding */ setBigUint64)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n/**\n * Merkle-Damgard hash utils.\n * @module\n */\n/**\n * Polyfill for Safari 14\n */\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n/**\n * Choice: a ? b : c\n */\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n/**\n * Majority function, true if any two inputs is true\n */\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nclass HashMD extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(this.buffer);\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.aexists)(this);\n const { view, buffer, blockLen } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.aexists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.aoutput)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_md.js?"); /***/ }), @@ -8774,7 +12854,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ add: () => (/* binding */ add),\n/* harmony export */ add3H: () => (/* binding */ add3H),\n/* harmony export */ add3L: () => (/* binding */ add3L),\n/* harmony export */ add4H: () => (/* binding */ add4H),\n/* harmony export */ add4L: () => (/* binding */ add4L),\n/* harmony export */ add5H: () => (/* binding */ add5H),\n/* harmony export */ add5L: () => (/* binding */ add5L),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ fromBig: () => (/* binding */ fromBig),\n/* harmony export */ rotlBH: () => (/* binding */ rotlBH),\n/* harmony export */ rotlBL: () => (/* binding */ rotlBL),\n/* harmony export */ rotlSH: () => (/* binding */ rotlSH),\n/* harmony export */ rotlSL: () => (/* binding */ rotlSL),\n/* harmony export */ rotr32H: () => (/* binding */ rotr32H),\n/* harmony export */ rotr32L: () => (/* binding */ rotr32L),\n/* harmony export */ rotrBH: () => (/* binding */ rotrBH),\n/* harmony export */ rotrBL: () => (/* binding */ rotrBL),\n/* harmony export */ rotrSH: () => (/* binding */ rotrSH),\n/* harmony export */ rotrSL: () => (/* binding */ rotrSL),\n/* harmony export */ shrSH: () => (/* binding */ shrSH),\n/* harmony export */ shrSL: () => (/* binding */ shrSL),\n/* harmony export */ split: () => (/* binding */ split),\n/* harmony export */ toBig: () => (/* binding */ toBig)\n/* harmony export */ });\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\n\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (u64);\n//# sourceMappingURL=_u64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_u64.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ add: () => (/* binding */ add),\n/* harmony export */ add3H: () => (/* binding */ add3H),\n/* harmony export */ add3L: () => (/* binding */ add3L),\n/* harmony export */ add4H: () => (/* binding */ add4H),\n/* harmony export */ add4L: () => (/* binding */ add4L),\n/* harmony export */ add5H: () => (/* binding */ add5H),\n/* harmony export */ add5L: () => (/* binding */ add5L),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ fromBig: () => (/* binding */ fromBig),\n/* harmony export */ rotlBH: () => (/* binding */ rotlBH),\n/* harmony export */ rotlBL: () => (/* binding */ rotlBL),\n/* harmony export */ rotlSH: () => (/* binding */ rotlSH),\n/* harmony export */ rotlSL: () => (/* binding */ rotlSL),\n/* harmony export */ rotr32H: () => (/* binding */ rotr32H),\n/* harmony export */ rotr32L: () => (/* binding */ rotr32L),\n/* harmony export */ rotrBH: () => (/* binding */ rotrBH),\n/* harmony export */ rotrBL: () => (/* binding */ rotrBL),\n/* harmony export */ rotrSH: () => (/* binding */ rotrSH),\n/* harmony export */ rotrSL: () => (/* binding */ rotrSL),\n/* harmony export */ shrSH: () => (/* binding */ shrSH),\n/* harmony export */ shrSL: () => (/* binding */ shrSL),\n/* harmony export */ split: () => (/* binding */ split),\n/* harmony export */ toBig: () => (/* binding */ toBig)\n/* harmony export */ });\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n/**\n * BigUint64Array is too slow as per 2024, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\n\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (u64);\n//# sourceMappingURL=_u64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/_u64.js?"); /***/ }), @@ -8796,7 +12876,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ expand: () => (/* binding */ expand),\n/* harmony export */ extract: () => (/* binding */ extract),\n/* harmony export */ hkdf: () => (/* binding */ hkdf)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _hmac_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hmac.js */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n\n\n\n// HKDF (RFC 5869)\n// https://soatok.blog/2021/11/17/understanding-hkdf/\n/**\n * HKDF-Extract(IKM, salt) -> PRK\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash\n * @param ikm\n * @param salt\n * @returns\n */\nfunction extract(hash, ikm, salt) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.hash)(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros\n return (0,_hmac_js__WEBPACK_IMPORTED_MODULE_1__.hmac)(hash, (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.toBytes)(salt), (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.toBytes)(ikm));\n}\n// HKDF-Expand(PRK, info, L) -> OKM\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n/**\n * HKDF-expand from the spec.\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in octets\n */\nfunction expand(hash, prk, info, length = 32) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.hash)(hash);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.number)(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = _hmac_js__WEBPACK_IMPORTED_MODULE_1__.hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information\n * @param length - length of output keying material in octets\n */\nconst hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/hkdf.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ expand: () => (/* binding */ expand),\n/* harmony export */ extract: () => (/* binding */ extract),\n/* harmony export */ hkdf: () => (/* binding */ hkdf)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n/* harmony import */ var _hmac_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hmac.js */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n\n\n\n/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See https://soatok.blog/2021/11/17/understanding-hkdf/.\n * @module\n */\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n */\nfunction extract(hash, ikm, salt) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.ahash)(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined)\n salt = new Uint8Array(hash.outputLen);\n return (0,_hmac_js__WEBPACK_IMPORTED_MODULE_1__.hmac)(hash, (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.toBytes)(salt), (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.toBytes)(ikm));\n}\nconst HKDF_COUNTER = /* @__PURE__ */ new Uint8Array([0]);\nconst EMPTY_BUFFER = /* @__PURE__ */ new Uint8Array();\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n */\nfunction expand(hash, prk, info, length = 32) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.ahash)(hash);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.anumber)(length);\n if (length > 255 * hash.outputLen)\n throw new Error('Length should be <= 255*HashLen');\n const blocks = Math.ceil(length / hash.outputLen);\n if (info === undefined)\n info = EMPTY_BUFFER;\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * hash.outputLen);\n // Re-use HMAC instance between blocks\n const HMAC = _hmac_js__WEBPACK_IMPORTED_MODULE_1__.hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, hash.outputLen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n T.fill(0);\n HKDF_COUNTER.fill(0);\n return okm.slice(0, length);\n}\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes\n * @example\n * import { hkdf } from '@noble/hashes/hkdf';\n * import { sha256 } from '@noble/hashes/sha2';\n * import { randomBytes } from '@noble/hashes/utils';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = 'application-key';\n * const hk1 = hkdf(sha256, inputKey, salt, info, 32);\n */\nconst hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);\n//# sourceMappingURL=hkdf.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/hkdf.js?"); /***/ }), @@ -8807,7 +12887,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ HMAC: () => (/* binding */ HMAC),\n/* harmony export */ hmac: () => (/* binding */ hmac)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n// HMAC (RFC 2104)\nclass HMAC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.hash)(hash);\n const key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.bytes)(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nconst hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/hmac.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ HMAC: () => (/* binding */ HMAC),\n/* harmony export */ hmac: () => (/* binding */ hmac)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nclass HMAC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.ahash)(hash);\n const key = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.aexists)(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.aexists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.abytes)(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nconst hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/hmac.js?"); /***/ }), @@ -8818,7 +12898,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ pbkdf2: () => (/* binding */ pbkdf2),\n/* harmony export */ pbkdf2Async: () => (/* binding */ pbkdf2Async)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _hmac_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hmac.js */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.hash)(hash);\n const opts = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.number)(c);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.number)(dkLen);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.number)(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(_password);\n const salt = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = _hmac_js__WEBPACK_IMPORTED_MODULE_2__.hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nfunction pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\nasync function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.asyncLoop)(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/pbkdf2.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ pbkdf2: () => (/* binding */ pbkdf2),\n/* harmony export */ pbkdf2Async: () => (/* binding */ pbkdf2Async)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _hmac_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hmac.js */ \"./node_modules/@noble/hashes/esm/hmac.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.ahash)(hash);\n const opts = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.checkOpts)({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.anumber)(c);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.anumber)(dkLen);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.anumber)(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(_password);\n const salt = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = _hmac_js__WEBPACK_IMPORTED_MODULE_2__.hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n * @example\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: 2 ** 18 });\n */\nfunction pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function. Async version.\n * @example\n * await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n */\nasync function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.createView)(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.asyncLoop)(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/pbkdf2.js?"); /***/ }), @@ -8829,7 +12909,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha224: () => (/* binding */ sha224),\n/* harmony export */ sha256: () => (/* binding */ sha256)\n/* harmony export */ });\n/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_md.js */ \"./node_modules/@noble/hashes/esm/_md.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _md_js__WEBPACK_IMPORTED_MODULE_0__.HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);\n const T1 = (H + sigma1 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);\n const T2 = (sigma0 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Maj)(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nconst sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());\nconst sha224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/sha256.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ SHA256: () => (/* binding */ SHA256),\n/* harmony export */ sha224: () => (/* binding */ sha224),\n/* harmony export */ sha256: () => (/* binding */ sha256)\n/* harmony export */ });\n/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_md.js */ \"./node_modules/@noble/hashes/esm/_md.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n/**\n * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.\n *\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n *\n * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\n/** Round constants: first 32 bits of fractional parts of the cube roots of the first 64 primes 2..311). */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Initial state: first 32 bits of fractional parts of the square roots of the first 8 primes 2..19. */\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n/**\n * Temporary buffer, not used to store anything between runs.\n * Named this way because it matches specification.\n */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _md_js__WEBPACK_IMPORTED_MODULE_0__.HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);\n const T1 = (H + sigma1 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);\n const T2 = (sigma0 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Maj)(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n/**\n * Constants taken from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf.\n */\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/** SHA2-256 hash function */\nconst sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());\n/** SHA2-224 hash function */\nconst sha224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/sha256.js?"); /***/ }), @@ -8840,7 +12920,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ SHA512: () => (/* binding */ SHA512),\n/* harmony export */ sha384: () => (/* binding */ sha384),\n/* harmony export */ sha512: () => (/* binding */ sha512),\n/* harmony export */ sha512_224: () => (/* binding */ sha512_224),\n/* harmony export */ sha512_256: () => (/* binding */ sha512_256)\n/* harmony export */ });\n/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_md.js */ \"./node_modules/@noble/hashes/esm/_md.js\");\n/* harmony import */ var _u64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_u64.js */ \"./node_modules/@noble/hashes/esm/_u64.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nclass SHA512 extends _md_js__WEBPACK_IMPORTED_MODULE_1__.HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSH(W15h, W15l, 7);\n const s0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSH(W2h, W2l, 6);\n const s1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Eh, El, 41);\n const sigma1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Ah, Al, 39);\n const sigma0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add3L(T1l, sigma0l, MAJl);\n Ah = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nconst sha512 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512());\nconst sha512_224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_224());\nconst sha512_256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_256());\nconst sha384 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA384());\n//# sourceMappingURL=sha512.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/sha512.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ SHA384: () => (/* binding */ SHA384),\n/* harmony export */ SHA512: () => (/* binding */ SHA512),\n/* harmony export */ SHA512_224: () => (/* binding */ SHA512_224),\n/* harmony export */ SHA512_256: () => (/* binding */ SHA512_256),\n/* harmony export */ sha384: () => (/* binding */ sha384),\n/* harmony export */ sha512: () => (/* binding */ sha512),\n/* harmony export */ sha512_224: () => (/* binding */ sha512_224),\n/* harmony export */ sha512_256: () => (/* binding */ sha512_256)\n/* harmony export */ });\n/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_md.js */ \"./node_modules/@noble/hashes/esm/_md.js\");\n/* harmony import */ var _u64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_u64.js */ \"./node_modules/@noble/hashes/esm/_u64.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n/**\n * SHA2-512 a.k.a. sha512 and sha384. It is slower than sha256 in js because u64 operations are slow.\n *\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf).\n * @module\n */\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nclass SHA512 extends _md_js__WEBPACK_IMPORTED_MODULE_1__.HashMD {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSH(W15h, W15l, 7);\n const s0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W15h, W15l, 1) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W15h, W15l, 8) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSH(W2h, W2l, 6);\n const s1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(W2h, W2l, 19) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(W2h, W2l, 61) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Eh, El, 41);\n const sigma1l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Eh, El, 14) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Eh, El, 18) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSH(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBH(Ah, Al, 39);\n const sigma0l = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrSL(Ah, Al, 28) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Ah, Al, 34) ^ _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add3L(T1l, sigma0l, MAJl);\n Ah = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = _u64_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\n/** SHA2-512 hash function. */\nconst sha512 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512());\n/** SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks. */\nconst sha512_224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_224());\n/** SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks. */\nconst sha512_256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA512_256());\n/** SHA2-384 hash function. */\nconst sha384 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.wrapConstructor)(() => new SHA384());\n//# sourceMappingURL=sha512.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/sha512.js?"); /***/ }), @@ -8851,7 +12931,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hash: () => (/* binding */ Hash),\n/* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),\n/* harmony export */ byteSwap: () => (/* binding */ byteSwap),\n/* harmony export */ byteSwap32: () => (/* binding */ byteSwap32),\n/* harmony export */ byteSwapIfBE: () => (/* binding */ byteSwapIfBE),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ checkOpts: () => (/* binding */ checkOpts),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createView: () => (/* binding */ createView),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ isLE: () => (/* binding */ isLE),\n/* harmony export */ nextTick: () => (/* binding */ nextTick),\n/* harmony export */ randomBytes: () => (/* binding */ randomBytes),\n/* harmony export */ rotl: () => (/* binding */ rotl),\n/* harmony export */ rotr: () => (/* binding */ rotr),\n/* harmony export */ toBytes: () => (/* binding */ toBytes),\n/* harmony export */ u32: () => (/* binding */ u32),\n/* harmony export */ u8: () => (/* binding */ u8),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),\n/* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts),\n/* harmony export */ wrapXOFConstructorWithOpts: () => (/* binding */ wrapXOFConstructorWithOpts)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/@noble/hashes/esm/crypto.js\");\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\n\n\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nconst isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nconst byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nfunction byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues === 'function') {\n return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/utils.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hash: () => (/* binding */ Hash),\n/* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),\n/* harmony export */ byteSwap: () => (/* binding */ byteSwap),\n/* harmony export */ byteSwap32: () => (/* binding */ byteSwap32),\n/* harmony export */ byteSwapIfBE: () => (/* binding */ byteSwapIfBE),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ checkOpts: () => (/* binding */ checkOpts),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createView: () => (/* binding */ createView),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ isLE: () => (/* binding */ isLE),\n/* harmony export */ nextTick: () => (/* binding */ nextTick),\n/* harmony export */ randomBytes: () => (/* binding */ randomBytes),\n/* harmony export */ rotl: () => (/* binding */ rotl),\n/* harmony export */ rotr: () => (/* binding */ rotr),\n/* harmony export */ toBytes: () => (/* binding */ toBytes),\n/* harmony export */ u32: () => (/* binding */ u32),\n/* harmony export */ u8: () => (/* binding */ u8),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),\n/* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts),\n/* harmony export */ wrapXOFConstructorWithOpts: () => (/* binding */ wrapXOFConstructorWithOpts)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/@noble/hashes/esm/crypto.js\");\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/@noble/hashes/esm/_assert.js\");\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\n\n\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n/** The rotate right (circular right shift) operation for uint32 */\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n/** The rotate left (circular left shift) operation for uint32 */\nconst rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nconst isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n/** Conditionally byte swap if on a big-endian platform */\nconst byteSwapIfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nfunction byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Convert JS string to byte array.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.abytes)(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues === 'function') {\n return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.randomBytes === 'function') {\n return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.randomBytes(bytesLength);\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@noble/hashes/esm/utils.js?"); /***/ }), @@ -8866,6 +12946,17 @@ eval("var crypto__WEBPACK_IMPORTED_MODULE_0___namespace_cache;\n__webpack_requir /***/ }), +/***/ "./node_modules/@sindresorhus/fnv1a/index.js": +/*!***************************************************!*\ + !*** ./node_modules/@sindresorhus/fnv1a/index.js ***! + \***************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ fnv1a)\n/* harmony export */ });\n// FNV_PRIMES and FNV_OFFSETS from\n// http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-param\n\nconst FNV_PRIMES = {\n\t32: 16_777_619n,\n\t64: 1_099_511_628_211n,\n\t128: 309_485_009_821_345_068_724_781_371n,\n\t256: 374_144_419_156_711_147_060_143_317_175_368_453_031_918_731_002_211n,\n\t512: 35_835_915_874_844_867_368_919_076_489_095_108_449_946_327_955_754_392_558_399_825_615_420_669_938_882_575_126_094_039_892_345_713_852_759n,\n\t1024: 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573n,\n};\n\nconst FNV_OFFSETS = {\n\t32: 2_166_136_261n,\n\t64: 14_695_981_039_346_656_037n,\n\t128: 144_066_263_297_769_815_596_495_629_667_062_367_629n,\n\t256: 100_029_257_958_052_580_907_070_968_620_625_704_837_092_796_014_241_193_945_225_284_501_741_471_925_557n,\n\t512: 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785n,\n\t1024: 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915n,\n};\n\nconst cachedEncoder = new globalThis.TextEncoder();\n\nfunction fnv1aUint8Array(uint8Array, size) {\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\n\t// eslint-disable-next-line unicorn/no-for-loop -- This is a performance-sensitive loop\n\tfor (let index = 0; index < uint8Array.length; index++) {\n\t\thash ^= BigInt(uint8Array[index]);\n\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1aEncodeInto(string, size, utf8Buffer) {\n\tif (utf8Buffer.length === 0) {\n\t\tthrow new Error('The `utf8Buffer` option must have a length greater than zero');\n\t}\n\n\tconst fnvPrime = FNV_PRIMES[size];\n\tlet hash = FNV_OFFSETS[size];\n\tlet remaining = string;\n\n\twhile (remaining.length > 0) {\n\t\tconst result = cachedEncoder.encodeInto(remaining, utf8Buffer);\n\t\tremaining = remaining.slice(result.read);\n\t\tfor (let index = 0; index < result.written; index++) {\n\t\t\thash ^= BigInt(utf8Buffer[index]);\n\t\t\thash = BigInt.asUintN(size, hash * fnvPrime);\n\t\t}\n\t}\n\n\treturn hash;\n}\n\nfunction fnv1a(value, {size = 32, utf8Buffer} = {}) {\n\tif (!FNV_PRIMES[size]) {\n\t\tthrow new Error('The `size` option must be one of 32, 64, 128, 256, 512, or 1024');\n\t}\n\n\tif (typeof value === 'string') {\n\t\tif (utf8Buffer) {\n\t\t\treturn fnv1aEncodeInto(value, size, utf8Buffer);\n\t\t}\n\n\t\tvalue = cachedEncoder.encode(value);\n\t}\n\n\treturn fnv1aUint8Array(value, size);\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/@sindresorhus/fnv1a/index.js?"); + +/***/ }), + /***/ "./node_modules/@waku/core/dist/index.js": /*!***********************************************!*\ !*** ./node_modules/@waku/core/dist/index.js ***! @@ -9658,6 +13749,787 @@ eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=waku.j /***/ }), +/***/ "./node_modules/@waku/message-hash/dist/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/@waku/message-hash/dist/index.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ messageHash: () => (/* binding */ messageHash),\n/* harmony export */ messageHashStr: () => (/* binding */ messageHashStr)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/@noble/hashes/esm/sha256.js\");\n/* harmony import */ var _waku_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/utils */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/index.js\");\n/* harmony import */ var _waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @waku/utils/bytes */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/bytes/index.js\");\n\n\n\n/**\n * Deterministic Message Hashing as defined in\n * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)\n */\nfunction messageHash(pubsubTopic, message) {\n const pubsubTopicBytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)(pubsubTopic);\n const contentTopicBytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)(message.contentTopic);\n const timestampBytes = tryConvertTimestampToBytes(message.timestamp);\n const bytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__.concat)([\n pubsubTopicBytes,\n message.payload,\n contentTopicBytes,\n message.meta,\n timestampBytes\n ].filter(_waku_utils__WEBPACK_IMPORTED_MODULE_0__.isDefined));\n return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_2__.sha256)(bytes);\n}\nfunction tryConvertTimestampToBytes(timestamp) {\n if (!timestamp) {\n return;\n }\n let bigIntTimestamp;\n if (typeof timestamp === \"bigint\") {\n bigIntTimestamp = timestamp;\n }\n else {\n bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;\n }\n return (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__.numberToBytes)(bigIntTimestamp);\n}\nfunction messageHashStr(pubsubTopic, message) {\n const hash = messageHash(pubsubTopic, message);\n const hashStr = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_1__.bytesToHex)(hash);\n return hashStr;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/dist/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/connection_manager.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/connection_manager.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ EConnectionStateEvents: () => (/* binding */ EConnectionStateEvents),\n/* harmony export */ EPeersByDiscoveryEvents: () => (/* binding */ EPeersByDiscoveryEvents),\n/* harmony export */ Tags: () => (/* binding */ Tags)\n/* harmony export */ });\nvar Tags;\n(function (Tags) {\n Tags[\"BOOTSTRAP\"] = \"bootstrap\";\n Tags[\"PEER_EXCHANGE\"] = \"peer-exchange\";\n Tags[\"LOCAL\"] = \"local-peer-cache\";\n})(Tags || (Tags = {}));\nvar EPeersByDiscoveryEvents;\n(function (EPeersByDiscoveryEvents) {\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_BOOTSTRAP\"] = \"peer:discovery:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_DISCOVERY_PEER_EXCHANGE\"] = \"peer:discovery:peer-exchange\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_BOOTSTRAP\"] = \"peer:connected:bootstrap\";\n EPeersByDiscoveryEvents[\"PEER_CONNECT_PEER_EXCHANGE\"] = \"peer:connected:peer-exchange\";\n})(EPeersByDiscoveryEvents || (EPeersByDiscoveryEvents = {}));\nvar EConnectionStateEvents;\n(function (EConnectionStateEvents) {\n EConnectionStateEvents[\"CONNECTION_STATUS\"] = \"waku:connection\";\n})(EConnectionStateEvents || (EConnectionStateEvents = {}));\n//# sourceMappingURL=connection_manager.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/connection_manager.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/constants.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/constants.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_CLUSTER_ID: () => (/* binding */ DEFAULT_CLUSTER_ID),\n/* harmony export */ DefaultNetworkConfig: () => (/* binding */ DefaultNetworkConfig),\n/* harmony export */ DefaultShardInfo: () => (/* binding */ DefaultShardInfo)\n/* harmony export */ });\n/**\n * The default cluster ID for The Waku Network\n */\nconst DEFAULT_CLUSTER_ID = 1;\n/**\n * DefaultShardInfo is default configuration for The Waku Network.\n */\nconst DefaultShardInfo = {\n clusterId: DEFAULT_CLUSTER_ID,\n shards: [0, 1, 2, 3, 4, 5, 6, 7, 8]\n};\nconst DefaultNetworkConfig = DefaultShardInfo;\n//# sourceMappingURL=constants.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/constants.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/dns_discovery.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/dns_discovery.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DNS_DISCOVERY_TAG: () => (/* binding */ DNS_DISCOVERY_TAG)\n/* harmony export */ });\nconst DNS_DISCOVERY_TAG = \"@waku/bootstrap\";\n//# sourceMappingURL=dns_discovery.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/dns_discovery.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/enr.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/enr.js ***! + \***********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=enr.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/enr.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/filter.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/filter.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=filter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/filter.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/health_manager.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/health_manager.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ HealthStatus: () => (/* binding */ HealthStatus)\n/* harmony export */ });\nvar HealthStatus;\n(function (HealthStatus) {\n HealthStatus[\"Unhealthy\"] = \"Unhealthy\";\n HealthStatus[\"MinimallyHealthy\"] = \"MinimallyHealthy\";\n HealthStatus[\"SufficientlyHealthy\"] = \"SufficientlyHealthy\";\n})(HealthStatus || (HealthStatus = {}));\n//# sourceMappingURL=health_manager.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/health_manager.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/index.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/index.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_CLUSTER_ID: () => (/* reexport safe */ _constants_js__WEBPACK_IMPORTED_MODULE_17__.DEFAULT_CLUSTER_ID),\n/* harmony export */ DNS_DISCOVERY_TAG: () => (/* reexport safe */ _dns_discovery_js__WEBPACK_IMPORTED_MODULE_15__.DNS_DISCOVERY_TAG),\n/* harmony export */ DefaultNetworkConfig: () => (/* reexport safe */ _constants_js__WEBPACK_IMPORTED_MODULE_17__.DefaultNetworkConfig),\n/* harmony export */ DefaultShardInfo: () => (/* reexport safe */ _constants_js__WEBPACK_IMPORTED_MODULE_17__.DefaultShardInfo),\n/* harmony export */ EConnectionStateEvents: () => (/* reexport safe */ _connection_manager_js__WEBPACK_IMPORTED_MODULE_9__.EConnectionStateEvents),\n/* harmony export */ EPeersByDiscoveryEvents: () => (/* reexport safe */ _connection_manager_js__WEBPACK_IMPORTED_MODULE_9__.EPeersByDiscoveryEvents),\n/* harmony export */ HealthStatus: () => (/* reexport safe */ _health_manager_js__WEBPACK_IMPORTED_MODULE_19__.HealthStatus),\n/* harmony export */ ProtocolError: () => (/* reexport safe */ _protocols_js__WEBPACK_IMPORTED_MODULE_5__.ProtocolError),\n/* harmony export */ Protocols: () => (/* reexport safe */ _protocols_js__WEBPACK_IMPORTED_MODULE_5__.Protocols),\n/* harmony export */ Tags: () => (/* reexport safe */ _connection_manager_js__WEBPACK_IMPORTED_MODULE_9__.Tags)\n/* harmony export */ });\n/* harmony import */ var _enr_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./enr.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/enr.js\");\n/* harmony import */ var _filter_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./filter.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/filter.js\");\n/* harmony import */ var _light_push_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./light_push.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/light_push.js\");\n/* harmony import */ var _message_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./message.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/message.js\");\n/* harmony import */ var _peer_exchange_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./peer_exchange.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/peer_exchange.js\");\n/* harmony import */ var _protocols_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./protocols.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/protocols.js\");\n/* harmony import */ var _relay_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./relay.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/relay.js\");\n/* harmony import */ var _store_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./store.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/store.js\");\n/* harmony import */ var _waku_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./waku.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/waku.js\");\n/* harmony import */ var _connection_manager_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./connection_manager.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/connection_manager.js\");\n/* harmony import */ var _sender_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./sender.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sender.js\");\n/* harmony import */ var _receiver_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./receiver.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/receiver.js\");\n/* harmony import */ var _misc_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./misc.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/misc.js\");\n/* harmony import */ var _libp2p_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./libp2p.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/libp2p.js\");\n/* harmony import */ var _keep_alive_manager_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./keep_alive_manager.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/keep_alive_manager.js\");\n/* harmony import */ var _dns_discovery_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./dns_discovery.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/dns_discovery.js\");\n/* harmony import */ var _metadata_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./metadata.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/metadata.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/constants.js\");\n/* harmony import */ var _local_storage_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./local_storage.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/local_storage.js\");\n/* harmony import */ var _health_manager_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./health_manager.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/health_manager.js\");\n/* harmony import */ var _sharding_js__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./sharding.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sharding.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/keep_alive_manager.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/keep_alive_manager.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=keep_alive_manager.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/keep_alive_manager.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/libp2p.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/libp2p.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=libp2p.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/libp2p.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/light_push.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/light_push.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=light_push.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/light_push.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/local_storage.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/local_storage.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=local_storage.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/local_storage.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/message.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/message.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=message.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/message.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/metadata.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/metadata.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=metadata.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/metadata.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/misc.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/misc.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=misc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/misc.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/peer_exchange.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/peer_exchange.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=peer_exchange.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/peer_exchange.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/protocols.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/protocols.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ProtocolError: () => (/* binding */ ProtocolError),\n/* harmony export */ Protocols: () => (/* binding */ Protocols)\n/* harmony export */ });\nvar Protocols;\n(function (Protocols) {\n Protocols[\"Relay\"] = \"relay\";\n Protocols[\"Store\"] = \"store\";\n Protocols[\"LightPush\"] = \"lightpush\";\n Protocols[\"Filter\"] = \"filter\";\n})(Protocols || (Protocols = {}));\nvar ProtocolError;\n(function (ProtocolError) {\n /** Could not determine the origin of the fault. Best to check connectivity and try again */\n ProtocolError[\"GENERIC_FAIL\"] = \"Generic error\";\n /**\n * Failure to protobuf encode the message. This is not recoverable and needs\n * further investigation.\n */\n ProtocolError[\"ENCODE_FAILED\"] = \"Failed to encode\";\n /**\n * Failure to protobuf decode the message. May be due to a remote peer issue,\n * ensuring that messages are sent via several peer enable mitigation of this error.\n */\n ProtocolError[\"DECODE_FAILED\"] = \"Failed to decode\";\n /**\n * The message payload is empty, making the message invalid. Ensure that a non-empty\n * payload is set on the outgoing message.\n */\n ProtocolError[\"EMPTY_PAYLOAD\"] = \"Payload is empty\";\n /**\n * The message size is above the maximum message size allowed on the Waku Network.\n * Compressing the message or using an alternative strategy for large messages is recommended.\n */\n ProtocolError[\"SIZE_TOO_BIG\"] = \"Size is too big\";\n /**\n * The PubsubTopic passed to the send function is not configured on the Waku node.\n * Please ensure that the PubsubTopic is used when initializing the Waku node.\n */\n ProtocolError[\"TOPIC_NOT_CONFIGURED\"] = \"Topic not configured\";\n /**\n * The pubsub topic configured on the decoder does not match the pubsub topic setup on the protocol.\n * Ensure that the pubsub topic used for decoder creation is the same as the one used for protocol.\n */\n ProtocolError[\"TOPIC_DECODER_MISMATCH\"] = \"Topic decoder mismatch\";\n /**\n * The topics passed in the decoders do not match each other, or don't exist at all.\n * Ensure that all the pubsub topics used in the decoders are valid and match each other.\n */\n ProtocolError[\"INVALID_DECODER_TOPICS\"] = \"Invalid decoder topics\";\n /**\n * Failure to find a peer with suitable protocols. This may due to a connection issue.\n * Mitigation can be: retrying after a given time period, display connectivity issue\n * to user or listening for `peer:connected:bootstrap` or `peer:connected:peer-exchange`\n * on the connection manager before retrying.\n */\n ProtocolError[\"NO_PEER_AVAILABLE\"] = \"No peer available\";\n /**\n * Failure to find a stream to the peer. This may be because the connection with the peer is not still alive.\n * Mitigation can be: retrying after a given time period, or mitigation for `NO_PEER_AVAILABLE` can be used.\n */\n ProtocolError[\"NO_STREAM_AVAILABLE\"] = \"No stream available\";\n /**\n * The remote peer did not behave as expected. Mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"NO_RESPONSE\"] = \"No response received\";\n /**\n * The remote peer rejected the message. Information provided by the remote peer\n * is logged. Review message validity, or mitigation for `NO_PEER_AVAILABLE`\n * or `DECODE_FAILED` can be used.\n */\n ProtocolError[\"REMOTE_PEER_REJECTED\"] = \"Remote peer rejected\";\n /**\n * The protocol request timed out without a response. This may be due to a connection issue.\n * Mitigation can be: retrying after a given time period\n */\n ProtocolError[\"REQUEST_TIMEOUT\"] = \"Request timeout\";\n /**\n * Missing credentials info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L186\n */\n ProtocolError[\"RLN_IDENTITY_MISSING\"] = \"Identity credentials are not set\";\n /**\n * Membership index missing info message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L188\n */\n ProtocolError[\"RLN_MEMBERSHIP_INDEX\"] = \"Membership index is not set\";\n /**\n * Message limit is missing.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L190\n */\n ProtocolError[\"RLN_LIMIT_MISSING\"] = \"User message limit is not set\";\n /**\n * General proof generation error message.\n * nwaku: https://github.com/waku-org/nwaku/blob/c3cb06ac6c03f0f382d3941ea53b330f6a8dd127/waku/waku_rln_relay/group_manager/group_manager_base.nim#L201C19-L201C42\n */\n ProtocolError[\"RLN_PROOF_GENERATION\"] = \"Proof generation failed\";\n})(ProtocolError || (ProtocolError = {}));\n//# sourceMappingURL=protocols.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/protocols.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/receiver.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/receiver.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=receiver.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/receiver.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/relay.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/relay.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=relay.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/relay.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sender.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sender.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=sender.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sender.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sharding.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sharding.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=sharding.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/sharding.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/store.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/store.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=store.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/store.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/waku.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/waku.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=waku.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/waku.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/bytes/index.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/bytes/index.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ bytesToUtf8: () => (/* binding */ bytesToUtf8),\n/* harmony export */ concat: () => (/* binding */ concat),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ numberToBytes: () => (/* binding */ numberToBytes),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes)\n/* harmony export */ });\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/to-string.js\");\n\n\n/**\n * Convert input to a byte array.\n *\n * Handles both `0x` prefixed and non-prefixed strings.\n */\nfunction hexToBytes(hex) {\n if (typeof hex === \"string\") {\n const _hex = hex.replace(/^0x/i, \"\");\n return (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(_hex.toLowerCase(), \"base16\");\n }\n return hex;\n}\nfunction numberToBytes(value) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n if (typeof value === \"number\") {\n view.setFloat64(0, value, false);\n }\n else {\n view.setBigInt64(0, value, false);\n }\n return new Uint8Array(buffer);\n}\n/**\n * Convert byte array to hex string (no `0x` prefix).\n */\nconst bytesToHex = (bytes) => (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__.toString)(bytes, \"base16\");\n/**\n * Decode byte array to utf-8 string.\n */\nconst bytesToUtf8 = (b) => (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_1__.toString)(b, \"utf8\");\n/**\n * Encode utf-8 string to byte array.\n */\nconst utf8ToBytes = (s) => (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(s, \"utf8\");\n/**\n * Concatenate using Uint8Arrays as `Buffer` has a different behavior with `DataView`\n */\nfunction concat(byteArrays, totalLength) {\n const len = totalLength ?? byteArrays.reduce((acc, curr) => acc + curr.length, 0);\n const res = new Uint8Array(len);\n let offset = 0;\n for (const bytes of byteArrays) {\n res.set(bytes, offset);\n offset += bytes.length;\n }\n return res;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/bytes/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/delay.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/delay.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ delay: () => (/* binding */ delay)\n/* harmony export */ });\nasync function delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n//# sourceMappingURL=delay.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/delay.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/group_by.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/group_by.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ groupByContentTopic: () => (/* binding */ groupByContentTopic)\n/* harmony export */ });\nfunction groupByContentTopic(values) {\n const groupedDecoders = new Map();\n values.forEach((value) => {\n let decs = groupedDecoders.get(value.contentTopic);\n if (!decs) {\n groupedDecoders.set(value.contentTopic, []);\n decs = groupedDecoders.get(value.contentTopic);\n }\n decs.push(value);\n });\n return groupedDecoders;\n}\n//# sourceMappingURL=group_by.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/group_by.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/index.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/index.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ contentTopicToPubsubTopic: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.contentTopicToPubsubTopic),\n/* harmony export */ contentTopicToShardIndex: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.contentTopicToShardIndex),\n/* harmony export */ contentTopicsByPubsubTopic: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.contentTopicsByPubsubTopic),\n/* harmony export */ decodeRelayShard: () => (/* reexport safe */ _relay_shard_codec_js__WEBPACK_IMPORTED_MODULE_7__.decodeRelayShard),\n/* harmony export */ delay: () => (/* reexport safe */ _delay_js__WEBPACK_IMPORTED_MODULE_8__.delay),\n/* harmony export */ derivePubsubTopicsFromNetworkConfig: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.derivePubsubTopicsFromNetworkConfig),\n/* harmony export */ determinePubsubTopic: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.determinePubsubTopic),\n/* harmony export */ encodeRelayShard: () => (/* reexport safe */ _relay_shard_codec_js__WEBPACK_IMPORTED_MODULE_7__.encodeRelayShard),\n/* harmony export */ ensurePubsubTopicIsConfigured: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.ensurePubsubTopicIsConfigured),\n/* harmony export */ ensureShardingConfigured: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.ensureShardingConfigured),\n/* harmony export */ ensureValidContentTopic: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.ensureValidContentTopic),\n/* harmony export */ getPseudoRandomSubset: () => (/* reexport safe */ _random_subset_js__WEBPACK_IMPORTED_MODULE_1__.getPseudoRandomSubset),\n/* harmony export */ getWsMultiaddrFromMultiaddrs: () => (/* binding */ getWsMultiaddrFromMultiaddrs),\n/* harmony export */ groupByContentTopic: () => (/* reexport safe */ _group_by_js__WEBPACK_IMPORTED_MODULE_2__.groupByContentTopic),\n/* harmony export */ isAutoSharding: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.isAutoSharding),\n/* harmony export */ isDefined: () => (/* reexport safe */ _is_defined_js__WEBPACK_IMPORTED_MODULE_0__.isDefined),\n/* harmony export */ isMessageSizeUnderCap: () => (/* reexport safe */ _is_size_valid_js__WEBPACK_IMPORTED_MODULE_4__.isMessageSizeUnderCap),\n/* harmony export */ isStaticSharding: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.isStaticSharding),\n/* harmony export */ isWireSizeUnderCap: () => (/* reexport safe */ _is_size_valid_js__WEBPACK_IMPORTED_MODULE_4__.isWireSizeUnderCap),\n/* harmony export */ pubsubTopicToSingleShardInfo: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.pubsubTopicToSingleShardInfo),\n/* harmony export */ pubsubTopicsToShardInfo: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.pubsubTopicsToShardInfo),\n/* harmony export */ pushOrInitMapSet: () => (/* reexport safe */ _push_or_init_map_js__WEBPACK_IMPORTED_MODULE_6__.pushOrInitMapSet),\n/* harmony export */ removeItemFromArray: () => (/* binding */ removeItemFromArray),\n/* harmony export */ shardInfoToPubsubTopics: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.shardInfoToPubsubTopics),\n/* harmony export */ singleShardInfoToPubsubTopic: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.singleShardInfoToPubsubTopic),\n/* harmony export */ singleShardInfosToShardInfo: () => (/* reexport safe */ _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__.singleShardInfosToShardInfo),\n/* harmony export */ toAsyncIterator: () => (/* reexport safe */ _to_async_iterator_js__WEBPACK_IMPORTED_MODULE_3__.toAsyncIterator)\n/* harmony export */ });\n/* harmony import */ var _is_defined_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./is_defined.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_defined.js\");\n/* harmony import */ var _random_subset_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./random_subset.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/random_subset.js\");\n/* harmony import */ var _group_by_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./group_by.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/group_by.js\");\n/* harmony import */ var _to_async_iterator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./to_async_iterator.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/to_async_iterator.js\");\n/* harmony import */ var _is_size_valid_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./is_size_valid.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_size_valid.js\");\n/* harmony import */ var _sharding_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./sharding/index.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/index.js\");\n/* harmony import */ var _push_or_init_map_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./push_or_init_map.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/push_or_init_map.js\");\n/* harmony import */ var _relay_shard_codec_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./relay_shard_codec.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/relay_shard_codec.js\");\n/* harmony import */ var _delay_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./delay.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/delay.js\");\n\n\n\n\n\n\n\n\n\nfunction removeItemFromArray(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n }\n return arr;\n}\nfunction getWsMultiaddrFromMultiaddrs(addresses) {\n const wsMultiaddr = addresses.find((addr) => addr.toString().includes(\"ws\") || addr.toString().includes(\"wss\"));\n if (!wsMultiaddr) {\n throw new Error(\"No ws multiaddr found in the given addresses\");\n }\n return wsMultiaddr;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_defined.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_defined.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isDefined: () => (/* binding */ isDefined)\n/* harmony export */ });\nfunction isDefined(value) {\n return Boolean(value);\n}\n//# sourceMappingURL=is_defined.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_defined.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_size_valid.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_size_valid.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isMessageSizeUnderCap: () => (/* binding */ isMessageSizeUnderCap),\n/* harmony export */ isWireSizeUnderCap: () => (/* binding */ isWireSizeUnderCap)\n/* harmony export */ });\nconst MB = 1024 ** 2;\nconst SIZE_CAP_IN_MB = 1;\n/**\n * Return whether the size of the message is under the upper limit for the network.\n * This performs a protobuf encoding! If you have access to the fully encoded message,\n * use {@link isSizeUnderCapBuf} instead.\n * @param message\n * @param encoder\n */\nasync function isMessageSizeUnderCap(encoder, message) {\n const buf = await encoder.toWire(message);\n if (!buf)\n return false;\n return isWireSizeUnderCap(buf);\n}\nconst isWireSizeUnderCap = (buf) => buf.length / MB <= SIZE_CAP_IN_MB;\n//# sourceMappingURL=is_size_valid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/is_size_valid.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/push_or_init_map.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/push_or_init_map.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ pushOrInitMapSet: () => (/* binding */ pushOrInitMapSet)\n/* harmony export */ });\nfunction pushOrInitMapSet(map, key, newValue) {\n let arr = map.get(key);\n if (typeof arr === \"undefined\") {\n map.set(key, new Set());\n arr = map.get(key);\n }\n arr.add(newValue);\n}\n//# sourceMappingURL=push_or_init_map.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/push_or_init_map.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/random_subset.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/random_subset.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getPseudoRandomSubset: () => (/* binding */ getPseudoRandomSubset)\n/* harmony export */ });\n/**\n * Return pseudo random subset of the input.\n */\nfunction getPseudoRandomSubset(values, wantedNumber) {\n if (values.length <= wantedNumber || values.length <= 1) {\n return values;\n }\n return shuffle(values).slice(0, wantedNumber);\n}\nfunction shuffle(arr) {\n if (arr.length <= 1) {\n return arr;\n }\n const randInt = () => {\n return Math.floor(Math.random() * Math.floor(arr.length));\n };\n for (let i = 0; i < arr.length; i++) {\n const j = randInt();\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n return arr;\n}\n//# sourceMappingURL=random_subset.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/random_subset.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/relay_shard_codec.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/relay_shard_codec.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decodeRelayShard: () => (/* binding */ decodeRelayShard),\n/* harmony export */ encodeRelayShard: () => (/* binding */ encodeRelayShard)\n/* harmony export */ });\nconst decodeRelayShard = (bytes) => {\n // explicitly converting to Uint8Array to avoid Buffer\n // https://github.com/libp2p/js-libp2p/issues/2146\n bytes = new Uint8Array(bytes);\n if (bytes.length < 3)\n throw new Error(\"Insufficient data\");\n const view = new DataView(bytes.buffer);\n const clusterId = view.getUint16(0);\n const shards = [];\n if (bytes.length === 130) {\n // rsv format (Bit Vector)\n for (let i = 0; i < 1024; i++) {\n const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (i % 8);\n if (view.getUint8(byteIndex) & (1 << bitIndex)) {\n shards.push(i);\n }\n }\n }\n else {\n // rs format (Index List)\n const numIndices = view.getUint8(2);\n for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {\n if (offset + 1 >= bytes.length)\n throw new Error(\"Unexpected end of data\");\n shards.push(view.getUint16(offset));\n }\n }\n return { clusterId, shards };\n};\nconst encodeRelayShard = (shardInfo) => {\n const { clusterId, shards } = shardInfo;\n const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;\n const buffer = new ArrayBuffer(totalLength);\n const view = new DataView(buffer);\n view.setUint16(0, clusterId);\n if (shards.length >= 64) {\n // rsv format (Bit Vector)\n for (const index of shards) {\n const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field\n const bitIndex = 7 - (index % 8);\n view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));\n }\n }\n else {\n // rs format (Index List)\n view.setUint8(2, shards.length);\n for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {\n view.setUint16(offset, shards[i]);\n }\n }\n return new Uint8Array(buffer);\n};\n//# sourceMappingURL=relay_shard_codec.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/relay_shard_codec.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/index.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/index.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ contentTopicToPubsubTopic: () => (/* binding */ contentTopicToPubsubTopic),\n/* harmony export */ contentTopicToShardIndex: () => (/* binding */ contentTopicToShardIndex),\n/* harmony export */ contentTopicsByPubsubTopic: () => (/* binding */ contentTopicsByPubsubTopic),\n/* harmony export */ derivePubsubTopicsFromNetworkConfig: () => (/* binding */ derivePubsubTopicsFromNetworkConfig),\n/* harmony export */ determinePubsubTopic: () => (/* binding */ determinePubsubTopic),\n/* harmony export */ ensurePubsubTopicIsConfigured: () => (/* binding */ ensurePubsubTopicIsConfigured),\n/* harmony export */ ensureShardingConfigured: () => (/* binding */ ensureShardingConfigured),\n/* harmony export */ ensureValidContentTopic: () => (/* binding */ ensureValidContentTopic),\n/* harmony export */ isAutoSharding: () => (/* reexport safe */ _type_guards_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSharding),\n/* harmony export */ isStaticSharding: () => (/* reexport safe */ _type_guards_js__WEBPACK_IMPORTED_MODULE_2__.isStaticSharding),\n/* harmony export */ pubsubTopicToSingleShardInfo: () => (/* binding */ pubsubTopicToSingleShardInfo),\n/* harmony export */ pubsubTopicsToShardInfo: () => (/* binding */ pubsubTopicsToShardInfo),\n/* harmony export */ shardInfoToPubsubTopics: () => (/* binding */ shardInfoToPubsubTopics),\n/* harmony export */ singleShardInfoToPubsubTopic: () => (/* binding */ singleShardInfoToPubsubTopic),\n/* harmony export */ singleShardInfosToShardInfo: () => (/* binding */ singleShardInfosToShardInfo)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/@noble/hashes/esm/sha256.js\");\n/* harmony import */ var _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/interfaces */ \"./node_modules/@waku/message-hash/node_modules/@waku/interfaces/dist/index.js\");\n/* harmony import */ var _bytes_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../bytes/index.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/bytes/index.js\");\n/* harmony import */ var _type_guards_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./type_guards.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/type_guards.js\");\n\n\n\n\n\nfunction derivePubsubTopicsFromNetworkConfig(networkConfig) {\n if ((0,_type_guards_js__WEBPACK_IMPORTED_MODULE_2__.isStaticSharding)(networkConfig)) {\n if (networkConfig.shards.length === 0) {\n throw new Error(\"Invalid shards configuration: please provide at least one shard\");\n }\n return shardInfoToPubsubTopics(networkConfig);\n }\n else if ((0,_type_guards_js__WEBPACK_IMPORTED_MODULE_2__.isAutoSharding)(networkConfig)) {\n if (networkConfig.contentTopics.length === 0) {\n throw new Error(\"Invalid content topics configuration: please provide at least one content topic\");\n }\n return networkConfig.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, networkConfig.clusterId));\n }\n else {\n throw new Error(\"Unknown shard config. Please use ShardInfo or ContentTopicInfo\");\n }\n}\nconst singleShardInfoToPubsubTopic = (shardInfo) => {\n if (shardInfo.shard === undefined)\n throw new Error(\"Invalid shard\");\n return `/waku/2/rs/${shardInfo.clusterId ?? _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID}/${shardInfo.shard}`;\n};\nconst singleShardInfosToShardInfo = (singleShardInfos) => {\n if (singleShardInfos.length === 0)\n throw new Error(\"Invalid shard\");\n const clusterIds = singleShardInfos.map((shardInfo) => shardInfo.clusterId);\n if (new Set(clusterIds).size !== 1) {\n throw new Error(\"Passed shard infos have different clusterIds\");\n }\n const shards = singleShardInfos\n .map((shardInfo) => shardInfo.shard)\n .filter((shard) => shard !== undefined);\n return {\n clusterId: singleShardInfos[0].clusterId,\n shards\n };\n};\nconst shardInfoToPubsubTopics = (shardInfo) => {\n if (\"contentTopics\" in shardInfo && shardInfo.contentTopics) {\n // Autosharding: explicitly defined content topics\n return Array.from(new Set(shardInfo.contentTopics.map((contentTopic) => contentTopicToPubsubTopic(contentTopic, shardInfo.clusterId))));\n }\n else if (\"shards\" in shardInfo) {\n // Static sharding\n if (shardInfo.shards === undefined)\n throw new Error(\"Invalid shard\");\n return Array.from(new Set(shardInfo.shards.map((index) => `/waku/2/rs/${shardInfo.clusterId ?? _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID}/${index}`)));\n }\n else if (\"application\" in shardInfo && \"version\" in shardInfo) {\n // Autosharding: single shard from application and version\n return [\n contentTopicToPubsubTopic(`/${shardInfo.application}/${shardInfo.version}/default/default`, shardInfo.clusterId)\n ];\n }\n else {\n throw new Error(\"Missing required configuration in shard parameters\");\n }\n};\nconst pubsubTopicToSingleShardInfo = (pubsubTopics) => {\n const parts = pubsubTopics.split(\"/\");\n if (parts.length != 6 ||\n parts[1] !== \"waku\" ||\n parts[2] !== \"2\" ||\n parts[3] !== \"rs\")\n throw new Error(\"Invalid pubsub topic\");\n const clusterId = parseInt(parts[4]);\n const shard = parseInt(parts[5]);\n if (isNaN(clusterId) || isNaN(shard))\n throw new Error(\"Invalid clusterId or shard\");\n return {\n clusterId,\n shard\n };\n};\nconst pubsubTopicsToShardInfo = (pubsubTopics) => {\n const shardInfoSet = new Set();\n const clusterIds = new Set();\n for (const topic of pubsubTopics) {\n const { clusterId, shard } = pubsubTopicToSingleShardInfo(topic);\n shardInfoSet.add(`${clusterId}:${shard}`);\n clusterIds.add(clusterId);\n }\n if (shardInfoSet.size === 0) {\n throw new Error(\"No valid pubsub topics provided\");\n }\n if (clusterIds.size > 1) {\n throw new Error(\"Pubsub topics from multiple cluster IDs are not supported\");\n }\n const clusterId = clusterIds.values().next().value;\n const shards = Array.from(shardInfoSet).map((info) => parseInt(info.split(\":\")[1]));\n return {\n clusterId,\n shards\n };\n};\n//TODO: move part of BaseProtocol instead of utils\n// return `ProtocolError.TOPIC_NOT_CONFIGURED` instead of throwing\nfunction ensurePubsubTopicIsConfigured(pubsubTopic, configuredTopics) {\n if (!configuredTopics.includes(pubsubTopic)) {\n throw new Error(`Pubsub topic ${pubsubTopic} has not been configured on this instance. Configured topics are: ${configuredTopics}. Please update your configuration by passing in the topic during Waku node instantiation.`);\n }\n}\n/**\n * Given a string, will throw an error if it is not formatted as a valid content topic for autosharding based on https://rfc.vac.dev/spec/51/\n * @param contentTopic String to validate\n * @returns Object with each content topic field as an attribute\n */\nfunction ensureValidContentTopic(contentTopic) {\n const parts = contentTopic.split(\"/\");\n if (parts.length < 5 || parts.length > 6) {\n throw Error(\"Content topic format is invalid\");\n }\n // Validate generation field if present\n let generation = 0;\n if (parts.length == 6) {\n generation = parseInt(parts[1]);\n if (isNaN(generation)) {\n throw new Error(\"Invalid generation field in content topic\");\n }\n if (generation > 0) {\n throw new Error(\"Generation greater than 0 is not supported\");\n }\n }\n // Validate remaining fields\n const fields = parts.splice(-4);\n // Validate application field\n if (fields[0].length == 0) {\n throw new Error(\"Application field cannot be empty\");\n }\n // Validate version field\n if (fields[1].length == 0) {\n throw new Error(\"Version field cannot be empty\");\n }\n // Validate topic name field\n if (fields[2].length == 0) {\n throw new Error(\"Topic name field cannot be empty\");\n }\n // Validate encoding field\n if (fields[3].length == 0) {\n throw new Error(\"Encoding field cannot be empty\");\n }\n return {\n generation,\n application: fields[0],\n version: fields[1],\n topicName: fields[2],\n encoding: fields[3]\n };\n}\n/**\n * Given a string, determines which autoshard index to use for its pubsub topic.\n * Based on the algorithm described in the RFC: https://rfc.vac.dev/spec/51//#algorithm\n */\nfunction contentTopicToShardIndex(contentTopic, networkShards = 8) {\n const { application, version } = ensureValidContentTopic(contentTopic);\n const digest = (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_3__.sha256)((0,_bytes_index_js__WEBPACK_IMPORTED_MODULE_1__.concat)([(0,_bytes_index_js__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)(application), (0,_bytes_index_js__WEBPACK_IMPORTED_MODULE_1__.utf8ToBytes)(version)]));\n const dataview = new DataView(digest.buffer.slice(-8));\n return Number(dataview.getBigUint64(0, false) % BigInt(networkShards));\n}\nfunction contentTopicToPubsubTopic(contentTopic, clusterId = _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID, networkShards = 8) {\n if (!contentTopic) {\n throw Error(\"Content topic must be specified\");\n }\n const shardIndex = contentTopicToShardIndex(contentTopic, networkShards);\n return `/waku/2/rs/${clusterId}/${shardIndex}`;\n}\n/**\n * Given an array of content topics, groups them together by their Pubsub topic as derived using the algorithm for autosharding.\n * If any of the content topics are not properly formatted, the function will throw an error.\n */\nfunction contentTopicsByPubsubTopic(contentTopics, clusterId = _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID, networkShards = 8) {\n const groupedContentTopics = new Map();\n for (const contentTopic of contentTopics) {\n const pubsubTopic = contentTopicToPubsubTopic(contentTopic, clusterId, networkShards);\n let topics = groupedContentTopics.get(pubsubTopic);\n if (!topics) {\n groupedContentTopics.set(pubsubTopic, []);\n topics = groupedContentTopics.get(pubsubTopic);\n }\n topics.push(contentTopic);\n }\n return groupedContentTopics;\n}\n/**\n * Used when creating encoders/decoders to determine which pubsub topic to use\n */\nfunction determinePubsubTopic(contentTopic, \n// TODO: make it accept ShardInfo https://github.com/waku-org/js-waku/issues/2086\npubsubTopicShardInfo) {\n if (typeof pubsubTopicShardInfo == \"string\") {\n return pubsubTopicShardInfo;\n }\n return pubsubTopicShardInfo?.shard !== undefined\n ? singleShardInfoToPubsubTopic(pubsubTopicShardInfo)\n : contentTopicToPubsubTopic(contentTopic, pubsubTopicShardInfo?.clusterId ?? _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID);\n}\n/**\n * Validates sharding configuration and sets defaults where possible.\n * @returns Validated sharding parameters, with any missing values set to defaults\n */\nconst ensureShardingConfigured = (networkConfig) => {\n const clusterId = networkConfig.clusterId ?? _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_CLUSTER_ID;\n const shards = \"shards\" in networkConfig ? networkConfig.shards : [];\n const contentTopics = \"contentTopics\" in networkConfig ? networkConfig.contentTopics : [];\n const isShardsConfigured = shards && shards.length > 0;\n const isContentTopicsConfigured = contentTopics && contentTopics.length > 0;\n if (isShardsConfigured) {\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics: shardInfoToPubsubTopics({ clusterId, shards })\n };\n }\n if (isContentTopicsConfigured) {\n const pubsubTopics = Array.from(new Set(contentTopics.map((topic) => contentTopicToPubsubTopic(topic, clusterId))));\n const shards = Array.from(new Set(contentTopics.map((topic) => contentTopicToShardIndex(topic))));\n return {\n shardInfo: { clusterId, shards },\n pubsubTopics\n };\n }\n throw new Error(\"Missing minimum required configuration options for static sharding or autosharding.\");\n};\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/type_guards.js": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/type_guards.js ***! + \******************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isAutoSharding: () => (/* binding */ isAutoSharding),\n/* harmony export */ isStaticSharding: () => (/* binding */ isStaticSharding)\n/* harmony export */ });\nfunction isStaticSharding(config) {\n return (\"clusterId\" in config && \"shards\" in config && !(\"contentTopics\" in config));\n}\nfunction isAutoSharding(config) {\n return \"contentTopics\" in config;\n}\n//# sourceMappingURL=type_guards.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/sharding/type_guards.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/to_async_iterator.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/to_async_iterator.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ toAsyncIterator: () => (/* binding */ toAsyncIterator)\n/* harmony export */ });\nconst FRAME_RATE = 60;\n/**\n * Function that transforms IReceiver subscription to iterable stream of data.\n * @param receiver - object that allows to be subscribed to;\n * @param decoder - parameter to be passed to receiver for subscription;\n * @param options - options for receiver for subscription;\n * @param iteratorOptions - optional configuration for iterator;\n * @returns iterator and stop function to terminate it.\n */\nasync function toAsyncIterator(receiver, decoder, iteratorOptions) {\n const iteratorDelay = iteratorOptions?.iteratorDelay ?? FRAME_RATE;\n const messages = [];\n let unsubscribe;\n unsubscribe = await receiver.subscribeWithUnsubscribe(decoder, (message) => {\n messages.push(message);\n });\n const isWithTimeout = Number.isInteger(iteratorOptions?.timeoutMs);\n const timeoutMs = iteratorOptions?.timeoutMs ?? 0;\n const startTime = Date.now();\n async function* iterator() {\n while (true) {\n if (isWithTimeout && Date.now() - startTime >= timeoutMs) {\n return;\n }\n await wait(iteratorDelay);\n const message = messages.shift();\n if (!unsubscribe && messages.length === 0) {\n return message;\n }\n if (!message && unsubscribe) {\n continue;\n }\n yield message;\n }\n }\n return {\n iterator: iterator(),\n async stop() {\n if (unsubscribe) {\n await unsubscribe();\n unsubscribe = undefined;\n }\n }\n };\n}\nfunction wait(ms) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n//# sourceMappingURL=to_async_iterator.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/to_async_iterator.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/index.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/index.js ***! + \********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Logger: () => (/* reexport safe */ _logger_index_js__WEBPACK_IMPORTED_MODULE_1__.Logger),\n/* harmony export */ contentTopicToPubsubTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.contentTopicToPubsubTopic),\n/* harmony export */ contentTopicToShardIndex: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.contentTopicToShardIndex),\n/* harmony export */ contentTopicsByPubsubTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.contentTopicsByPubsubTopic),\n/* harmony export */ decodeRelayShard: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.decodeRelayShard),\n/* harmony export */ delay: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.delay),\n/* harmony export */ derivePubsubTopicsFromNetworkConfig: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.derivePubsubTopicsFromNetworkConfig),\n/* harmony export */ determinePubsubTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.determinePubsubTopic),\n/* harmony export */ encodeRelayShard: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.encodeRelayShard),\n/* harmony export */ ensurePubsubTopicIsConfigured: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.ensurePubsubTopicIsConfigured),\n/* harmony export */ ensureShardingConfigured: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.ensureShardingConfigured),\n/* harmony export */ ensureValidContentTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.ensureValidContentTopic),\n/* harmony export */ getPseudoRandomSubset: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.getPseudoRandomSubset),\n/* harmony export */ getWsMultiaddrFromMultiaddrs: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.getWsMultiaddrFromMultiaddrs),\n/* harmony export */ groupByContentTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.groupByContentTopic),\n/* harmony export */ isAutoSharding: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.isAutoSharding),\n/* harmony export */ isDefined: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.isDefined),\n/* harmony export */ isMessageSizeUnderCap: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.isMessageSizeUnderCap),\n/* harmony export */ isStaticSharding: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.isStaticSharding),\n/* harmony export */ isWireSizeUnderCap: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.isWireSizeUnderCap),\n/* harmony export */ pubsubTopicToSingleShardInfo: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.pubsubTopicToSingleShardInfo),\n/* harmony export */ pubsubTopicsToShardInfo: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.pubsubTopicsToShardInfo),\n/* harmony export */ pushOrInitMapSet: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.pushOrInitMapSet),\n/* harmony export */ removeItemFromArray: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.removeItemFromArray),\n/* harmony export */ shardInfoToPubsubTopics: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.shardInfoToPubsubTopics),\n/* harmony export */ singleShardInfoToPubsubTopic: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.singleShardInfoToPubsubTopic),\n/* harmony export */ singleShardInfosToShardInfo: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.singleShardInfosToShardInfo),\n/* harmony export */ toAsyncIterator: () => (/* reexport safe */ _common_index_js__WEBPACK_IMPORTED_MODULE_0__.toAsyncIterator)\n/* harmony export */ });\n/* harmony import */ var _common_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./common/index.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/common/index.js\");\n/* harmony import */ var _logger_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger/index.js */ \"./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/logger/index.js\");\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/logger/index.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/logger/index.js ***! + \***************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Logger: () => (/* binding */ Logger)\n/* harmony export */ });\n/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\");\n\nconst APP_NAME = \"waku\";\nclass Logger {\n _info;\n _warn;\n _error;\n static createDebugNamespace(level, prefix) {\n return prefix ? `${APP_NAME}:${level}:${prefix}` : `${APP_NAME}:${level}`;\n }\n constructor(prefix) {\n this._info = debug__WEBPACK_IMPORTED_MODULE_0__(Logger.createDebugNamespace(\"info\", prefix));\n this._warn = debug__WEBPACK_IMPORTED_MODULE_0__(Logger.createDebugNamespace(\"warn\", prefix));\n this._error = debug__WEBPACK_IMPORTED_MODULE_0__(Logger.createDebugNamespace(\"error\", prefix));\n }\n get info() {\n return this._info;\n }\n get warn() {\n return this._warn;\n }\n get error() {\n return this._error;\n }\n log(level, ...args) {\n const logger = this[level];\n logger(...args);\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/@waku/utils/dist/logger/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base10.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base10.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base10: () => (/* binding */ base10)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base10 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: '9',\n name: 'base10',\n alphabet: '0123456789'\n});\n//# sourceMappingURL=base10.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base10.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base16.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base16.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base16: () => (/* binding */ base16),\n/* harmony export */ base16upper: () => (/* binding */ base16upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base16 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'f',\n name: 'base16',\n alphabet: '0123456789abcdef',\n bitsPerChar: 4\n});\nconst base16upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'F',\n name: 'base16upper',\n alphabet: '0123456789ABCDEF',\n bitsPerChar: 4\n});\n//# sourceMappingURL=base16.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base16.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base2.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base2.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base2: () => (/* binding */ base2)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base2 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '0',\n name: 'base2',\n alphabet: '01',\n bitsPerChar: 1\n});\n//# sourceMappingURL=base2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base2.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base256emoji.js": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base256emoji.js ***! + \**************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base256emoji.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base32.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base32.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base32: () => (/* binding */ base32),\n/* harmony export */ base32hex: () => (/* binding */ base32hex),\n/* harmony export */ base32hexpad: () => (/* binding */ base32hexpad),\n/* harmony export */ base32hexpadupper: () => (/* binding */ base32hexpadupper),\n/* harmony export */ base32hexupper: () => (/* binding */ base32hexupper),\n/* harmony export */ base32pad: () => (/* binding */ base32pad),\n/* harmony export */ base32padupper: () => (/* binding */ base32padupper),\n/* harmony export */ base32upper: () => (/* binding */ base32upper),\n/* harmony export */ base32z: () => (/* binding */ base32z)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base32 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n});\nconst base32upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n});\nconst base32pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n});\nconst base32padupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n});\nconst base32hex = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n});\nconst base32hexupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n});\nconst base32hexpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n});\nconst base32hexpadupper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n});\nconst base32z = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n});\n//# sourceMappingURL=base32.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base32.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base36.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base36.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base36: () => (/* binding */ base36),\n/* harmony export */ base36upper: () => (/* binding */ base36upper)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base36 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'k',\n name: 'base36',\n alphabet: '0123456789abcdefghijklmnopqrstuvwxyz'\n});\nconst base36upper = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n prefix: 'K',\n name: 'base36upper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base36.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base36.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base58.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base58.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base58btc: () => (/* binding */ base58btc),\n/* harmony export */ base58flickr: () => (/* binding */ base58flickr)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base58btc = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n});\nconst base58flickr = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.baseX)({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n});\n//# sourceMappingURL=base58.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base58.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base64.js": +/*!********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base64.js ***! + \********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base64: () => (/* binding */ base64),\n/* harmony export */ base64pad: () => (/* binding */ base64pad),\n/* harmony export */ base64url: () => (/* binding */ base64url),\n/* harmony export */ base64urlpad: () => (/* binding */ base64urlpad)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base64 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n});\nconst base64pad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n});\nconst base64url = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n});\nconst base64urlpad = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n});\n//# sourceMappingURL=base64.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base64.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base8.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base8.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base8: () => (/* binding */ base8)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst base8 = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.rfc4648)({\n prefix: '7',\n name: 'base8',\n alphabet: '01234567',\n bitsPerChar: 3\n});\n//# sourceMappingURL=base8.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base8.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/identity.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/identity.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base.js\");\n\n\nconst identity = (0,_base_js__WEBPACK_IMPORTED_MODULE_1__.from)({\n prefix: '\\x00',\n name: 'identity',\n encode: (buf) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.toString)(buf),\n decode: (str) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.fromString)(str)\n});\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/interface.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/interface.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// Base encoders / decoders just base encode / decode between binary and\n// textual representation. They are unaware of multibase.\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/basics.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/basics.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.CID),\n/* harmony export */ bases: () => (/* binding */ bases),\n/* harmony export */ bytes: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.bytes),\n/* harmony export */ codecs: () => (/* binding */ codecs),\n/* harmony export */ digest: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.digest),\n/* harmony export */ hasher: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.hasher),\n/* harmony export */ hashes: () => (/* binding */ hashes),\n/* harmony export */ varint: () => (/* reexport safe */ _index_js__WEBPACK_IMPORTED_MODULE_14__.varint)\n/* harmony export */ });\n/* harmony import */ var _bases_base10_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base10.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base10.js\");\n/* harmony import */ var _bases_base16_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base16.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base16.js\");\n/* harmony import */ var _bases_base2_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base2.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base2.js\");\n/* harmony import */ var _bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bases/base256emoji.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base256emoji.js\");\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bases_base64_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./bases/base64.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _bases_base8_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./bases/base8.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base8.js\");\n/* harmony import */ var _bases_identity_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./bases/identity.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/identity.js\");\n/* harmony import */ var _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./codecs/json.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/json.js\");\n/* harmony import */ var _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./codecs/raw.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/raw.js\");\n/* harmony import */ var _hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./hashes/identity.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var _hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./hashes/sha2.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/index.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst bases = { ..._bases_identity_js__WEBPACK_IMPORTED_MODULE_9__, ..._bases_base2_js__WEBPACK_IMPORTED_MODULE_2__, ..._bases_base8_js__WEBPACK_IMPORTED_MODULE_8__, ..._bases_base10_js__WEBPACK_IMPORTED_MODULE_0__, ..._bases_base16_js__WEBPACK_IMPORTED_MODULE_1__, ..._bases_base32_js__WEBPACK_IMPORTED_MODULE_4__, ..._bases_base36_js__WEBPACK_IMPORTED_MODULE_5__, ..._bases_base58_js__WEBPACK_IMPORTED_MODULE_6__, ..._bases_base64_js__WEBPACK_IMPORTED_MODULE_7__, ..._bases_base256emoji_js__WEBPACK_IMPORTED_MODULE_3__ };\nconst hashes = { ..._hashes_sha2_js__WEBPACK_IMPORTED_MODULE_13__, ..._hashes_identity_js__WEBPACK_IMPORTED_MODULE_12__ };\nconst codecs = { raw: _codecs_raw_js__WEBPACK_IMPORTED_MODULE_11__, json: _codecs_json_js__WEBPACK_IMPORTED_MODULE_10__ };\n\n//# sourceMappingURL=basics.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/basics.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/block/interface.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/block/interface.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/block/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ coerce: () => (/* binding */ coerce),\n/* harmony export */ empty: () => (/* binding */ empty),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ fromHex: () => (/* binding */ fromHex),\n/* harmony export */ fromString: () => (/* binding */ fromString),\n/* harmony export */ isBinary: () => (/* binding */ isBinary),\n/* harmony export */ toHex: () => (/* binding */ toHex),\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\nconst empty = new Uint8Array(0);\nfunction toHex(d) {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '');\n}\nfunction fromHex(hex) {\n const hexes = hex.match(/../g);\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty;\n}\nfunction equals(aa, bb) {\n if (aa === bb)\n return true;\n if (aa.byteLength !== bb.byteLength) {\n return false;\n }\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false;\n }\n }\n return true;\n}\nfunction coerce(o) {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array')\n return o;\n if (o instanceof ArrayBuffer)\n return new Uint8Array(o);\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);\n }\n throw new Error('Unknown type, must be binary type');\n}\nfunction isBinary(o) {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o);\n}\nfunction fromString(str) {\n return new TextEncoder().encode(str);\n}\nfunction toString(b) {\n return new TextDecoder().decode(b);\n}\n//# sourceMappingURL=bytes.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/cid.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/cid.js ***! + \***********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/cid.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/interface.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/interface.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/json.js": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/json.js ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\nconst name = 'json';\nconst code = 0x0200;\nfunction encode(node) {\n return textEncoder.encode(JSON.stringify(node));\n}\nfunction decode(data) {\n return JSON.parse(textDecoder.decode(data));\n}\n//# sourceMappingURL=json.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/json.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/raw.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/raw.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ code: () => (/* binding */ code),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encode: () => (/* binding */ encode),\n/* harmony export */ name: () => (/* binding */ name)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n\nconst name = 'raw';\nconst code = 0x55;\nfunction encode(node) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(node);\n}\nfunction decode(data) {\n return (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(data);\n}\n//# sourceMappingURL=raw.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/raw.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/hasher.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/hasher.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hasher: () => (/* binding */ Hasher),\n/* harmony export */ from: () => (/* binding */ from)\n/* harmony export */ });\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js\");\n\nfunction from({ name, code, encode }) {\n return new Hasher(name, code, encode);\n}\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nclass Hasher {\n name;\n code;\n encode;\n constructor(name, code, encode) {\n this.name = name;\n this.code = code;\n this.encode = encode;\n }\n digest(input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input);\n return result instanceof Uint8Array\n ? _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => _digest_js__WEBPACK_IMPORTED_MODULE_0__.create(this.code, digest));\n }\n else {\n throw Error('Unknown type, must be binary type');\n /* c8 ignore next 1 */\n }\n }\n}\n//# sourceMappingURL=hasher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/hasher.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/identity.js": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/identity.js ***! + \***********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ identity: () => (/* binding */ identity)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _digest_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./digest.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js\");\n\n\nconst code = 0x0;\nconst name = 'identity';\nconst encode = _bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce;\nfunction digest(input) {\n return _digest_js__WEBPACK_IMPORTED_MODULE_1__.create(code, encode(input));\n}\nconst identity = { code, name, encode, digest };\n//# sourceMappingURL=identity.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/identity.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/interface.js": +/*!************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/interface.js ***! + \************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n// # Multihash\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/sha2-browser.js": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/sha2-browser.js ***! + \***************************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha256: () => (/* binding */ sha256),\n/* harmony export */ sha512: () => (/* binding */ sha512)\n/* harmony export */ });\n/* harmony import */ var _hasher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./hasher.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* global crypto */\n\nfunction sha(name) {\n return async (data) => new Uint8Array(await crypto.subtle.digest(name, data));\n}\nconst sha256 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n});\nconst sha512 = (0,_hasher_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n});\n//# sourceMappingURL=sha2-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/sha2-browser.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/index.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/index.js ***! + \*************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* reexport safe */ _cid_js__WEBPACK_IMPORTED_MODULE_1__.CID),\n/* harmony export */ bytes: () => (/* reexport module object */ _bytes_js__WEBPACK_IMPORTED_MODULE_0__),\n/* harmony export */ digest: () => (/* reexport module object */ _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ hasher: () => (/* reexport module object */ _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__),\n/* harmony export */ varint: () => (/* reexport module object */ _varint_js__WEBPACK_IMPORTED_MODULE_4__)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _cid_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cid.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _hashes_hasher_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/hasher.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/hasher.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/interface.js\");\n/**\n * @packageDocumentation\n *\n * This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.\n *\n * This library provides implementations for most basics and many others can be found in linked repositories.\n *\n * ```TypeScript\n * import { CID } from 'multiformats/cid'\n * import * as json from 'multiformats/codecs/json'\n * import { sha256 } from 'multiformats/hashes/sha2'\n *\n * const bytes = json.encode({ hello: 'world' })\n *\n * const hash = await sha256.digest(bytes)\n * const cid = CID.create(1, json.code, hash)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Creating Blocks\n *\n * ```TypeScript\n * import * as Block from 'multiformats/block'\n * import * as codec from '@ipld/dag-cbor'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * const value = { hello: 'world' }\n *\n * // encode a block\n * let block = await Block.encode({ value, codec, hasher })\n *\n * block.value // { hello: 'world' }\n * block.bytes // Uint8Array\n * block.cid // CID() w/ sha2-256 hash address and dag-cbor codec\n *\n * // you can also decode blocks from their binary state\n * block = await Block.decode({ bytes: block.bytes, codec, hasher })\n *\n * // if you have the cid you can also verify the hash on decode\n * block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })\n * ```\n *\n * ## Multibase Encoders / Decoders / Codecs\n *\n * CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:\n *\n * ```TypeScript\n * import { base64 } from \"multiformats/bases/base64\"\n * cid.toString(base64.encoder)\n * //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'\n * ```\n *\n * Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:\n *\n * ```TypeScript\n * CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * Dual of multibase encoder & decoder is defined as multibase codec and it exposes\n * them as `encoder` and `decoder` properties. For added convenience codecs also\n * implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be\n * used as either or both:\n *\n * ```TypeScript\n * cid.toString(base64)\n * CID.parse(cid.toString(base64), base64)\n * ```\n *\n * **Note:** CID implementation comes bundled with `base32` and `base58btc`\n * multibase codecs so that CIDs can be base serialized to (version specific)\n * default base encoding and parsed without having to supply base encoders/decoders:\n *\n * ```TypeScript\n * const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')\n * v1.toString()\n * //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'\n *\n * const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n * v0.toString()\n * //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'\n * v0.toV1().toString()\n * //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'\n * ```\n *\n * ## Multicodec Encoders / Decoders / Codecs\n *\n * This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).\n * Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.\n * Here is an example implementation of JSON `BlockCodec`.\n *\n * ```TypeScript\n * export const { name, code, encode, decode } = {\n * name: 'json',\n * code: 0x0200,\n * encode: json => new TextEncoder().encode(JSON.stringify(json)),\n * decode: bytes => JSON.parse(new TextDecoder().decode(bytes))\n * }\n * ```\n *\n * ## Multihash Hashers\n *\n * This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:\n *\n * ```TypeScript\n * import * as hasher from 'multiformats/hashes/hasher'\n *\n * const sha256 = hasher.from({\n * // As per multiformats table\n * // https://github.com/multiformats/multicodec/blob/master/table.csv#L9\n * name: 'sha2-256',\n * code: 0x12,\n *\n * encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())\n * })\n *\n * const hash = await sha256.digest(json.encode({ hello: 'world' }))\n * CID.create(1, json.code, hash)\n *\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Traversal\n *\n * This library contains higher-order functions for traversing graphs of data easily.\n *\n * `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.\n *\n * ```TypeScript\n * import { walk } from 'multiformats/traversal'\n * import * as Block from 'multiformats/block'\n * import * as codec from 'multiformats/codecs/json'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * // build a DAG (a single block for this simple example)\n * const value = { hello: 'world' }\n * const block = await Block.encode({ value, codec, hasher })\n * const { cid } = block\n * console.log(cid)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n *\n * // create a loader function that also collects CIDs of blocks in\n * // their traversal order\n * const load = (cid, blocks) => async (cid) => {\n * // fetch a block using its cid\n * // e.g.: const block = await fetchBlockByCID(cid)\n * blocks.push(cid)\n * return block\n * }\n *\n * // collect blocks in this DAG starting from the root `cid`\n * const blocks = []\n * await walk({ cid, load: load(cid, blocks) })\n *\n * console.log(blocks)\n * //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]\n * ```\n *\n * ## Legacy interface\n *\n * [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an\n * [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.\n *\n * ## Implementations\n *\n * By default, no base encodings (other than base32 & base58btc), hash functions,\n * or codec implementations are exposed by `multiformats`, you need to\n * import the ones you need yourself.\n *\n * ### Multibase codecs\n *\n * | bases | import | repo |\n * | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |\n * | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n *\n * Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.\n *\n * ### Multihash hashers\n *\n * | hashes | import | repo |\n * | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |\n * | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |\n * | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |\n * | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |\n * | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |\n * | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |\n *\n * ### IPLD codecs (multicodec)\n *\n * | codec | import | repo |\n * | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |\n * | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |\n * | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |\n * | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |\n * | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |\n */\n\n\n\n\n\n// This way TS will also expose all the types from module\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/interface.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/interface.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _bases_interface_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/bases/interface.js\");\n/* harmony import */ var _hashes_interface_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./hashes/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/hashes/interface.js\");\n/* harmony import */ var _codecs_interface_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/codecs/interface.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/link/interface.js\");\n/* harmony import */ var _block_interface_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./block/interface.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/block/interface.js\");\n\n\n\n\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/link/interface.js": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/link/interface.js ***! + \**********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */\n/* eslint-disable no-use-before-define */\n\n//# sourceMappingURL=interface.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/link/interface.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ encodeTo: () => (/* binding */ encodeTo),\n/* harmony export */ encodingLength: () => (/* binding */ encodingLength)\n/* harmony export */ });\n/* harmony import */ var _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vendor/varint.js */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/varint.js\");\n\nfunction decode(data, offset = 0) {\n const code = _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode(data, offset);\n return [code, _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].decode.bytes];\n}\nfunction encodeTo(int, target, offset = 0) {\n _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encode(int, target, offset);\n return target;\n}\nfunction encodingLength(int) {\n return _vendor_varint_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"].encodingLength(int);\n}\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/base-x.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/base-x.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base(ALPHABET, name) {\n if (ALPHABET.length >= 255) {\n throw new TypeError('Alphabet too long');\n }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) {\n throw new TypeError(x + ' is ambiguous');\n }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable} source\n */\n function encode(source) {\n // @ts-ignore\n if (source instanceof Uint8Array)\n ;\n else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n }\n else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) {\n throw new TypeError('Expected Uint8Array');\n }\n if (source.length === 0) {\n return '';\n }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) {\n str += ALPHABET.charAt(b58[it2]);\n }\n return str;\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe(source) {\n if (typeof source !== 'string') {\n throw new TypeError('Expected String');\n }\n if (source.length === 0) {\n return new Uint8Array();\n }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) {\n return;\n }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) {\n throw new Error('Non-zero carry');\n }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') {\n return;\n }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch;\n }\n /**\n * @param {string | string[]} string\n */\n function decode(string) {\n var buffer = decodeUnsafe(string);\n if (buffer) {\n return buffer;\n }\n throw new Error(`Non-${name} character`);\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n };\n}\nvar src = base;\nvar _brrp__multiformats_scope_baseX = src;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp__multiformats_scope_baseX);\n//# sourceMappingURL=base-x.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/base-x.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/varint.js": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/varint.js ***! + \*********************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-disable */\nvar encode_1 = encode;\nvar MSB = 0x80, REST = 0x7F, MSBALL = ~REST, INT = Math.pow(2, 31);\n/**\n * @param {number} num\n * @param {number[]} out\n * @param {number} offset\n */\nfunction encode(num, out, offset) {\n out = out || [];\n offset = offset || 0;\n var oldOffset = offset;\n while (num >= INT) {\n out[offset++] = (num & 0xFF) | MSB;\n num /= 128;\n }\n while (num & MSBALL) {\n out[offset++] = (num & 0xFF) | MSB;\n num >>>= 7;\n }\n out[offset] = num | 0;\n // @ts-ignore\n encode.bytes = offset - oldOffset + 1;\n return out;\n}\nvar decode = read;\nvar MSB$1 = 0x80, REST$1 = 0x7F;\n/**\n * @param {string | any[]} buf\n * @param {number} offset\n */\nfunction read(buf, offset) {\n var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;\n do {\n if (counter >= l) {\n // @ts-ignore\n read.bytes = 0;\n throw new RangeError('Could not decode varint');\n }\n b = buf[counter++];\n res += shift < 28\n ? (b & REST$1) << shift\n : (b & REST$1) * Math.pow(2, shift);\n shift += 7;\n } while (b >= MSB$1);\n // @ts-ignore\n read.bytes = counter - offset;\n return res;\n}\nvar N1 = Math.pow(2, 7);\nvar N2 = Math.pow(2, 14);\nvar N3 = Math.pow(2, 21);\nvar N4 = Math.pow(2, 28);\nvar N5 = Math.pow(2, 35);\nvar N6 = Math.pow(2, 42);\nvar N7 = Math.pow(2, 49);\nvar N8 = Math.pow(2, 56);\nvar N9 = Math.pow(2, 63);\nvar length = function (/** @type {number} */ value) {\n return (value < N1 ? 1\n : value < N2 ? 2\n : value < N3 ? 3\n : value < N4 ? 4\n : value < N5 ? 5\n : value < N6 ? 6\n : value < N7 ? 7\n : value < N8 ? 8\n : value < N9 ? 9\n : 10);\n};\nvar varint = {\n encode: encode_1,\n decode: decode,\n encodingLength: length\n};\nvar _brrp_varint = varint;\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_brrp_varint);\n//# sourceMappingURL=varint.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/vendor/varint.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/alloc.js": +/*!************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/alloc.js ***! + \************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ alloc: () => (/* binding */ alloc),\n/* harmony export */ allocUnsafe: () => (/* binding */ allocUnsafe)\n/* harmony export */ });\n/**\n * Returns a `Uint8Array` of the requested size. Referenced memory will\n * be initialized to 0.\n */\nfunction alloc(size = 0) {\n return new Uint8Array(size);\n}\n/**\n * Where possible returns a Uint8Array of the requested size that references\n * uninitialized memory. Only use if you are certain you will immediately\n * overwrite every value in the returned `Uint8Array`.\n */\nfunction allocUnsafe(size = 0) {\n return new Uint8Array(size);\n}\n//# sourceMappingURL=alloc.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/alloc.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/from-string.js": +/*!******************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/from-string.js ***! + \******************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ fromString: () => (/* binding */ fromString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Create a `Uint8Array` from the passed string\n *\n * Supports `utf8`, `utf-8`, `hex`, and any encoding supported by the multiformats module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction fromString(string, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // add multibase prefix\n return base.decoder.decode(`${base.prefix}${string}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions\n}\n//# sourceMappingURL=from-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/from-string.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/to-string.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/to-string.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ toString: () => (/* binding */ toString)\n/* harmony export */ });\n/* harmony import */ var _util_bases_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util/bases.js */ \"./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/util/bases.js\");\n\n/**\n * Turns a `Uint8Array` into a string.\n *\n * Supports `utf8`, `utf-8` and any encoding supported by the multibase module.\n *\n * Also `ascii` which is similar to node's 'binary' encoding.\n */\nfunction toString(array, encoding = 'utf8') {\n const base = _util_bases_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"][encoding];\n if (base == null) {\n throw new Error(`Unsupported encoding \"${encoding}\"`);\n }\n // strip multibase prefix\n return base.encoder.encode(array).substring(1);\n}\n//# sourceMappingURL=to-string.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/to-string.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/util/bases.js": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/util/bases.js ***! + \*****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@waku/message-hash/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var _alloc__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! #alloc */ \"./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/alloc.js\");\n\n\nfunction createCodec(name, prefix, encode, decode) {\n return {\n name,\n prefix,\n encoder: {\n name,\n prefix,\n encode\n },\n decoder: {\n decode\n }\n };\n}\nconst string = createCodec('utf8', 'u', (buf) => {\n const decoder = new TextDecoder('utf8');\n return 'u' + decoder.decode(buf);\n}, (str) => {\n const encoder = new TextEncoder();\n return encoder.encode(str.substring(1));\n});\nconst ascii = createCodec('ascii', 'a', (buf) => {\n let string = 'a';\n for (let i = 0; i < buf.length; i++) {\n string += String.fromCharCode(buf[i]);\n }\n return string;\n}, (str) => {\n str = str.substring(1);\n const buf = (0,_alloc__WEBPACK_IMPORTED_MODULE_1__.allocUnsafe)(str.length);\n for (let i = 0; i < str.length; i++) {\n buf[i] = str.charCodeAt(i);\n }\n return buf;\n});\nconst BASES = {\n utf8: string,\n 'utf-8': string,\n hex: multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases.base16,\n latin1: ascii,\n ascii,\n binary: ascii,\n ...multiformats_basics__WEBPACK_IMPORTED_MODULE_0__.bases\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BASES);\n//# sourceMappingURL=bases.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/message-hash/node_modules/uint8arrays/dist/src/util/bases.js?"); + +/***/ }), + /***/ "./node_modules/@waku/proto/dist/index.js": /*!************************************************!*\ !*** ./node_modules/@waku/proto/dist/index.js ***! @@ -10204,7 +15076,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decryptEipKeystore: () => (/* binding */ decryptEipKeystore),\n/* harmony export */ keccak256Checksum: () => (/* binding */ keccak256Checksum)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_bls_keystore_lib_cipher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/cipher.js */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher.js\");\n/* harmony import */ var _chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/kdf.js */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf.js\");\n/* harmony import */ var _chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/password.js */ \"./node_modules/@chainsafe/bls-keystore/lib/password.js\");\n/* harmony import */ var ethereum_cryptography_keccak__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ethereum-cryptography/keccak */ \"./node_modules/ethereum-cryptography/esm/keccak.js\");\n/* harmony import */ var ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/esm/utils.js\");\n\n\n\n\n\n// eipKeystore supports only sha256 checksum so we just make an assumption it is keccak256\nconst validateChecksum = async (password, eipKeystore) => {\n const computedChecksum = await keccak256Checksum(password, eipKeystore);\n return computedChecksum === eipKeystore.crypto.checksum.message;\n};\n// decrypt from @chainsafe/bls-keystore supports only sha256\n// but nwaku uses keccak256\n// https://github.com/waku-org/nwaku/blob/25d6e52e3804d15f9b61bc4cc6dd448540c072a1/waku/waku_keystore/keyfile.nim#L367\nconst decryptEipKeystore = async (password, eipKeystore) => {\n const decryptionKey = await (0,_chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__.kdf)(eipKeystore.crypto.kdf, (0,_chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__.normalizePassword)(password));\n const isChecksumValid = await validateChecksum(password, eipKeystore);\n if (!isChecksumValid) {\n throw Error(\"Password is invalid.\");\n }\n return (0,_chainsafe_bls_keystore_lib_cipher_js__WEBPACK_IMPORTED_MODULE_0__.cipherDecrypt)(eipKeystore.crypto.cipher, decryptionKey.slice(0, 16));\n};\nconst keccak256Checksum = async (password, eipKeystore) => {\n const key = await (0,_chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__.kdf)(eipKeystore.crypto.kdf, (0,_chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__.normalizePassword)(password));\n const payload = (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.concatBytes)(key.slice(16), (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.hexToBytes)(eipKeystore.crypto.cipher.message));\n const ciphertext = (0,ethereum_cryptography_keccak__WEBPACK_IMPORTED_MODULE_3__.keccak256)(payload);\n return (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.bytesToHex)(ciphertext);\n};\n//# sourceMappingURL=cipher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/rln/dist/keystore/cipher.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decryptEipKeystore: () => (/* binding */ decryptEipKeystore),\n/* harmony export */ keccak256Checksum: () => (/* binding */ keccak256Checksum)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_bls_keystore_lib_cipher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/cipher.js */ \"./node_modules/@chainsafe/bls-keystore/lib/cipher/index.js\");\n/* harmony import */ var _chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/kdf.js */ \"./node_modules/@chainsafe/bls-keystore/lib/kdf/index.js\");\n/* harmony import */ var _chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @chainsafe/bls-keystore/lib/password.js */ \"./node_modules/@chainsafe/bls-keystore/lib/password.js\");\n/* harmony import */ var ethereum_cryptography_keccak__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ethereum-cryptography/keccak */ \"./node_modules/ethereum-cryptography/esm/keccak.js\");\n/* harmony import */ var ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ethereum-cryptography/utils */ \"./node_modules/ethereum-cryptography/esm/utils.js\");\n\n\n\n\n\n// eipKeystore supports only sha256 checksum so we just make an assumption it is keccak256\nconst validateChecksum = async (password, eipKeystore) => {\n const computedChecksum = await keccak256Checksum(password, eipKeystore);\n return computedChecksum === eipKeystore.crypto.checksum.message;\n};\n// decrypt from @chainsafe/bls-keystore supports only sha256\n// but nwaku uses keccak256\n// https://github.com/waku-org/nwaku/blob/25d6e52e3804d15f9b61bc4cc6dd448540c072a1/waku/waku_keystore/keyfile.nim#L367\nconst decryptEipKeystore = async (password, eipKeystore) => {\n const decryptionKey = await (0,_chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__.kdf)(eipKeystore.crypto.kdf, (0,_chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__.normalizePassword)(password));\n const isChecksumValid = await validateChecksum(password, eipKeystore);\n if (!isChecksumValid) {\n throw Error(\"Password is invalid.\");\n }\n return (0,_chainsafe_bls_keystore_lib_cipher_js__WEBPACK_IMPORTED_MODULE_0__.cipherDecrypt)(eipKeystore.crypto.cipher, decryptionKey.slice(0, 16));\n};\nconst keccak256Checksum = async (password, eipKeystore) => {\n const key = await (0,_chainsafe_bls_keystore_lib_kdf_js__WEBPACK_IMPORTED_MODULE_1__.kdf)(eipKeystore.crypto.kdf, (0,_chainsafe_bls_keystore_lib_password_js__WEBPACK_IMPORTED_MODULE_2__.normalizePassword)(password));\n const payload = (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.concatBytes)(key.slice(16), (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.hexToBytes)(eipKeystore.crypto.cipher.message));\n const ciphertext = (0,ethereum_cryptography_keccak__WEBPACK_IMPORTED_MODULE_3__.keccak256)(payload);\n return (0,ethereum_cryptography_utils__WEBPACK_IMPORTED_MODULE_4__.bytesToHex)(ciphertext);\n};\n//# sourceMappingURL=cipher.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/rln/dist/keystore/cipher.js?"); /***/ }), @@ -10611,7 +15483,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n *\n * @param type\n * @param bits - Minimum of 1024\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519PrivateKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PrivateKey),\n/* harmony export */ Ed25519PublicKey: () => (/* reexport safe */ _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.Ed25519PublicKey),\n/* harmony export */ MAX_RSA_KEY_SIZE: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.MAX_RSA_KEY_SIZE),\n/* harmony export */ RsaPrivateKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPrivateKey),\n/* harmony export */ RsaPublicKey: () => (/* reexport safe */ _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__.RsaPublicKey),\n/* harmony export */ Secp256k1PrivateKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PrivateKey),\n/* harmony export */ Secp256k1PublicKey: () => (/* reexport safe */ _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__.Secp256k1PublicKey),\n/* harmony export */ generateEphemeralKeyPair: () => (/* reexport safe */ _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"]),\n/* harmony export */ generateKeyPair: () => (/* binding */ generateKeyPair),\n/* harmony export */ generateKeyPairFromSeed: () => (/* binding */ generateKeyPairFromSeed),\n/* harmony export */ importKey: () => (/* binding */ importKey),\n/* harmony export */ keyStretcher: () => (/* reexport safe */ _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__.keyStretcher),\n/* harmony export */ keysPBM: () => (/* reexport module object */ _keys_js__WEBPACK_IMPORTED_MODULE_2__),\n/* harmony export */ marshalPrivateKey: () => (/* binding */ marshalPrivateKey),\n/* harmony export */ marshalPublicKey: () => (/* binding */ marshalPublicKey),\n/* harmony export */ supportedKeys: () => (/* binding */ supportedKeys),\n/* harmony export */ unmarshalPrivateKey: () => (/* binding */ unmarshalPrivateKey),\n/* harmony export */ unmarshalPublicKey: () => (/* binding */ unmarshalPublicKey)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ed25519-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/ed25519-class.js\");\n/* harmony import */ var _ephemeral_keys_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ephemeral-keys.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/ephemeral-keys.js\");\n/* harmony import */ var _importer_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./importer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/importer.js\");\n/* harmony import */ var _key_stretcher_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./key-stretcher.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/key-stretcher.js\");\n/* harmony import */ var _keys_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/keys.js\");\n/* harmony import */ var _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./rsa-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/rsa-class.js\");\n/* harmony import */ var _rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./rsa-utils.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/rsa-utils.js\");\n/* harmony import */ var _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./secp256k1-class.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/secp256k1-class.js\");\n/**\n * @packageDocumentation\n *\n * **Supported Key Types**\n *\n * The {@link generateKeyPair}, {@link marshalPublicKey}, and {@link marshalPrivateKey} functions accept a string `type` argument.\n *\n * Currently the `'RSA'`, `'ed25519'`, and `secp256k1` types are supported, although ed25519 and secp256k1 keys support only signing and verification of messages.\n *\n * For encryption / decryption support, RSA keys should be used.\n */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst supportedKeys = {\n rsa: _rsa_class_js__WEBPACK_IMPORTED_MODULE_3__,\n ed25519: _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__,\n secp256k1: _secp256k1_class_js__WEBPACK_IMPORTED_MODULE_5__\n};\nfunction unsupportedKey(type) {\n const supported = Object.keys(supportedKeys).join(' / ');\n return new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError(`invalid or unsupported key type ${type}. Must be ${supported}`, 'ERR_UNSUPPORTED_KEY_TYPE');\n}\nfunction typeToKey(type) {\n type = type.toLowerCase();\n if (type === 'rsa' || type === 'ed25519' || type === 'secp256k1') {\n return supportedKeys[type];\n }\n throw unsupportedKey(type);\n}\n/**\n * Generates a keypair of the given type and bitsize\n */\nasync function generateKeyPair(type, bits) {\n return typeToKey(type).generateKeyPair(bits ?? 2048);\n}\n/**\n * Generates a keypair of the given type and bitsize.\n *\n * Seed is a 32 byte uint8array\n */\nasync function generateKeyPairFromSeed(type, seed, bits) {\n if (type.toLowerCase() !== 'ed25519') {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Seed key derivation is unimplemented for RSA or secp256k1', 'ERR_UNSUPPORTED_KEY_DERIVATION_TYPE');\n }\n return _ed25519_class_js__WEBPACK_IMPORTED_MODULE_4__.generateKeyPairFromSeed(seed);\n}\n/**\n * Converts a protobuf serialized public key into its representative object\n */\nfunction unmarshalPublicKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PublicKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PublicKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PublicKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'unknown');\n }\n}\n/**\n * Converts a public key object into a protobuf serialized public key\n */\nfunction marshalPublicKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts a protobuf serialized private key into its representative object\n */\nasync function unmarshalPrivateKey(buf) {\n const decoded = _keys_js__WEBPACK_IMPORTED_MODULE_2__.PrivateKey.decode(buf);\n const data = decoded.Data ?? new Uint8Array();\n switch (decoded.Type) {\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.RSA:\n return supportedKeys.rsa.unmarshalRsaPrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Ed25519:\n return supportedKeys.ed25519.unmarshalEd25519PrivateKey(data);\n case _keys_js__WEBPACK_IMPORTED_MODULE_2__.KeyType.Secp256k1:\n return supportedKeys.secp256k1.unmarshalSecp256k1PrivateKey(data);\n default:\n throw unsupportedKey(decoded.Type ?? 'RSA');\n }\n}\n/**\n * Converts a private key object into a protobuf serialized private key\n */\nfunction marshalPrivateKey(key, type) {\n type = (type ?? 'rsa').toLowerCase();\n typeToKey(type); // check type\n return key.bytes;\n}\n/**\n * Converts an exported private key into its representative object.\n *\n * Supported formats are 'pem' (RSA only) and 'libp2p-key'.\n */\nasync function importKey(encryptedKey, password) {\n try {\n const key = await (0,_importer_js__WEBPACK_IMPORTED_MODULE_7__.importer)(encryptedKey, password);\n return await unmarshalPrivateKey(key);\n }\n catch (_) {\n // Ignore and try the old pem decrypt\n }\n if (!encryptedKey.includes('BEGIN')) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Encrypted key was not a libp2p-key or a PEM file', 'ERR_INVALID_IMPORT_FORMAT');\n }\n return (0,_rsa_utils_js__WEBPACK_IMPORTED_MODULE_8__.importFromPem)(encryptedKey, password);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js?"); /***/ }), @@ -10721,7 +15593,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto == null || nativeCrypto.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* eslint-env browser */\n// Check native crypto exists and is enabled (In insecure context `self.crypto`\n// exists but `self.crypto.subtle` does not).\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({\n get(win = globalThis) {\n const nativeCrypto = win.crypto;\n if (nativeCrypto?.subtle == null) {\n throw Object.assign(new Error('Missing Web Crypto API. ' +\n 'The most likely cause of this error is that this page is being accessed ' +\n 'from an insecure context (i.e. not HTTPS). For more information and ' +\n 'possible resolutions see ' +\n 'https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api'), { code: 'ERR_MISSING_WEB_CRYPTO' });\n }\n return nativeCrypto;\n }\n});\n//# sourceMappingURL=webcrypto-browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/webcrypto-browser.js?"); /***/ }), @@ -10765,7 +15637,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\n/**\n * CustomEvent is a standard event but it's not supported by node.\n *\n * Remove this when https://github.com/nodejs/node/issues/40678 is closed.\n *\n * Ref: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent\n */\nclass CustomEventPolyfill extends Event {\n /** Returns any custom data event was created with. Typically used for synthetic events. */\n detail;\n constructor(message, data) {\n super(message, data);\n // @ts-expect-error could be undefined\n this.detail = data?.detail;\n }\n}\nconst CustomEvent = globalThis.CustomEvent ?? CustomEventPolyfill;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomEvent: () => (/* binding */ CustomEvent),\n/* harmony export */ TypedEventEmitter: () => (/* binding */ TypedEventEmitter)\n/* harmony export */ });\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n\n/**\n * An implementation of a typed event target\n * etc\n */\nclass TypedEventEmitter extends EventTarget {\n #listeners = new Map();\n constructor() {\n super();\n // silence MaxListenersExceededWarning warning on Node.js, this is a red\n // herring almost all of the time\n (0,_events_js__WEBPACK_IMPORTED_MODULE_0__.setMaxListeners)(Infinity, this);\n }\n listenerCount(type) {\n const listeners = this.#listeners.get(type);\n if (listeners == null) {\n return 0;\n }\n return listeners.length;\n }\n addEventListener(type, listener, options) {\n super.addEventListener(type, listener, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n list = [];\n this.#listeners.set(type, list);\n }\n list.push({\n callback: listener,\n once: (options !== true && options !== false && options?.once) ?? false\n });\n }\n removeEventListener(type, listener, options) {\n super.removeEventListener(type.toString(), listener ?? null, options);\n let list = this.#listeners.get(type);\n if (list == null) {\n return;\n }\n list = list.filter(({ callback }) => callback !== listener);\n this.#listeners.set(type, list);\n }\n dispatchEvent(event) {\n const result = super.dispatchEvent(event);\n let list = this.#listeners.get(event.type);\n if (list == null) {\n return result;\n }\n list = list.filter(({ once }) => !once);\n this.#listeners.set(event.type, list);\n return result;\n }\n safeDispatchEvent(type, detail = {}) {\n return this.dispatchEvent(new CustomEvent(type, detail));\n }\n}\nconst CustomEvent = globalThis.CustomEvent;\n//# sourceMappingURL=event-target.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js?"); /***/ }), @@ -10791,6 +15663,28 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/index.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/index.js ***! + \*********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AbortError),\n/* harmony export */ AggregateCodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.AggregateCodeError),\n/* harmony export */ CodeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.CodeError),\n/* harmony export */ CustomEvent: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.CustomEvent),\n/* harmony export */ ERR_INVALID_MESSAGE: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_MESSAGE),\n/* harmony export */ ERR_INVALID_PARAMETERS: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_INVALID_PARAMETERS),\n/* harmony export */ ERR_NOT_FOUND: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_NOT_FOUND),\n/* harmony export */ ERR_TIMEOUT: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.ERR_TIMEOUT),\n/* harmony export */ Ed25519: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.Ed25519),\n/* harmony export */ FaultTolerance: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.FaultTolerance),\n/* harmony export */ InvalidCryptoExchangeError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoExchangeError),\n/* harmony export */ InvalidCryptoTransmissionError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.InvalidCryptoTransmissionError),\n/* harmony export */ KEEP_ALIVE: () => (/* reexport safe */ _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__.KEEP_ALIVE),\n/* harmony export */ RSA: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.RSA),\n/* harmony export */ StrictNoSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictNoSign),\n/* harmony export */ StrictSign: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* reexport safe */ _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__.TopicValidatorResult),\n/* harmony export */ TypedEventEmitter: () => (/* reexport safe */ _event_target_js__WEBPACK_IMPORTED_MODULE_10__.TypedEventEmitter),\n/* harmony export */ UnexpectedPeerError: () => (/* reexport safe */ _errors_js__WEBPACK_IMPORTED_MODULE_9__.UnexpectedPeerError),\n/* harmony export */ connectionSymbol: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.connectionSymbol),\n/* harmony export */ contentRoutingSymbol: () => (/* reexport safe */ _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__.contentRoutingSymbol),\n/* harmony export */ isConnection: () => (/* reexport safe */ _connection_index_js__WEBPACK_IMPORTED_MODULE_0__.isConnection),\n/* harmony export */ isPeerId: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.isPeerId),\n/* harmony export */ isStartable: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.isStartable),\n/* harmony export */ isTransport: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.isTransport),\n/* harmony export */ peerDiscoverySymbol: () => (/* reexport safe */ _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__.peerDiscoverySymbol),\n/* harmony export */ peerIdSymbol: () => (/* reexport safe */ _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__.peerIdSymbol),\n/* harmony export */ peerRoutingSymbol: () => (/* reexport safe */ _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__.peerRoutingSymbol),\n/* harmony export */ secp256k1: () => (/* reexport safe */ _keys_index_js__WEBPACK_IMPORTED_MODULE_2__.secp256k1),\n/* harmony export */ serviceCapabilities: () => (/* binding */ serviceCapabilities),\n/* harmony export */ serviceDependencies: () => (/* binding */ serviceDependencies),\n/* harmony export */ setMaxListeners: () => (/* reexport safe */ _events_js__WEBPACK_IMPORTED_MODULE_11__.setMaxListeners),\n/* harmony export */ start: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.start),\n/* harmony export */ stop: () => (/* reexport safe */ _startable_js__WEBPACK_IMPORTED_MODULE_12__.stop),\n/* harmony export */ transportSymbol: () => (/* reexport safe */ _transport_index_js__WEBPACK_IMPORTED_MODULE_8__.transportSymbol)\n/* harmony export */ });\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/connection/index.js\");\n/* harmony import */ var _content_routing_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./content-routing/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _keys_index_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keys/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/keys/index.js\");\n/* harmony import */ var _peer_discovery_index_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./peer-discovery/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _peer_id_index_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./peer-id/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _peer_routing_index_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./peer-routing/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _peer_store_tags_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./peer-store/tags.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _pubsub_index_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./pubsub/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/pubsub/index.js\");\n/* harmony import */ var _transport_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./transport/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _event_target_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./event-target.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./events.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _startable_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./startable.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/startable.js\");\n/**\n * @packageDocumentation\n *\n * Exports a `Libp2p` type for modules to use as a type argument.\n *\n * @example\n *\n * ```typescript\n * import type { Libp2p } from '@libp2p/interface'\n *\n * function doSomethingWithLibp2p (node: Libp2p) {\n * // ...\n * }\n * ```\n */\n/**\n * This symbol is used by libp2p services to define the capabilities they can\n * provide to other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of provided capabilities.\n */\nconst serviceCapabilities = Symbol.for('@libp2p/service-capabilities');\n/**\n * This symbol is used by libp2p services to define the capabilities they\n * require from other libp2p services.\n *\n * The service should define a property with this symbol as the key and the\n * value should be a string array of required capabilities.\n */\nconst serviceDependencies = Symbol.for('@libp2p/service-dependencies');\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/keys/index.js": +/*!**************************************************************************************!*\ + !*** ./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/keys/index.js ***! + \**************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Ed25519: () => (/* binding */ Ed25519),\n/* harmony export */ RSA: () => (/* binding */ RSA),\n/* harmony export */ secp256k1: () => (/* binding */ secp256k1)\n/* harmony export */ });\nconst Ed25519 = 'Ed25519';\nconst RSA = 'RSA';\nconst secp256k1 = 'secp256k1';\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/keys/index.js?"); + +/***/ }), + /***/ "./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js": /*!************************************************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js ***! @@ -10835,6 +15729,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/pubsub/index.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/pubsub/index.js ***! + \****************************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ StrictNoSign: () => (/* binding */ StrictNoSign),\n/* harmony export */ StrictSign: () => (/* binding */ StrictSign),\n/* harmony export */ TopicValidatorResult: () => (/* binding */ TopicValidatorResult)\n/* harmony export */ });\n/**\n * On the producing side:\n * * Build messages with the signature, key (from may be enough for certain inlineable public key types), from and seqno fields.\n *\n * On the consuming side:\n * * Enforce the fields to be present, reject otherwise.\n * * Propagate only if the fields are valid and signature can be verified, reject otherwise.\n */\nconst StrictSign = 'StrictSign';\n/**\n * On the producing side:\n * * Build messages without the signature, key, from and seqno fields.\n * * The corresponding protobuf key-value pairs are absent from the marshalled message, not just empty.\n *\n * On the consuming side:\n * * Enforce the fields to be absent, reject otherwise.\n * * Propagate only if the fields are absent, reject otherwise.\n * * A message_id function will not be able to use the above fields, and should instead rely on the data field. A commonplace strategy is to calculate a hash.\n */\nconst StrictNoSign = 'StrictNoSign';\nvar TopicValidatorResult;\n(function (TopicValidatorResult) {\n /**\n * The message is considered valid, and it should be delivered and forwarded to the network\n */\n TopicValidatorResult[\"Accept\"] = \"accept\";\n /**\n * The message is neither delivered nor forwarded to the network\n */\n TopicValidatorResult[\"Ignore\"] = \"ignore\";\n /**\n * The message is considered invalid, and it should be rejected\n */\n TopicValidatorResult[\"Reject\"] = \"reject\";\n})(TopicValidatorResult || (TopicValidatorResult = {}));\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/pubsub/index.js?"); + +/***/ }), + /***/ "./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/startable.js": /*!*************************************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/startable.js ***! @@ -10857,28 +15762,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/index.js": -/*!******************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/index.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ defaultLogger: () => (/* binding */ defaultLogger),\n/* harmony export */ disable: () => (/* binding */ disable),\n/* harmony export */ enable: () => (/* binding */ enable),\n/* harmony export */ enabled: () => (/* binding */ enabled),\n/* harmony export */ logger: () => (/* binding */ logger),\n/* harmony export */ peerLogger: () => (/* binding */ peerLogger),\n/* harmony export */ prefixLogger: () => (/* binding */ prefixLogger)\n/* harmony export */ });\n/* harmony import */ var debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! debug */ \"./node_modules/debug/src/browser.js\");\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/bases/base64 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base64.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/utils.js\");\n/**\n * @packageDocumentation\n *\n * A logger for libp2p based on the venerable [debug](https://www.npmjs.com/package/debug) module.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('libp2p:my:component:name')\n *\n * try {\n * // an operation\n * log('something happened: %s', 'it was ok')\n * } catch (err) {\n * log.error('something bad happened: %o', err)\n * }\n *\n * log('with this peer: %p', {})\n * log('and this base58btc: %b', Uint8Array.from([0, 1, 2, 3]))\n * log('and this base32: %t', Uint8Array.from([4, 5, 6, 7]))\n * ```\n *\n * ```console\n * $ DEBUG=libp2p:* node index.js\n * something happened: it was ok\n * something bad happened: \n * with this peer: 12D3Foo\n * with this base58btc: Qmfoo\n * with this base32: bafyfoo\n * ```\n */\n\n\n\n\n\n// Add a formatter for converting to a base58 string\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.b = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_2__.base58btc.baseEncode(v);\n};\n// Add a formatter for converting to a base32 string\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.t = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.baseEncode(v);\n};\n// Add a formatter for converting to a base64 string\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.m = (v) => {\n return v == null ? 'undefined' : multiformats_bases_base64__WEBPACK_IMPORTED_MODULE_3__.base64.baseEncode(v);\n};\n// Add a formatter for stringifying peer ids\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.p = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying CIDs\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.c = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Datastore keys\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.k = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\n// Add a formatter for stringifying Multiaddrs\ndebug__WEBPACK_IMPORTED_MODULE_0__.formatters.a = (v) => {\n return v == null ? 'undefined' : v.toString();\n};\nfunction createDisabledLogger(namespace) {\n const logger = () => { };\n logger.enabled = false;\n logger.color = '';\n logger.diff = 0;\n logger.log = () => { };\n logger.namespace = namespace;\n logger.destroy = () => true;\n logger.extend = () => logger;\n return logger;\n}\n/**\n * Create a component logger that will prefix any log messages with a truncated\n * peer id.\n *\n * @example\n *\n * ```TypeScript\n * import { peerLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const peerId = peerIdFromString('12D3FooBar')\n * const logger = peerLogger(peerId)\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"12…oBar:my-component hello world\"\n * ```\n */\nfunction peerLogger(peerId, options = {}) {\n return prefixLogger((0,_utils_js__WEBPACK_IMPORTED_MODULE_4__.truncatePeerId)(peerId, options));\n}\n/**\n * Create a component logger that will prefix any log messages with the passed\n * string.\n *\n * @example\n *\n * ```TypeScript\n * import { prefixLogger } from '@libp2p/logger'\n *\n * const logger = prefixLogger('my-node')\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-node:my-component hello world\"\n * ```\n */\nfunction prefixLogger(prefix) {\n return {\n forComponent(name) {\n return logger(`${prefix}:${name}`);\n }\n };\n}\n/**\n * Create a component logger\n *\n * @example\n *\n * ```TypeScript\n * import { defaultLogger } from '@libp2p/logger'\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * const logger = defaultLogger()\n *\n * const log = logger.forComponent('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nfunction defaultLogger() {\n return {\n forComponent(name) {\n return logger(name);\n }\n };\n}\n/**\n * Creates a logger for the passed component name.\n *\n * @example\n *\n * ```TypeScript\n * import { logger } from '@libp2p/logger'\n *\n * const log = logger('my-component')\n * log.info('hello world')\n * // logs \"my-component hello world\"\n * ```\n */\nfunction logger(name) {\n // trace logging is a no-op by default\n let trace = createDisabledLogger(`${name}:trace`);\n // look at all the debug names and see if trace logging has explicitly been enabled\n if (debug__WEBPACK_IMPORTED_MODULE_0__.enabled(`${name}:trace`) && debug__WEBPACK_IMPORTED_MODULE_0__.names.map(r => r.toString()).find(n => n.includes(':trace')) != null) {\n trace = debug__WEBPACK_IMPORTED_MODULE_0__(`${name}:trace`);\n }\n return Object.assign(debug__WEBPACK_IMPORTED_MODULE_0__(name), {\n error: debug__WEBPACK_IMPORTED_MODULE_0__(`${name}:error`),\n trace\n });\n}\nfunction disable() {\n debug__WEBPACK_IMPORTED_MODULE_0__.disable();\n}\nfunction enable(namespaces) {\n debug__WEBPACK_IMPORTED_MODULE_0__.enable(namespaces);\n}\nfunction enabled(namespaces) {\n return debug__WEBPACK_IMPORTED_MODULE_0__.enabled(namespaces);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/index.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/utils.js": -/*!******************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/utils.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ truncatePeerId: () => (/* binding */ truncatePeerId)\n/* harmony export */ });\nfunction truncatePeerId(peerId, options = {}) {\n const prefixLength = options.prefixLength ?? 2;\n const suffixLength = options.suffixLength ?? 4;\n const peerIdString = peerId.toString();\n return `${peerIdString.substring(0, prefixLength)}…${peerIdString.substring(peerIdString.length, peerIdString.length - suffixLength)}`;\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/utils.js?"); - -/***/ }), - /***/ "./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/constants.js": /*!**********************************************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/constants.js ***! @@ -10923,39 +15806,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js": -/*!**************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js ***! - \**************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerMap: () => (/* binding */ PeerMap),\n/* harmony export */ peerMap: () => (/* binding */ peerMap)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/util.js\");\n\n\n/**\n * We can't use PeerIds as map keys because map keys are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerMap } from '@libp2p/peer-collections'\n *\n * const map = peerMap()\n * map.set(peerId, 'value')\n * ```\n */\nclass PeerMap {\n map;\n constructor(map) {\n this.map = new Map();\n if (map != null) {\n for (const [key, value] of map.entries()) {\n this.map.set(key.toString(), value);\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries();\n }\n clear() {\n this.map.clear();\n }\n delete(peer) {\n return this.map.delete(peer.toString());\n }\n entries() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.map.entries(), (val) => {\n return [(0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val[0]), val[1]];\n });\n }\n forEach(fn) {\n this.map.forEach((value, key) => {\n fn(value, (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(key), this);\n });\n }\n get(peer) {\n return this.map.get(peer.toString());\n }\n has(peer) {\n return this.map.has(peer.toString());\n }\n set(peer, value) {\n this.map.set(peer.toString(), value);\n }\n keys() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.map.keys(), (val) => {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val);\n });\n }\n values() {\n return this.map.values();\n }\n get size() {\n return this.map.size;\n }\n}\nfunction peerMap() {\n return new PeerMap();\n}\n//# sourceMappingURL=map.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js": -/*!**************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js ***! - \**************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerSet: () => (/* binding */ PeerSet),\n/* harmony export */ peerSet: () => (/* binding */ peerSet)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./util.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/util.js\");\n\n\n/**\n * We can't use PeerIds as set entries because set entries are\n * compared using same-value-zero equality, so this is just\n * a map that stringifies the PeerIds before storing them.\n *\n * PeerIds cache stringified versions of themselves so this\n * should be a cheap operation.\n *\n * @example\n *\n * ```TypeScript\n * import { peerSet } from '@libp2p/peer-collections'\n *\n * const set = peerSet()\n * set.add(peerId)\n * ```\n */\nclass PeerSet {\n set;\n constructor(set) {\n this.set = new Set();\n if (set != null) {\n for (const key of set) {\n this.set.add(key.toString());\n }\n }\n }\n get size() {\n return this.set.size;\n }\n [Symbol.iterator]() {\n return this.values();\n }\n add(peer) {\n this.set.add(peer.toString());\n }\n clear() {\n this.set.clear();\n }\n delete(peer) {\n this.set.delete(peer.toString());\n }\n entries() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.set.entries(), (val) => {\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val[0]);\n return [peerId, peerId];\n });\n }\n forEach(predicate) {\n this.set.forEach((str) => {\n const id = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(str);\n predicate(id, id, this);\n });\n }\n has(peer) {\n return this.set.has(peer.toString());\n }\n values() {\n return (0,_util_js__WEBPACK_IMPORTED_MODULE_0__.mapIterable)(this.set.values(), (val) => {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(val);\n });\n }\n intersection(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n if (this.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n difference(other) {\n const output = new PeerSet();\n for (const peerId of this) {\n if (!other.has(peerId)) {\n output.add(peerId);\n }\n }\n return output;\n }\n union(other) {\n const output = new PeerSet();\n for (const peerId of other) {\n output.add(peerId);\n }\n for (const peerId of this) {\n output.add(peerId);\n }\n return output;\n }\n}\nfunction peerSet() {\n return new PeerSet();\n}\n//# sourceMappingURL=set.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/util.js": -/*!***************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/util.js ***! - \***************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ mapIterable: () => (/* binding */ mapIterable)\n/* harmony export */ });\n/**\n * Calls the passed map function on every entry of the passed iterable iterator\n */\nfunction mapIterable(iter, map) {\n const iterator = {\n [Symbol.iterator]: () => {\n return iterator;\n },\n next: () => {\n const next = iter.next();\n const val = next.value;\n if (next.done === true || val == null) {\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n return {\n done: false,\n value: map(val)\n };\n }\n };\n return iterator;\n}\n//# sourceMappingURL=util.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/util.js?"); - -/***/ }), - /***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js": /*!***************************************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js ***! @@ -10963,7 +15813,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createEd25519PeerId: () => (/* binding */ createEd25519PeerId),\n/* harmony export */ createFromJSON: () => (/* binding */ createFromJSON),\n/* harmony export */ createFromPrivKey: () => (/* binding */ createFromPrivKey),\n/* harmony export */ createFromProtobuf: () => (/* binding */ createFromProtobuf),\n/* harmony export */ createFromPubKey: () => (/* binding */ createFromPubKey),\n/* harmony export */ createRSAPeerId: () => (/* binding */ createRSAPeerId),\n/* harmony export */ createSecp256k1PeerId: () => (/* binding */ createSecp256k1PeerId),\n/* harmony export */ exportToProtobuf: () => (/* binding */ exportToProtobuf)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _proto_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./proto.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/proto.js\");\n/**\n * @packageDocumentation\n *\n * Generate, import, and export PeerIDs.\n *\n * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.\n *\n * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.\n *\n * @example\n *\n * ```TypeScript\n * import { createEd25519PeerId } from '@libp2p/peer-id-factory'\n *\n * const peerId = await createEd25519PeerId()\n * console.log(peerId.toString())\n * ```\n *\n * ```bash\n * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD\n * ```\n */\n\n\n\n\nconst createEd25519PeerId = async () => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('Ed25519');\n const id = await createFromPrivKey(key);\n if (id.type === 'Ed25519') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nconst createSecp256k1PeerId = async () => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('secp256k1');\n const id = await createFromPrivKey(key);\n if (id.type === 'secp256k1') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nconst createRSAPeerId = async (opts) => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('RSA', opts?.bits ?? 2048);\n const id = await createFromPrivKey(key);\n if (id.type === 'RSA') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nasync function createFromPubKey(publicKey) {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromKeys)((0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPublicKey)(publicKey));\n}\nasync function createFromPrivKey(privateKey) {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromKeys)((0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPublicKey)(privateKey.public), (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPrivateKey)(privateKey));\n}\nfunction exportToProtobuf(peerId, excludePrivateKey) {\n return _proto_js__WEBPACK_IMPORTED_MODULE_3__.PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n });\n}\nasync function createFromProtobuf(buf) {\n const { id, privKey, pubKey } = _proto_js__WEBPACK_IMPORTED_MODULE_3__.PeerIdProto.decode(buf);\n return createFromParts(id ?? new Uint8Array(0), privKey, pubKey);\n}\nasync function createFromJSON(obj) {\n return createFromParts((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.id, 'base58btc'), obj.privKey != null ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.privKey, 'base64pad') : undefined, obj.pubKey != null ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.pubKey, 'base64pad') : undefined);\n}\nasync function createFromParts(multihash, privKey, pubKey) {\n if (privKey != null) {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.unmarshalPrivateKey)(privKey);\n return createFromPrivKey(key);\n }\n else if (pubKey != null) {\n const key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.unmarshalPublicKey)(pubKey);\n return createFromPubKey(key);\n }\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromBytes)(multihash);\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createEd25519PeerId: () => (/* binding */ createEd25519PeerId),\n/* harmony export */ createFromJSON: () => (/* binding */ createFromJSON),\n/* harmony export */ createFromPrivKey: () => (/* binding */ createFromPrivKey),\n/* harmony export */ createFromProtobuf: () => (/* binding */ createFromProtobuf),\n/* harmony export */ createFromPubKey: () => (/* binding */ createFromPubKey),\n/* harmony export */ createRSAPeerId: () => (/* binding */ createRSAPeerId),\n/* harmony export */ createSecp256k1PeerId: () => (/* binding */ createSecp256k1PeerId),\n/* harmony export */ exportToProtobuf: () => (/* binding */ exportToProtobuf)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _proto_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./proto.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/proto.js\");\n/**\n * @packageDocumentation\n *\n * Generate, import, and export PeerIDs.\n *\n * A Peer ID is the SHA-256 [multihash](https://github.com/multiformats/multihash) of a public key.\n *\n * The public key is a base64 encoded string of a protobuf containing an RSA DER buffer. This uses a node buffer to pass the base64 encoded public key protobuf to the multihash for ID generation.\n *\n * @example\n *\n * ```TypeScript\n * import { createEd25519PeerId } from '@libp2p/peer-id-factory'\n *\n * const peerId = await createEd25519PeerId()\n * console.log(peerId.toString())\n * ```\n *\n * ```bash\n * 12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD\n * ```\n */\n\n\n\n\nconst createEd25519PeerId = async () => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('Ed25519');\n const id = await createFromPrivKey(key);\n if (id.type === 'Ed25519') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nconst createSecp256k1PeerId = async () => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('secp256k1');\n const id = await createFromPrivKey(key);\n if (id.type === 'secp256k1') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nconst createRSAPeerId = async (opts) => {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.generateKeyPair)('RSA', opts?.bits ?? 2048);\n const id = await createFromPrivKey(key);\n if (id.type === 'RSA') {\n return id;\n }\n throw new Error(`Generated unexpected PeerId type \"${id.type}\"`);\n};\nasync function createFromPubKey(publicKey) {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromKeys)((0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPublicKey)(publicKey));\n}\nasync function createFromPrivKey(privateKey) {\n return (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromKeys)((0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPublicKey)(privateKey.public), (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.marshalPrivateKey)(privateKey));\n}\nfunction exportToProtobuf(peerId, excludePrivateKey) {\n return _proto_js__WEBPACK_IMPORTED_MODULE_3__.PeerIdProto.encode({\n id: peerId.multihash.bytes,\n pubKey: peerId.publicKey,\n privKey: excludePrivateKey === true || peerId.privateKey == null ? undefined : peerId.privateKey\n });\n}\nasync function createFromProtobuf(buf) {\n const { id, privKey, pubKey } = _proto_js__WEBPACK_IMPORTED_MODULE_3__.PeerIdProto.decode(buf);\n return createFromParts(id ?? new Uint8Array(0), privKey, pubKey);\n}\nasync function createFromJSON(obj) {\n return createFromParts((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.id, 'base58btc'), obj.privKey != null ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.privKey, 'base64pad') : undefined, obj.pubKey != null ? (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_0__.fromString)(obj.pubKey, 'base64pad') : undefined);\n}\nasync function createFromParts(multihash, privKey, pubKey) {\n if (privKey != null) {\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.unmarshalPrivateKey)(privKey);\n return createFromPrivKey(key);\n }\n else if (pubKey != null) {\n const key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_1__.unmarshalPublicKey)(pubKey);\n return createFromPubKey(key);\n }\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromBytes)(multihash);\n if (peerId.type !== 'Ed25519' && peerId.type !== 'secp256k1' && peerId.type !== 'RSA') {\n // should not be possible since `multihash` is derived from keys and these\n // are the cryptographic peer id types\n throw new Error('Supplied PeerID is invalid');\n }\n return peerId;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js?"); /***/ }), @@ -10985,73 +15835,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/equals.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid == null || cid.multihash == null || cid.version == null || (cid.version === 1 && cid.code !== LIBP2P_KEY_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js": -/*!***********************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js ***! - \***********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Envelope: () => (/* binding */ Envelope)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar Envelope;\n(function (Envelope) {\n let _codec;\n Envelope.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.publicKey != null && obj.publicKey.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.publicKey);\n }\n if ((obj.payloadType != null && obj.payloadType.byteLength > 0)) {\n w.uint32(18);\n w.bytes(obj.payloadType);\n }\n if ((obj.payload != null && obj.payload.byteLength > 0)) {\n w.uint32(26);\n w.bytes(obj.payload);\n }\n if ((obj.signature != null && obj.signature.byteLength > 0)) {\n w.uint32(42);\n w.bytes(obj.signature);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n publicKey: new Uint8Array(0),\n payloadType: new Uint8Array(0),\n payload: new Uint8Array(0),\n signature: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.publicKey = reader.bytes();\n break;\n case 2:\n obj.payloadType = reader.bytes();\n break;\n case 3:\n obj.payload = reader.bytes();\n break;\n case 5:\n obj.signature = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n Envelope.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, Envelope.codec());\n };\n Envelope.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, Envelope.codec());\n };\n})(Envelope || (Envelope = {}));\n//# sourceMappingURL=envelope.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/index.js": -/*!********************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/index.js ***! - \********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RecordEnvelope: () => (/* binding */ RecordEnvelope)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/errors.js\");\n/* harmony import */ var _envelope_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./envelope.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/envelope.js\");\n\n\n\n\n\n\n\n\n\nclass RecordEnvelope {\n /**\n * Unmarshal a serialized Envelope protobuf message\n */\n static createFromProtobuf = async (data) => {\n const envelopeData = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.decode(data);\n const peerId = await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__.peerIdFromKeys)(envelopeData.publicKey);\n return new RecordEnvelope({\n peerId,\n payloadType: envelopeData.payloadType,\n payload: envelopeData.payload,\n signature: envelopeData.signature\n });\n };\n /**\n * Seal marshals the given Record, places the marshaled bytes inside an Envelope\n * and signs it with the given peerId's private key\n */\n static seal = async (record, peerId) => {\n if (peerId.privateKey == null) {\n throw new Error('Missing private key');\n }\n const domain = record.domain;\n const payloadType = record.codec;\n const payload = record.marshal();\n const signData = formatSignaturePayload(domain, payloadType, payload);\n const key = await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPrivateKey)(peerId.privateKey);\n const signature = await key.sign(signData.subarray());\n return new RecordEnvelope({\n peerId,\n payloadType,\n payload,\n signature\n });\n };\n /**\n * Open and certify a given marshalled envelope.\n * Data is unmarshalled and the signature validated for the given domain.\n */\n static openAndCertify = async (data, domain) => {\n const envelope = await RecordEnvelope.createFromProtobuf(data);\n const valid = await envelope.validate(domain);\n if (!valid) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_7__.CodeError('envelope signature is not valid for the given domain', _errors_js__WEBPACK_IMPORTED_MODULE_8__.codes.ERR_SIGNATURE_NOT_VALID);\n }\n return envelope;\n };\n peerId;\n payloadType;\n payload;\n signature;\n marshaled;\n /**\n * The Envelope is responsible for keeping an arbitrary signed record\n * by a libp2p peer.\n */\n constructor(init) {\n const { peerId, payloadType, payload, signature } = init;\n this.peerId = peerId;\n this.payloadType = payloadType;\n this.payload = payload;\n this.signature = signature;\n }\n /**\n * Marshal the envelope content\n */\n marshal() {\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n if (this.marshaled == null) {\n this.marshaled = _envelope_js__WEBPACK_IMPORTED_MODULE_4__.Envelope.encode({\n publicKey: this.peerId.publicKey,\n payloadType: this.payloadType,\n payload: this.payload.subarray(),\n signature: this.signature\n });\n }\n return this.marshaled;\n }\n /**\n * Verifies if the other Envelope is identical to this one\n */\n equals(other) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(this.marshal(), other.marshal());\n }\n /**\n * Validate envelope data signature for the given domain\n */\n async validate(domain) {\n const signData = formatSignaturePayload(domain, this.payloadType, this.payload);\n if (this.peerId.publicKey == null) {\n throw new Error('Missing public key');\n }\n const key = (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_6__.unmarshalPublicKey)(this.peerId.publicKey);\n return key.verify(signData.subarray(), this.signature);\n }\n}\n/**\n * Helper function that prepares a Uint8Array to sign or verify a signature\n */\nconst formatSignaturePayload = (domain, payloadType, payload) => {\n // When signing, a peer will prepare a Uint8Array by concatenating the following:\n // - The length of the domain separation string string in bytes\n // - The domain separation string, encoded as UTF-8\n // - The length of the payload_type field in bytes\n // - The value of the payload_type field\n // - The length of the payload field in bytes\n // - The value of the payload field\n const domainUint8Array = (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(domain);\n const domainLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(domainUint8Array.byteLength);\n const payloadTypeLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payloadType.length);\n const payloadLength = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encode(payload.length);\n return new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList(domainLength, domainUint8Array, payloadTypeLength, payloadType, payloadLength, payload);\n};\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/index.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/errors.js": -/*!************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/errors.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ codes: () => (/* binding */ codes)\n/* harmony export */ });\nconst codes = {\n ERR_SIGNATURE_NOT_VALID: 'ERR_SIGNATURE_NOT_VALID'\n};\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/errors.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js": -/*!************************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js ***! - \************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ENVELOPE_DOMAIN_PEER_RECORD: () => (/* binding */ ENVELOPE_DOMAIN_PEER_RECORD),\n/* harmony export */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD: () => (/* binding */ ENVELOPE_PAYLOAD_TYPE_PEER_RECORD)\n/* harmony export */ });\n// The domain string used for peer records contained in a Envelope.\nconst ENVELOPE_DOMAIN_PEER_RECORD = 'libp2p-peer-record';\n// The type hint used to identify peer records in a Envelope.\n// Defined in https://github.com/multiformats/multicodec/blob/master/table.csv\n// with name \"libp2p-peer-record\"\nconst ENVELOPE_PAYLOAD_TYPE_PEER_RECORD = Uint8Array.from([3, 1]);\n//# sourceMappingURL=consts.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js": -/*!***********************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js ***! - \***********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/utils/array-equals */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/array-equals.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _consts_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./consts.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/consts.js\");\n/* harmony import */ var _peer_record_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./peer-record.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js\");\n\n\n\n\n\n/**\n * The PeerRecord is used for distributing peer routing records across the network.\n * It contains the peer's reachable listen addresses.\n */\nclass PeerRecord {\n /**\n * Unmarshal Peer Record Protobuf\n */\n static createFromProtobuf = (buf) => {\n const peerRecord = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.decode(buf);\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromBytes)(peerRecord.peerId);\n const multiaddrs = (peerRecord.addresses ?? []).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a.multiaddr));\n const seqNumber = peerRecord.seq;\n return new PeerRecord({ peerId, multiaddrs, seqNumber });\n };\n static DOMAIN = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_DOMAIN_PEER_RECORD;\n static CODEC = _consts_js__WEBPACK_IMPORTED_MODULE_3__.ENVELOPE_PAYLOAD_TYPE_PEER_RECORD;\n peerId;\n multiaddrs;\n seqNumber;\n domain = PeerRecord.DOMAIN;\n codec = PeerRecord.CODEC;\n marshaled;\n constructor(init) {\n const { peerId, multiaddrs, seqNumber } = init;\n this.peerId = peerId;\n this.multiaddrs = multiaddrs ?? [];\n this.seqNumber = seqNumber ?? BigInt(Date.now());\n }\n /**\n * Marshal a record to be used in an envelope\n */\n marshal() {\n if (this.marshaled == null) {\n this.marshaled = _peer_record_js__WEBPACK_IMPORTED_MODULE_1__.PeerRecord.encode({\n peerId: this.peerId.toBytes(),\n seq: BigInt(this.seqNumber),\n addresses: this.multiaddrs.map((m) => ({\n multiaddr: m.bytes\n }))\n });\n }\n return this.marshaled;\n }\n /**\n * Returns true if `this` record equals the `other`\n */\n equals(other) {\n if (!(other instanceof PeerRecord)) {\n return false;\n }\n // Validate PeerId\n if (!this.peerId.equals(other.peerId)) {\n return false;\n }\n // Validate seqNumber\n if (this.seqNumber !== other.seqNumber) {\n return false;\n }\n // Validate multiaddrs\n if (!(0,_libp2p_utils_array_equals__WEBPACK_IMPORTED_MODULE_4__.arrayEquals)(this.multiaddrs, other.multiaddrs)) {\n return false;\n }\n return true;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js": -/*!*****************************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js ***! - \*****************************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerRecord: () => (/* binding */ PeerRecord)\n/* harmony export */ });\n/* harmony import */ var protons_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! protons-runtime */ \"./node_modules/protons-runtime/dist/src/index.js\");\n/* eslint-disable import/export */\n/* eslint-disable complexity */\n/* eslint-disable @typescript-eslint/no-namespace */\n/* eslint-disable @typescript-eslint/no-unnecessary-boolean-literal-compare */\n/* eslint-disable @typescript-eslint/no-empty-interface */\n\nvar PeerRecord;\n(function (PeerRecord) {\n let AddressInfo;\n (function (AddressInfo) {\n let _codec;\n AddressInfo.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.multiaddr != null && obj.multiaddr.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.multiaddr);\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n multiaddr: new Uint8Array(0)\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.multiaddr = reader.bytes();\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n AddressInfo.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, AddressInfo.codec());\n };\n AddressInfo.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, AddressInfo.codec());\n };\n })(AddressInfo = PeerRecord.AddressInfo || (PeerRecord.AddressInfo = {}));\n let _codec;\n PeerRecord.codec = () => {\n if (_codec == null) {\n _codec = (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.message)((obj, w, opts = {}) => {\n if (opts.lengthDelimited !== false) {\n w.fork();\n }\n if ((obj.peerId != null && obj.peerId.byteLength > 0)) {\n w.uint32(10);\n w.bytes(obj.peerId);\n }\n if ((obj.seq != null && obj.seq !== 0n)) {\n w.uint32(16);\n w.uint64(obj.seq);\n }\n if (obj.addresses != null) {\n for (const value of obj.addresses) {\n w.uint32(26);\n PeerRecord.AddressInfo.codec().encode(value, w);\n }\n }\n if (opts.lengthDelimited !== false) {\n w.ldelim();\n }\n }, (reader, length) => {\n const obj = {\n peerId: new Uint8Array(0),\n seq: 0n,\n addresses: []\n };\n const end = length == null ? reader.len : reader.pos + length;\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n obj.peerId = reader.bytes();\n break;\n case 2:\n obj.seq = reader.uint64();\n break;\n case 3:\n obj.addresses.push(PeerRecord.AddressInfo.codec().decode(reader, reader.uint32()));\n break;\n default:\n reader.skipType(tag & 7);\n break;\n }\n }\n return obj;\n });\n }\n return _codec;\n };\n PeerRecord.encode = (obj) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.encodeMessage)(obj, PeerRecord.codec());\n };\n PeerRecord.decode = (buf) => {\n return (0,protons_runtime__WEBPACK_IMPORTED_MODULE_0__.decodeMessage)(buf, PeerRecord.codec());\n };\n})(PeerRecord || (PeerRecord = {}));\n//# sourceMappingURL=peer-record.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/peer-record.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ createPeerId: () => (/* binding */ createPeerId),\n/* harmony export */ peerIdFromBytes: () => (/* binding */ peerIdFromBytes),\n/* harmony export */ peerIdFromCID: () => (/* binding */ peerIdFromCID),\n/* harmony export */ peerIdFromKeys: () => (/* binding */ peerIdFromKeys),\n/* harmony export */ peerIdFromPeerId: () => (/* binding */ peerIdFromPeerId),\n/* harmony export */ peerIdFromString: () => (/* binding */ peerIdFromString)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! multiformats/bases/base58 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var multiformats_basics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/basics */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/basics.js\");\n/* harmony import */ var multiformats_cid__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! multiformats/cid */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/cid.js\");\n/* harmony import */ var multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! multiformats/hashes/digest */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! multiformats/hashes/identity */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/identity.js\");\n/* harmony import */ var multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! multiformats/hashes/sha2 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/sha2-browser.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/to-string.js\");\n/**\n * @packageDocumentation\n *\n * An implementation of a peer id\n *\n * @example\n *\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n * const peer = peerIdFromString('k51qzi5uqu5dkwkqm42v9j9kqcam2jiuvloi16g72i4i4amoo2m8u3ol3mqu6s')\n *\n * console.log(peer.toCID()) // CID(bafzaa...)\n * console.log(peer.toString()) // \"12D3K...\"\n * ```\n */\n\n\n\n\n\n\n\n\n\n\n\nconst inspect = Symbol.for('nodejs.util.inspect.custom');\nconst baseDecoder = Object\n .values(multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases)\n .map(codec => codec.decoder)\n // @ts-expect-error https://github.com/multiformats/js-multiformats/issues/141\n .reduce((acc, curr) => acc.or(curr), multiformats_basics__WEBPACK_IMPORTED_MODULE_1__.bases.identity.decoder);\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst LIBP2P_KEY_CODE = 0x72;\nconst MARSHALLED_ED225519_PUBLIC_KEY_LENGTH = 36;\nconst MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH = 37;\nclass PeerIdImpl {\n type;\n multihash;\n privateKey;\n publicKey;\n string;\n constructor(init) {\n this.type = init.type;\n this.multihash = init.multihash;\n this.privateKey = init.privateKey;\n // mark string cache as non-enumerable\n Object.defineProperty(this, 'string', {\n enumerable: false,\n writable: true\n });\n }\n get [Symbol.toStringTag]() {\n return `PeerId(${this.toString()})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n if (this.string == null) {\n this.string = multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.encode(this.multihash.bytes).slice(1);\n }\n return this.string;\n }\n // return self-describing String representation\n // in default format from RFC 0001: https://github.com/libp2p/specs/pull/209\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(LIBP2P_KEY_CODE, this.multihash);\n }\n toBytes() {\n return this.multihash.bytes;\n }\n /**\n * Returns Multiaddr as a JSON string\n */\n toJSON() {\n return this.toString();\n }\n /**\n * Checks the equality of `this` peer against a given PeerId\n */\n equals(id) {\n if (id == null) {\n return false;\n }\n if (id instanceof Uint8Array) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id);\n }\n else if (typeof id === 'string') {\n return peerIdFromString(id).equals(this);\n }\n else if (id?.multihash?.bytes != null) {\n return (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_6__.equals)(this.multihash.bytes, id.multihash.bytes);\n }\n else {\n throw new Error('not valid Id');\n }\n }\n /**\n * Returns PeerId as a human-readable string\n * https://nodejs.org/api/util.html#utilinspectcustom\n *\n * @example\n * ```TypeScript\n * import { peerIdFromString } from '@libp2p/peer-id'\n *\n * console.info(peerIdFromString('QmFoo'))\n * // 'PeerId(QmFoo)'\n * ```\n */\n [inspect]() {\n return `PeerId(${this.toString()})`;\n }\n}\nclass RSAPeerIdImpl extends PeerIdImpl {\n type = 'RSA';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'RSA' });\n this.publicKey = init.publicKey;\n }\n}\nclass Ed25519PeerIdImpl extends PeerIdImpl {\n type = 'Ed25519';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'Ed25519' });\n this.publicKey = init.multihash.digest;\n }\n}\nclass Secp256k1PeerIdImpl extends PeerIdImpl {\n type = 'secp256k1';\n publicKey;\n constructor(init) {\n super({ ...init, type: 'secp256k1' });\n this.publicKey = init.multihash.digest;\n }\n}\n// these values are from https://github.com/multiformats/multicodec/blob/master/table.csv\nconst TRANSPORT_IPFS_GATEWAY_HTTP_CODE = 0x0920;\nclass URLPeerIdImpl {\n type = 'url';\n multihash;\n privateKey;\n publicKey;\n url;\n constructor(url) {\n this.url = url.toString();\n this.multihash = multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.digest((0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_7__.fromString)(this.url));\n }\n [inspect]() {\n return `PeerId(${this.url})`;\n }\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_9__.peerIdSymbol] = true;\n toString() {\n return this.toCID().toString();\n }\n toCID() {\n return multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.createV1(TRANSPORT_IPFS_GATEWAY_HTTP_CODE, this.multihash);\n }\n toBytes() {\n return this.toCID().bytes;\n }\n equals(other) {\n if (other == null) {\n return false;\n }\n if (other instanceof Uint8Array) {\n other = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(other);\n }\n return other.toString() === this.toString();\n }\n}\nfunction createPeerId(init) {\n if (init.type === 'RSA') {\n return new RSAPeerIdImpl(init);\n }\n if (init.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(init);\n }\n if (init.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(init);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Type must be \"RSA\", \"Ed25519\" or \"secp256k1\"', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromPeerId(other) {\n if (other.type === 'RSA') {\n return new RSAPeerIdImpl(other);\n }\n if (other.type === 'Ed25519') {\n return new Ed25519PeerIdImpl(other);\n }\n if (other.type === 'secp256k1') {\n return new Secp256k1PeerIdImpl(other);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.CodeError('Not a PeerId', 'ERR_INVALID_PARAMETERS');\n}\nfunction peerIdFromString(str, decoder) {\n decoder = decoder ?? baseDecoder;\n if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {\n // identity hash ed25519/secp256k1 key or sha2-256 hash of\n // rsa public key - base58btc encoded either way\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(multiformats_bases_base58__WEBPACK_IMPORTED_MODULE_0__.base58btc.decode(`z${str}`));\n if (str.startsWith('12D')) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (str.startsWith('16U')) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n else {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n return peerIdFromBytes(baseDecoder.decode(str));\n}\nfunction peerIdFromBytes(buf) {\n try {\n const multihash = multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.decode(buf);\n if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash });\n }\n }\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash });\n }\n }\n catch {\n return peerIdFromCID(multiformats_cid__WEBPACK_IMPORTED_MODULE_2__.CID.decode(buf));\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\nfunction peerIdFromCID(cid) {\n if (cid?.multihash == null || cid.version == null || (cid.version === 1 && (cid.code !== LIBP2P_KEY_CODE) && cid.code !== TRANSPORT_IPFS_GATEWAY_HTTP_CODE)) {\n throw new Error('Supplied PeerID CID is invalid');\n }\n if (cid.code === TRANSPORT_IPFS_GATEWAY_HTTP_CODE) {\n const url = (0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_8__.toString)(cid.multihash.digest);\n return new URLPeerIdImpl(new URL(url));\n }\n const multihash = cid.multihash;\n if (multihash.code === multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.code) {\n return new RSAPeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.code === multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code) {\n if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: cid.multihash });\n }\n else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: cid.multihash });\n }\n }\n throw new Error('Supplied PeerID CID is invalid');\n}\n/**\n * @param publicKey - A marshalled public key\n * @param privateKey - A marshalled private key\n */\nasync function peerIdFromKeys(publicKey, privateKey) {\n if (publicKey.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {\n return new Ed25519PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n if (publicKey.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {\n return new Secp256k1PeerIdImpl({ multihash: multiformats_hashes_digest__WEBPACK_IMPORTED_MODULE_3__.create(multiformats_hashes_identity__WEBPACK_IMPORTED_MODULE_4__.identity.code, publicKey), privateKey });\n }\n return new RSAPeerIdImpl({ multihash: await multiformats_hashes_sha2__WEBPACK_IMPORTED_MODULE_5__.sha256.digest(publicKey), publicKey, privateKey });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js?"); /***/ }), @@ -11073,7 +15857,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PersistentPeerStore: () => (/* binding */ PersistentPeerStore)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/envelope/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-record/dist/src/peer-record/index.js\");\n/* harmony import */ var it_all__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-all */ \"./node_modules/it-all/dist/src/index.js\");\n/* harmony import */ var _store_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./store.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/store.js\");\n/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\n\n\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nclass PersistentPeerStore {\n store;\n events;\n peerId;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.events = components.events;\n this.peerId = components.peerId;\n this.store = new _store_js__WEBPACK_IMPORTED_MODULE_1__.PersistentStore(components, init);\n }\n async forEach(fn, query) {\n this.log.trace('forEach await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('forEach got read lock');\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer);\n }\n }\n finally {\n this.log.trace('forEach release read lock');\n release();\n }\n }\n async all(query) {\n this.log.trace('all await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('all got read lock');\n try {\n return await (0,it_all__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(this.store.all(query));\n }\n finally {\n this.log.trace('all release read lock');\n release();\n }\n }\n async delete(peerId) {\n this.log.trace('delete await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('delete got write lock');\n try {\n await this.store.delete(peerId);\n }\n finally {\n this.log.trace('delete release write lock');\n release();\n }\n }\n async has(peerId) {\n this.log.trace('has await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('has got read lock');\n try {\n return await this.store.has(peerId);\n }\n finally {\n this.log.trace('has release read lock');\n release();\n }\n }\n async get(peerId) {\n this.log.trace('get await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('get got read lock');\n try {\n return await this.store.load(peerId);\n }\n finally {\n this.log.trace('get release read lock');\n release();\n }\n }\n async save(id, data) {\n this.log.trace('save await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('save got write lock');\n try {\n const result = await this.store.save(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('save release write lock');\n release();\n }\n }\n async patch(id, data) {\n this.log.trace('patch await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('patch got write lock');\n try {\n const result = await this.store.patch(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('patch release write lock');\n release();\n }\n }\n async merge(id, data) {\n this.log.trace('merge await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('merge got write lock');\n try {\n const result = await this.store.merge(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('merge release write lock');\n release();\n }\n }\n async consumePeerRecord(buf, expectedPeer) {\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__.RecordEnvelope.openAndCertify(buf, _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.DOMAIN);\n if (expectedPeer?.equals(envelope.peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, envelope.peerId);\n return false;\n }\n const peerRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.createFromProtobuf(envelope.payload);\n let peer;\n try {\n peer = await this.get(envelope.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__.RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope);\n const storedRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.createFromProtobuf(storedEnvelope.payload);\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n return false;\n }\n }\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n });\n return true;\n }\n #emitIfUpdated(id, result) {\n if (!result.updated) {\n return;\n }\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result });\n }\n else {\n this.events.safeDispatchEvent('peer:update', { detail: result });\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PersistentPeerStore: () => (/* binding */ PersistentPeerStore)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/peer-record/dist/src/envelope/index.js\");\n/* harmony import */ var _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-record */ \"./node_modules/@libp2p/peer-record/dist/src/peer-record/index.js\");\n/* harmony import */ var it_all__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-all */ \"./node_modules/it-all/dist/src/index.js\");\n/* harmony import */ var _store_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./store.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/store.js\");\n/**\n * @packageDocumentation\n *\n * The peer store is where libp2p stores data about the peers it has encountered on the network.\n */\n\n\n\n/**\n * An implementation of PeerStore that stores data in a Datastore\n */\nclass PersistentPeerStore {\n store;\n events;\n peerId;\n log;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-store');\n this.events = components.events;\n this.peerId = components.peerId;\n this.store = new _store_js__WEBPACK_IMPORTED_MODULE_1__.PersistentStore(components, init);\n }\n [Symbol.toStringTag] = '@libp2p/peer-store';\n async forEach(fn, query) {\n this.log.trace('forEach await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('forEach got read lock');\n try {\n for await (const peer of this.store.all(query)) {\n fn(peer);\n }\n }\n finally {\n this.log.trace('forEach release read lock');\n release();\n }\n }\n async all(query) {\n this.log.trace('all await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('all got read lock');\n try {\n return await (0,it_all__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(this.store.all(query));\n }\n finally {\n this.log.trace('all release read lock');\n release();\n }\n }\n async delete(peerId) {\n this.log.trace('delete await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('delete got write lock');\n try {\n await this.store.delete(peerId);\n }\n finally {\n this.log.trace('delete release write lock');\n release();\n }\n }\n async has(peerId) {\n this.log.trace('has await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('has got read lock');\n try {\n return await this.store.has(peerId);\n }\n finally {\n this.log.trace('has release read lock');\n release();\n }\n }\n async get(peerId) {\n this.log.trace('get await read lock');\n const release = await this.store.lock.readLock();\n this.log.trace('get got read lock');\n try {\n return await this.store.load(peerId);\n }\n finally {\n this.log.trace('get release read lock');\n release();\n }\n }\n async save(id, data) {\n this.log.trace('save await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('save got write lock');\n try {\n const result = await this.store.save(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('save release write lock');\n release();\n }\n }\n async patch(id, data) {\n this.log.trace('patch await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('patch got write lock');\n try {\n const result = await this.store.patch(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('patch release write lock');\n release();\n }\n }\n async merge(id, data) {\n this.log.trace('merge await write lock');\n const release = await this.store.lock.writeLock();\n this.log.trace('merge got write lock');\n try {\n const result = await this.store.merge(id, data);\n this.#emitIfUpdated(id, result);\n return result.peer;\n }\n finally {\n this.log.trace('merge release write lock');\n release();\n }\n }\n async consumePeerRecord(buf, expectedPeer) {\n const envelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__.RecordEnvelope.openAndCertify(buf, _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.DOMAIN);\n if (expectedPeer?.equals(envelope.peerId) === false) {\n this.log('envelope peer id was not the expected peer id - expected: %p received: %p', expectedPeer, envelope.peerId);\n return false;\n }\n const peerRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.createFromProtobuf(envelope.payload);\n let peer;\n try {\n peer = await this.get(envelope.peerId);\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n // ensure seq is greater than, or equal to, the last received\n if (peer?.peerRecordEnvelope != null) {\n const storedEnvelope = await _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_2__.RecordEnvelope.createFromProtobuf(peer.peerRecordEnvelope);\n const storedRecord = _libp2p_peer_record__WEBPACK_IMPORTED_MODULE_3__.PeerRecord.createFromProtobuf(storedEnvelope.payload);\n if (storedRecord.seqNumber >= peerRecord.seqNumber) {\n this.log('sequence number was lower or equal to existing sequence number - stored: %d received: %d', storedRecord.seqNumber, peerRecord.seqNumber);\n return false;\n }\n }\n await this.patch(peerRecord.peerId, {\n peerRecordEnvelope: buf,\n addresses: peerRecord.multiaddrs.map(multiaddr => ({\n isCertified: true,\n multiaddr\n }))\n });\n return true;\n }\n #emitIfUpdated(id, result) {\n if (!result.updated) {\n return;\n }\n if (this.peerId.equals(id)) {\n this.events.safeDispatchEvent('self:peer:update', { detail: result });\n }\n else {\n this.events.safeDispatchEvent('peer:update', { detail: result });\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/index.js?"); /***/ }), @@ -11095,7 +15879,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PersistentStore: () => (/* binding */ PersistentStore)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var mortice__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! mortice */ \"./node_modules/mortice/dist/src/index.js\");\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/errors.js\");\n/* harmony import */ var _pb_peer_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pb/peer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/pb/peer.js\");\n/* harmony import */ var _utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/bytes-to-peer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/bytes-to-peer.js\");\n/* harmony import */ var _utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/peer-id-to-datastore-key.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/peer-id-to-datastore-key.js\");\n/* harmony import */ var _utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/to-peer-pb.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/to-peer-pb.js\");\n\n\n\n\n\n\n\n\n\n\n\nfunction decodePeer(key, value, cache) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2];\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode(base32Str);\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__.peerIdFromBytes)(buf);\n const cached = cache.get(peerId);\n if (cached != null) {\n return cached;\n }\n const peer = (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, value);\n cache.set(peerId, peer);\n return peer;\n}\nfunction mapQuery(query, cache) {\n if (query == null) {\n return {};\n }\n return {\n prefix: _utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, cache));\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache));\n })\n };\n}\nclass PersistentStore {\n peerId;\n datastore;\n lock;\n addressFilter;\n constructor(components, init = {}) {\n this.peerId = components.peerId;\n this.datastore = components.datastore;\n this.addressFilter = init.addressFilter;\n this.lock = (0,mortice__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({\n name: 'peer-store',\n singleProcess: true\n });\n }\n async has(peerId) {\n return this.datastore.has((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n }\n async delete(peerId) {\n if (this.peerId.equals(peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Cannot delete self peer', _errors_js__WEBPACK_IMPORTED_MODULE_7__.codes.ERR_INVALID_PARAMETERS);\n }\n await this.datastore.delete((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n }\n async load(peerId) {\n const buf = await this.datastore.get((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n return (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf);\n }\n async save(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async patch(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async merge(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async *all(query) {\n const peerCache = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__.PeerMap();\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {\n const peer = decodePeer(key, value, peerCache);\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue;\n }\n yield peer;\n }\n }\n async #findExistingPeer(peerId) {\n try {\n const existingBuf = await this.datastore.get((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n const existingPeer = (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, existingBuf);\n return {\n existingBuf,\n existingPeer\n };\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n return {};\n }\n async #saveIfDifferent(peerId, peer, existingBuf, existingPeer) {\n const buf = _pb_peer_js__WEBPACK_IMPORTED_MODULE_10__.Peer.encode(peer);\n if (existingBuf != null && (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(buf, existingBuf)) {\n return {\n peer: (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf),\n previous: existingPeer,\n updated: false\n };\n }\n await this.datastore.put((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId), buf);\n return {\n peer: (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf),\n previous: existingPeer,\n updated: true\n };\n }\n}\n//# sourceMappingURL=store.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/store.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PersistentStore: () => (/* binding */ PersistentStore)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var mortice__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! mortice */ \"./node_modules/mortice/dist/src/index.js\");\n/* harmony import */ var multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! multiformats/bases/base32 */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/equals */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/equals.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/errors.js\");\n/* harmony import */ var _pb_peer_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pb/peer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/pb/peer.js\");\n/* harmony import */ var _utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/bytes-to-peer.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/bytes-to-peer.js\");\n/* harmony import */ var _utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/peer-id-to-datastore-key.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/peer-id-to-datastore-key.js\");\n/* harmony import */ var _utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/to-peer-pb.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/utils/to-peer-pb.js\");\n\n\n\n\n\n\n\n\n\n\n\nfunction decodePeer(key, value, cache) {\n // /peers/${peer-id-as-libp2p-key-cid-string-in-base-32}\n const base32Str = key.toString().split('/')[2];\n const buf = multiformats_bases_base32__WEBPACK_IMPORTED_MODULE_1__.base32.decode(base32Str);\n const peerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_3__.peerIdFromBytes)(buf);\n const cached = cache.get(peerId);\n if (cached != null) {\n return cached;\n }\n const peer = (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, value);\n cache.set(peerId, peer);\n return peer;\n}\nfunction mapQuery(query, cache) {\n if (query == null) {\n return {};\n }\n return {\n prefix: _utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.NAMESPACE_COMMON,\n filters: (query.filters ?? []).map(fn => ({ key, value }) => {\n return fn(decodePeer(key, value, cache));\n }),\n orders: (query.orders ?? []).map(fn => (a, b) => {\n return fn(decodePeer(a.key, a.value, cache), decodePeer(b.key, b.value, cache));\n })\n };\n}\nclass PersistentStore {\n peerId;\n datastore;\n lock;\n addressFilter;\n constructor(components, init = {}) {\n this.peerId = components.peerId;\n this.datastore = components.datastore;\n this.addressFilter = init.addressFilter;\n this.lock = (0,mortice__WEBPACK_IMPORTED_MODULE_0__[\"default\"])({\n name: 'peer-store',\n singleProcess: true\n });\n }\n async has(peerId) {\n return this.datastore.has((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n }\n async delete(peerId) {\n if (this.peerId.equals(peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_6__.CodeError('Cannot delete self peer', _errors_js__WEBPACK_IMPORTED_MODULE_7__.codes.ERR_INVALID_PARAMETERS);\n }\n await this.datastore.delete((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n }\n async load(peerId) {\n const buf = await this.datastore.get((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n return (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf);\n }\n async save(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'patch', {\n addressFilter: this.addressFilter\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async patch(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'patch', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async merge(peerId, data) {\n const { existingBuf, existingPeer } = await this.#findExistingPeer(peerId);\n const peerPb = await (0,_utils_to_peer_pb_js__WEBPACK_IMPORTED_MODULE_8__.toPeerPB)(peerId, data, 'merge', {\n addressFilter: this.addressFilter,\n existingPeer\n });\n return this.#saveIfDifferent(peerId, peerPb, existingBuf, existingPeer);\n }\n async *all(query) {\n const peerCache = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__.PeerMap();\n for await (const { key, value } of this.datastore.query(mapQuery(query ?? {}, peerCache))) {\n const peer = decodePeer(key, value, peerCache);\n if (peer.id.equals(this.peerId)) {\n // Skip self peer if present\n continue;\n }\n yield peer;\n }\n }\n async #findExistingPeer(peerId) {\n try {\n const existingBuf = await this.datastore.get((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId));\n const existingPeer = (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, existingBuf);\n return {\n existingBuf,\n existingPeer\n };\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n throw err;\n }\n }\n return {};\n }\n async #saveIfDifferent(peerId, peer, existingBuf, existingPeer) {\n const buf = _pb_peer_js__WEBPACK_IMPORTED_MODULE_10__.Peer.encode(peer);\n if (existingBuf != null && (0,uint8arrays_equals__WEBPACK_IMPORTED_MODULE_2__.equals)(buf, existingBuf)) {\n return {\n peer: (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf),\n previous: existingPeer,\n updated: false\n };\n }\n await this.datastore.put((0,_utils_peer_id_to_datastore_key_js__WEBPACK_IMPORTED_MODULE_5__.peerIdToDatastoreKey)(peerId), buf);\n return {\n peer: (0,_utils_bytes_to_peer_js__WEBPACK_IMPORTED_MODULE_4__.bytesToPeer)(peerId, buf),\n previous: existingPeer,\n updated: true\n };\n }\n}\n//# sourceMappingURL=store.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/store.js?"); /***/ }), @@ -11143,116 +15927,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js": -/*!************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ certifiedAddressesFirst: () => (/* binding */ certifiedAddressesFirst),\n/* harmony export */ circuitRelayAddressesLast: () => (/* binding */ circuitRelayAddressesLast),\n/* harmony export */ defaultAddressSort: () => (/* binding */ defaultAddressSort),\n/* harmony export */ publicAddressesFirst: () => (/* binding */ publicAddressesFirst)\n/* harmony export */ });\n/* harmony import */ var _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr-matcher */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js\");\n/* harmony import */ var _multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./multiaddr/is-private.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js\");\n/**\n * @packageDocumentation\n *\n * Provides strategies to sort a list of multiaddrs.\n *\n * @example\n *\n * ```typescript\n * import { publicAddressesFirst } from '@libp2p/utils/address-sort'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n *\n * const addresses = [\n * multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * multiaddr('/ip4/82.41.53.1/tcp/9000')\n * ].sort(publicAddressesFirst)\n *\n * console.info(addresses)\n * // ['/ip4/82.41.53.1/tcp/9000', '/ip4/127.0.0.1/tcp/9000']\n * ```\n */\n\n\n/**\n * Compare function for array.sort() that moves public addresses to the start\n * of the array.\n */\nfunction publicAddressesFirst(a, b) {\n const isAPrivate = (0,_multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__.isPrivate)(a.multiaddr);\n const isBPrivate = (0,_multiaddr_is_private_js__WEBPACK_IMPORTED_MODULE_1__.isPrivate)(b.multiaddr);\n if (isAPrivate && !isBPrivate) {\n return 1;\n }\n else if (!isAPrivate && isBPrivate) {\n return -1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves certified addresses to the start\n * of the array.\n */\nfunction certifiedAddressesFirst(a, b) {\n if (a.isCertified && !b.isCertified) {\n return -1;\n }\n else if (!a.isCertified && b.isCertified) {\n return 1;\n }\n return 0;\n}\n/**\n * Compare function for array.sort() that moves circuit relay addresses to the\n * start of the array.\n */\nfunction circuitRelayAddressesLast(a, b) {\n const isACircuit = _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__.Circuit.exactMatch(a.multiaddr);\n const isBCircuit = _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_0__.Circuit.exactMatch(b.multiaddr);\n if (isACircuit && !isBCircuit) {\n return 1;\n }\n else if (!isACircuit && isBCircuit) {\n return -1;\n }\n return 0;\n}\nfunction defaultAddressSort(a, b) {\n const publicResult = publicAddressesFirst(a, b);\n if (publicResult !== 0) {\n return publicResult;\n }\n const relayResult = circuitRelayAddressesLast(a, b);\n if (relayResult !== 0) {\n return relayResult;\n }\n const certifiedResult = certifiedAddressesFirst(a, b);\n return certifiedResult;\n}\n//# sourceMappingURL=address-sort.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/array-equals.js": -/*!************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/array-equals.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ arrayEquals: () => (/* binding */ arrayEquals)\n/* harmony export */ });\n/**\n * @packageDocumentation\n *\n * Provides strategies ensure arrays are equivalent.\n *\n * @example\n *\n * ```typescript\n * import { arrayEquals } from '@libp2p/utils/array-equals'\n * import { multiaddr } from '@multformats/multiaddr'\n *\n * const ma1 = multiaddr('/ip4/127.0.0.1/tcp/9000'),\n * const ma2 = multiaddr('/ip4/82.41.53.1/tcp/9000')\n *\n * console.info(arrayEquals([ma1], [ma1])) // true\n * console.info(arrayEquals([ma1], [ma2])) // false\n * ```\n */\n/**\n * Verify if two arrays of non primitive types with the \"equals\" function are equal.\n * Compatible with multiaddr, peer-id and others.\n */\nfunction arrayEquals(a, b) {\n const sort = (a, b) => a.toString().localeCompare(b.toString());\n if (a.length !== b.length) {\n return false;\n }\n b.sort(sort);\n return a.sort(sort).every((item, index) => b[index].equals(item));\n}\n//# sourceMappingURL=array-equals.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/array-equals.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js": -/*!********************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js ***! - \********************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPrivate: () => (/* binding */ isPrivate)\n/* harmony export */ });\n/* harmony import */ var _private_ip_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../private-ip.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/private-ip.js\");\n\n/**\n * Check if a given multiaddr has a private address.\n */\nfunction isPrivate(ma) {\n try {\n const { address } = ma.nodeAddress();\n return Boolean((0,_private_ip_js__WEBPACK_IMPORTED_MODULE_0__.isPrivateIp)(address));\n }\n catch {\n return true;\n }\n}\n//# sourceMappingURL=is-private.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/multiaddr/is-private.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/peer-queue.js": -/*!**********************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/peer-queue.js ***! - \**********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ PeerQueue: () => (/* binding */ PeerQueue)\n/* harmony export */ });\n/* harmony import */ var _queue_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./queue/index.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/index.js\");\n/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\n/**\n * Extends Queue to add support for querying queued jobs by peer id\n */\nclass PeerQueue extends _queue_index_js__WEBPACK_IMPORTED_MODULE_0__.Queue {\n has(peerId) {\n return this.find(peerId) != null;\n }\n find(peerId) {\n return this.queue.find(job => {\n return peerId.equals(job.options.peerId);\n });\n }\n}\n//# sourceMappingURL=peer-queue.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/peer-queue.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/private-ip.js": -/*!**********************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/private-ip.js ***! - \**********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isPrivateIp: () => (/* binding */ isPrivateIp)\n/* harmony export */ });\n/* harmony import */ var _chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @chainsafe/is-ip */ \"./node_modules/@chainsafe/is-ip/lib/is-ip.js\");\n/* harmony import */ var netmask__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! netmask */ \"./node_modules/netmask/lib/netmask.js\");\n\n\nconst PRIVATE_IP_RANGES = [\n '0.0.0.0/8',\n '10.0.0.0/8',\n '100.64.0.0/10',\n '127.0.0.0/8',\n '169.254.0.0/16',\n '172.16.0.0/12',\n '192.0.0.0/24',\n '192.0.0.0/29',\n '192.0.0.8/32',\n '192.0.0.9/32',\n '192.0.0.10/32',\n '192.0.0.170/32',\n '192.0.0.171/32',\n '192.0.2.0/24',\n '192.31.196.0/24',\n '192.52.193.0/24',\n '192.88.99.0/24',\n '192.168.0.0/16',\n '192.175.48.0/24',\n '198.18.0.0/15',\n '198.51.100.0/24',\n '203.0.113.0/24',\n '240.0.0.0/4',\n '255.255.255.255/32'\n];\nconst NETMASK_RANGES = PRIVATE_IP_RANGES.map(ipRange => new netmask__WEBPACK_IMPORTED_MODULE_1__.Netmask(ipRange));\nfunction ipv4Check(ipAddr) {\n for (const r of NETMASK_RANGES) {\n if (r.contains(ipAddr))\n return true;\n }\n return false;\n}\nfunction ipv6Check(ipAddr) {\n return /^::$/.test(ipAddr) ||\n /^::1$/.test(ipAddr) ||\n /^::f{4}:([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^::f{4}:0.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^64:ff9b::([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$/.test(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^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(ipAddr) ||\n /^f[c-d]([0-9a-fA-F]{2,2}):/i.test(ipAddr) ||\n /^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(ipAddr) ||\n /^ff([0-9a-fA-F]{2,2}):/i.test(ipAddr);\n}\nfunction isPrivateIp(ip) {\n if ((0,_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv4)(ip))\n return ipv4Check(ip);\n else if ((0,_chainsafe_is_ip__WEBPACK_IMPORTED_MODULE_0__.isIPv6)(ip))\n return ipv6Check(ip);\n else\n return undefined;\n}\n//# sourceMappingURL=private-ip.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/private-ip.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/index.js": -/*!***********************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/index.js ***! - \***********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Queue: () => (/* binding */ Queue)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var it_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-pushable */ \"./node_modules/it-pushable/dist/src/index.js\");\n/* harmony import */ var race_event__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! race-event */ \"./node_modules/race-event/dist/src/index.js\");\n/* harmony import */ var _job_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./job.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/job.js\");\n\n\n\n\n// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound\n// Used to compute insertion index to keep queue sorted after insertion\nfunction lowerBound(array, value, comparator) {\n let first = 0;\n let count = array.length;\n while (count > 0) {\n const step = Math.trunc(count / 2);\n let it = first + step;\n if (comparator(array[it], value) <= 0) {\n first = ++it;\n count -= step + 1;\n }\n else {\n count = step;\n }\n }\n return first;\n}\n/**\n * Heavily influence by `p-queue` with the following differences:\n *\n * 1. Items remain at the head of the queue while they are running so `queue.size` includes `queue.pending` items - this is so interested parties can join the results of a queue item while it is running\n * 2. The options for a job are stored separately to the job in order for them to be modified while they are still in the queue\n */\nclass Queue extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.TypedEventEmitter {\n concurrency;\n queue;\n pending;\n constructor(init = {}) {\n super();\n this.concurrency = init.concurrency ?? Number.POSITIVE_INFINITY;\n this.pending = 0;\n if (init.metricName != null) {\n init.metrics?.registerMetricGroup(init.metricName, {\n calculate: () => {\n return {\n size: this.queue.length,\n running: this.pending,\n queued: this.queue.length - this.pending\n };\n }\n });\n }\n this.queue = [];\n }\n tryToStartAnother() {\n if (this.size === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"empty\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('empty');\n });\n if (this.running === 0) {\n // do this in the microtask queue so all job recipients receive the\n // result before the \"idle\" event fires\n queueMicrotask(() => {\n this.safeDispatchEvent('idle');\n });\n }\n return false;\n }\n if (this.pending < this.concurrency) {\n let job;\n for (const j of this.queue) {\n if (j.status === 'queued') {\n job = j;\n break;\n }\n }\n if (job == null) {\n return false;\n }\n this.safeDispatchEvent('active');\n this.pending++;\n job.run()\n .finally(() => {\n // remove the job from the queue\n for (let i = 0; i < this.queue.length; i++) {\n if (this.queue[i] === job) {\n this.queue.splice(i, 1);\n break;\n }\n }\n this.pending--;\n this.tryToStartAnother();\n this.safeDispatchEvent('next');\n });\n return true;\n }\n return false;\n }\n enqueue(job) {\n if (this.queue[this.size - 1]?.priority >= job.priority) {\n this.queue.push(job);\n return;\n }\n const index = lowerBound(this.queue, job, (a, b) => b.priority - a.priority);\n this.queue.splice(index, 0, job);\n }\n /**\n * Adds a sync or async task to the queue. Always returns a promise.\n */\n async add(fn, options) {\n options?.signal?.throwIfAborted();\n const job = new _job_js__WEBPACK_IMPORTED_MODULE_3__.Job(fn, options, options?.priority);\n const p = job.join(options)\n .then(result => {\n this.safeDispatchEvent('completed', { detail: result });\n return result;\n })\n .catch(err => {\n this.safeDispatchEvent('error', { detail: err });\n throw err;\n });\n this.enqueue(job);\n this.safeDispatchEvent('add');\n this.tryToStartAnother();\n return p;\n }\n /**\n * Clear the queue\n */\n clear() {\n this.queue.splice(0, this.queue.length);\n }\n /**\n * Abort all jobs in the queue and clear it\n */\n abort() {\n this.queue.forEach(job => {\n job.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.AbortError());\n });\n this.clear();\n }\n /**\n * Can be called multiple times. Useful if you for example add additional items at a later time.\n *\n * @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty(options) {\n // Instantly resolve if the queue is empty\n if (this.size === 0) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'empty', options?.signal);\n }\n /**\n * @returns A promise that settles when the queue size is less than the given\n * limit: `queue.size < limit`.\n *\n * If you want to avoid having the queue grow beyond a certain size you can\n * `await queue.onSizeLessThan()` before adding a new item.\n *\n * Note that this only limits the number of items waiting to start. There\n * could still be up to `concurrency` jobs already running that this call does\n * not include in its calculation.\n */\n async onSizeLessThan(limit, options) {\n // Instantly resolve if the queue is empty.\n if (this.size < limit) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'next', options?.signal, {\n filter: () => this.size < limit\n });\n }\n /**\n * The difference with `.onEmpty` is that `.onIdle` guarantees that all work\n * from the queue has finished. `.onEmpty` merely signals that the queue is\n * empty, but it could mean that some promises haven't completed yet.\n *\n * @returns A promise that settles when the queue becomes empty, and all\n * promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle(options) {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.pending === 0 && this.size === 0) {\n return;\n }\n await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'idle', options?.signal);\n }\n /**\n * Size of the queue including running items\n */\n get size() {\n return this.queue.length;\n }\n /**\n * The number of queued items waiting to run.\n */\n get queued() {\n return this.queue.length - this.pending;\n }\n /**\n * The number of items currently running.\n */\n get running() {\n return this.pending;\n }\n /**\n * Returns an async generator that makes it easy to iterate over the results\n * of jobs added to the queue.\n *\n * The generator will end when the queue becomes idle, that is there are no\n * jobs running and no jobs that have yet to run.\n *\n * If you need to keep the queue open indefinitely, consider using it-pushable\n * instead.\n */\n async *toGenerator(options) {\n options?.signal?.throwIfAborted();\n const stream = (0,it_pushable__WEBPACK_IMPORTED_MODULE_0__.pushable)({\n objectMode: true\n });\n const cleanup = (err) => {\n if (err != null) {\n this.abort();\n }\n else {\n this.clear();\n }\n stream.end(err);\n };\n const onQueueJobComplete = (evt) => {\n if (evt.detail != null) {\n stream.push(evt.detail);\n }\n };\n const onQueueError = (evt) => {\n cleanup(evt.detail);\n };\n const onQueueIdle = () => {\n cleanup();\n };\n // clear the queue and throw if the query is aborted\n const onSignalAbort = () => {\n cleanup(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Queue aborted', 'ERR_QUEUE_ABORTED'));\n };\n // add listeners\n this.addEventListener('completed', onQueueJobComplete);\n this.addEventListener('error', onQueueError);\n this.addEventListener('idle', onQueueIdle);\n options?.signal?.addEventListener('abort', onSignalAbort);\n try {\n yield* stream;\n }\n finally {\n // remove listeners\n this.removeEventListener('completed', onQueueJobComplete);\n this.removeEventListener('error', onQueueError);\n this.removeEventListener('idle', onQueueIdle);\n options?.signal?.removeEventListener('abort', onSignalAbort);\n // empty the queue for when the user has broken out of a loop early\n cleanup();\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/index.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/job.js": -/*!*********************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/job.js ***! - \*********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Job: () => (/* binding */ Job)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var _recipient_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./recipient.js */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/recipient.js\");\n\n\n\n/**\n * Returns a random string\n */\nfunction randomId() {\n return `${(parseInt(String(Math.random() * 1e9), 10)).toString()}${Date.now()}`;\n}\nclass Job {\n id;\n fn;\n options;\n priority;\n recipients;\n status;\n timeline;\n controller;\n constructor(fn, options, priority = 0) {\n this.id = randomId();\n this.status = 'queued';\n this.fn = fn;\n this.priority = priority;\n this.options = options;\n this.recipients = [];\n this.timeline = {\n created: Date.now()\n };\n this.controller = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.setMaxListeners)(Infinity, this.controller.signal);\n this.onAbort = this.onAbort.bind(this);\n }\n abort(err) {\n this.controller.abort(err);\n }\n onAbort() {\n const allAborted = this.recipients.reduce((acc, curr) => {\n return acc && (curr.signal?.aborted === true);\n }, true);\n // if all recipients have aborted the job, actually abort the job\n if (allAborted) {\n this.controller.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.AbortError());\n }\n }\n async join(options = {}) {\n const recipient = new _recipient_js__WEBPACK_IMPORTED_MODULE_3__.JobRecipient((new Error('where')).stack, options.signal);\n this.recipients.push(recipient);\n options.signal?.addEventListener('abort', this.onAbort);\n return recipient.deferred.promise;\n }\n async run() {\n this.status = 'running';\n this.timeline.started = Date.now();\n try {\n this.controller.signal.throwIfAborted();\n const result = await (0,race_signal__WEBPACK_IMPORTED_MODULE_0__.raceSignal)(this.fn({\n ...(this.options ?? {}),\n signal: this.controller.signal\n }), this.controller.signal);\n this.recipients.forEach(recipient => {\n recipient.deferred.resolve(result);\n });\n this.status = 'complete';\n }\n catch (err) {\n this.recipients.forEach(recipient => {\n recipient.deferred.reject(err);\n });\n this.status = 'errored';\n }\n finally {\n this.timeline.finished = Date.now();\n this.cleanup();\n }\n }\n cleanup() {\n this.recipients.forEach(recipient => {\n recipient.signal?.removeEventListener('abort', this.onAbort);\n });\n }\n}\n//# sourceMappingURL=job.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/job.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/recipient.js": -/*!***************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/recipient.js ***! - \***************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ JobRecipient: () => (/* binding */ JobRecipient)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n\n\nclass JobRecipient {\n deferred;\n signal;\n where;\n constructor(where, signal) {\n this.signal = signal;\n this.deferred = (0,p_defer__WEBPACK_IMPORTED_MODULE_0__[\"default\"])();\n this.where = where;\n this.onAbort = this.onAbort.bind(this);\n this.signal?.addEventListener('abort', this.onAbort);\n }\n onAbort() {\n this.deferred.reject(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.AbortError());\n }\n cleanup() {\n this.signal?.removeEventListener('abort', this.onAbort);\n }\n}\n//# sourceMappingURL=recipient.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/recipient.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/rate-limiter.js": -/*!************************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/rate-limiter.js ***! - \************************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RateLimiter: () => (/* binding */ RateLimiter)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var delay__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! delay */ \"./node_modules/delay/index.js\");\n\n\nclass RateLimiter {\n memoryStorage;\n points;\n duration;\n blockDuration;\n execEvenly;\n execEvenlyMinDelayMs;\n keyPrefix;\n constructor(opts = {}) {\n this.points = opts.points ?? 4;\n this.duration = opts.duration ?? 1;\n this.blockDuration = opts.blockDuration ?? 0;\n this.execEvenly = opts.execEvenly ?? false;\n this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs ?? (this.duration * 1000 / this.points);\n this.keyPrefix = opts.keyPrefix ?? 'rlflx';\n this.memoryStorage = new MemoryStorage();\n }\n async consume(key, pointsToConsume = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n let res = this.memoryStorage.incrby(rlKey, pointsToConsume, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n if (res.consumedPoints > this.points) {\n // Block only first time when consumed more than points\n if (this.blockDuration > 0 && res.consumedPoints <= (this.points + pointsToConsume)) {\n // Block key\n res = this.memoryStorage.set(rlKey, res.consumedPoints, this.blockDuration);\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('Rate limit exceeded', 'ERR_RATE_LIMIT_EXCEEDED', res);\n }\n else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) {\n // Execute evenly\n let delayMs = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2));\n if (delayMs < this.execEvenlyMinDelayMs) {\n delayMs = res.consumedPoints * this.execEvenlyMinDelayMs;\n }\n await (0,delay__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(delayMs);\n }\n return res;\n }\n penalty(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n reward(key, points = 1, options = {}) {\n const rlKey = this.getKey(key);\n const secDuration = this._getKeySecDuration(options);\n const res = this.memoryStorage.incrby(rlKey, -points, secDuration);\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n return res;\n }\n /**\n * Block any key for secDuration seconds\n *\n * @param key\n * @param secDuration\n */\n block(key, secDuration) {\n const msDuration = secDuration * 1000;\n const initPoints = this.points + 1;\n this.memoryStorage.set(this.getKey(key), initPoints, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: initPoints,\n isFirstInDuration: false\n };\n }\n set(key, points, secDuration = 0) {\n const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000;\n this.memoryStorage.set(this.getKey(key), points, secDuration);\n return {\n remainingPoints: 0,\n msBeforeNext: msDuration === 0 ? -1 : msDuration,\n consumedPoints: points,\n isFirstInDuration: false\n };\n }\n get(key) {\n const res = this.memoryStorage.get(this.getKey(key));\n if (res != null) {\n res.remainingPoints = Math.max(this.points - res.consumedPoints, 0);\n }\n return res;\n }\n delete(key) {\n this.memoryStorage.delete(this.getKey(key));\n }\n _getKeySecDuration(options) {\n if (options?.customDuration != null && options.customDuration >= 0) {\n return options.customDuration;\n }\n return this.duration;\n }\n getKey(key) {\n return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key;\n }\n parseKey(rlKey) {\n return rlKey.substring(this.keyPrefix.length);\n }\n}\nclass MemoryStorage {\n storage;\n constructor() {\n this.storage = new Map();\n }\n incrby(key, value, durationSec) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n if (existing.expiresAt == null || msBeforeExpires > 0) {\n // Change value\n existing.value += value;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n return this.set(key, value, durationSec);\n }\n return this.set(key, value, durationSec);\n }\n set(key, value, durationSec) {\n const durationMs = durationSec * 1000;\n const existing = this.storage.get(key);\n if (existing != null) {\n clearTimeout(existing.timeoutId);\n }\n const record = {\n value,\n expiresAt: durationMs > 0 ? new Date(Date.now() + durationMs) : undefined\n };\n this.storage.set(key, record);\n if (durationMs > 0) {\n record.timeoutId = setTimeout(() => {\n this.storage.delete(key);\n }, durationMs);\n if (record.timeoutId.unref != null) {\n record.timeoutId.unref();\n }\n }\n return {\n remainingPoints: 0,\n msBeforeNext: durationMs === 0 ? -1 : durationMs,\n consumedPoints: record.value,\n isFirstInDuration: true\n };\n }\n get(key) {\n const existing = this.storage.get(key);\n if (existing != null) {\n const msBeforeExpires = existing.expiresAt != null\n ? existing.expiresAt.getTime() - new Date().getTime()\n : -1;\n return {\n remainingPoints: 0,\n msBeforeNext: msBeforeExpires,\n consumedPoints: existing.value,\n isFirstInDuration: false\n };\n }\n }\n delete(key) {\n const record = this.storage.get(key);\n if (record != null) {\n if (record.timeoutId != null) {\n clearTimeout(record.timeoutId);\n }\n this.storage.delete(key);\n return true;\n }\n return false;\n }\n}\n//# sourceMappingURL=rate-limiter.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/rate-limiter.js?"); - -/***/ }), - -/***/ "./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/tracked-map.js": -/*!***********************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/tracked-map.js ***! - \***********************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ trackedMap: () => (/* binding */ trackedMap)\n/* harmony export */ });\nclass TrackedMap extends Map {\n metric;\n constructor(init) {\n super();\n const { name, metrics } = init;\n this.metric = metrics.registerMetric(name);\n this.updateComponentMetric();\n }\n set(key, value) {\n super.set(key, value);\n this.updateComponentMetric();\n return this;\n }\n delete(key) {\n const deleted = super.delete(key);\n this.updateComponentMetric();\n return deleted;\n }\n clear() {\n super.clear();\n this.updateComponentMetric();\n }\n updateComponentMetric() {\n this.metric.update(this.size);\n }\n}\nfunction trackedMap(config) {\n const { name, metrics } = config;\n let map;\n if (metrics != null) {\n map = new TrackedMap({ name, metrics });\n }\n else {\n map = new Map();\n }\n return map;\n}\n//# sourceMappingURL=tracked-map.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/tracked-map.js?"); - -/***/ }), - /***/ "./node_modules/@waku/sdk/node_modules/@waku/core/dist/index.js": /*!**********************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@waku/core/dist/index.js ***! @@ -11304,7 +15978,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FilterCodecs: () => (/* binding */ FilterCodecs),\n/* harmony export */ wakuFilter: () => (/* binding */ wakuFilter)\n/* harmony export */ });\n/* harmony import */ var _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/interfaces */ \"./node_modules/@waku/sdk/node_modules/@waku/interfaces/dist/index.js\");\n/* harmony import */ var _waku_message_hash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @waku/message-hash */ \"./node_modules/@waku/sdk/node_modules/@waku/message-hash/dist/index.js\");\n/* harmony import */ var _waku_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @waku/utils */ \"./node_modules/@waku/utils/dist/index.js\");\n/* harmony import */ var it_all__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! it-all */ \"./node_modules/it-all/dist/src/index.js\");\n/* harmony import */ var it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! it-length-prefixed */ \"./node_modules/it-length-prefixed/dist/src/index.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var _base_protocol_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../base_protocol.js */ \"./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/base_protocol.js\");\n/* harmony import */ var _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./filter_rpc.js */ \"./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/filter_rpc.js\");\n\n\n\n\n\n\n\n\n\nconst log = new _waku_utils__WEBPACK_IMPORTED_MODULE_2__.Logger(\"filter:v2\");\nconst FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\n/**\n * A subscription object refers to a subscription to a given pubsub topic.\n */\nclass Subscription {\n peers;\n pubsubTopic;\n newStream;\n receivedMessagesHashStr = [];\n subscriptionCallbacks;\n constructor(pubsubTopic, remotePeers, newStream) {\n this.peers = remotePeers;\n this.pubsubTopic = pubsubTopic;\n this.newStream = newStream;\n this.subscriptionCallbacks = new Map();\n }\n async subscribe(decoders, callback) {\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n // check that all decoders are configured for the same pubsub topic as this subscription\n decodersArray.forEach((decoder) => {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n throw new Error(`Pubsub topic not configured: decoder is configured for pubsub topic ${decoder.pubsubTopic} but this subscription is for pubsub topic ${this.pubsubTopic}. Please create a new Subscription for the different pubsub topic.`);\n }\n });\n const decodersGroupedByCT = (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.groupByContentTopic)(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createSubscribeRequest(this.pubsubTopic, contentTopics);\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n log.info(\"Subscribed to peer \", peer.id.toString(), \"for content topics\", contentTopics);\n }\n catch (e) {\n throw new Error(\"Error subscribing to peer: \" +\n peer.id.toString() +\n \" for content topics: \" +\n contentTopics +\n \": \" +\n e);\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"subscribe\");\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n };\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n }\n async unsubscribe(contentTopics) {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const unsubscribeRequest = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createUnsubscribeRequest(this.pubsubTopic, contentTopics);\n try {\n await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([unsubscribeRequest.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream.sink);\n }\n catch (error) {\n throw new Error(\"Error unsubscribing: \" + error);\n }\n contentTopics.forEach((contentTopic) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"unsubscribe\");\n }\n async ping() {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createSubscriberPingRequest();\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n log.info(`Ping successful for peer ${peer.id.toString()}`);\n }\n catch (error) {\n log.error(\"Error pinging: \", error);\n throw error; // Rethrow the actual error instead of wrapping it\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"ping\");\n }\n async unsubscribeAll() {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createUnsubscribeAllRequest(this.pubsubTopic);\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n this.subscriptionCallbacks.clear();\n log.info(`Unsubscribed from all content topics for pubsub topic ${this.pubsubTopic}`);\n }\n catch (error) {\n throw new Error(\"Error unsubscribing from all content topics: \" + error);\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"unsubscribeAll\");\n }\n async processMessage(message) {\n const hashedMessageStr = (0,_waku_message_hash__WEBPACK_IMPORTED_MODULE_1__.messageHashStr)(this.pubsubTopic, message);\n if (this.receivedMessagesHashStr.includes(hashedMessageStr)) {\n log.info(\"Message already received, skipping\");\n return;\n }\n this.receivedMessagesHashStr.push(hashedMessageStr);\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\"Processing message with content topic \", contentTopic, \" on pubsub topic \", this.pubsubTopic);\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n // Filter out only the rejected promises and extract & handle their reasons\n handleErrors(results, type) {\n const errors = results\n .filter((result) => result.status === \"rejected\")\n .map((rejectedResult) => rejectedResult.reason);\n if (errors.length === this.peers.length) {\n const errorCounts = new Map();\n // TODO: streamline error logging with https://github.com/orgs/waku-org/projects/2/views/1?pane=issue&itemId=42849952\n errors.forEach((error) => {\n const message = error instanceof Error ? error.message : String(error);\n errorCounts.set(message, (errorCounts.get(message) || 0) + 1);\n });\n const uniqueErrorMessages = Array.from(errorCounts, ([message, count]) => `${message} (occurred ${count} times)`).join(\", \");\n throw new Error(`Error ${type} all peers: ${uniqueErrorMessages}`);\n }\n else if (errors.length > 0) {\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n log.warn(`Some ${type} failed. These will be refreshed with new peers`, errors);\n }\n else {\n log.info(`${type} successful for all peers`);\n }\n }\n}\nconst DEFAULT_NUM_PEERS = 3;\nclass Filter extends _base_protocol_js__WEBPACK_IMPORTED_MODULE_6__.BaseProtocol {\n activeSubscriptions = new Map();\n getActiveSubscription(pubsubTopic) {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n setActiveSubscription(pubsubTopic, subscription) {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n //TODO: Remove when FilterCore and FilterSDK are introduced\n numPeersToUse;\n constructor(libp2p, options) {\n super(FilterCodecs.SUBSCRIBE, libp2p.components, log, options.pubsubTopics, options);\n this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS;\n libp2p.handle(FilterCodecs.PUSH, this.onRequest.bind(this)).catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n this.activeSubscriptions = new Map();\n }\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(pubsubTopicShardInfo = _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DefaultPubsubTopic) {\n const pubsubTopic = typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.singleShardInfoToPubsubTopic)(pubsubTopicShardInfo);\n (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.ensurePubsubTopicIsConfigured)(pubsubTopic, this.pubsubTopics);\n const peers = await this.getPeers({\n maxBootstrapPeers: 1,\n numPeers: this.numPeersToUse\n });\n if (peers.length === 0) {\n throw new Error(\"No peer found to initiate subscription.\");\n }\n log.info(`Creating filter subscription with ${peers.length} peers: `, peers.map((peer) => peer.id.toString()));\n const subscription = this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(pubsubTopic, new Subscription(pubsubTopic, peers, this.getStream.bind(this)));\n return subscription;\n }\n toSubscriptionIterator(decoders) {\n return (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.toAsyncIterator)(this, decoders);\n }\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribe(decoders, callback) {\n const subscription = await this.createSubscription();\n await subscription.subscribe(decoders, callback);\n const contentTopics = Array.from((0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.groupByContentTopic)(Array.isArray(decoders) ? decoders : [decoders]).keys());\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n onRequest(streamData) {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)(stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => {\n for await (const bytes of source) {\n const response = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterPushRpc.decode(bytes.slice());\n const { pubsubTopic, wakuMessage } = response;\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n const subscription = this.getActiveSubscription(pubsubTopic);\n if (!subscription) {\n log.error(`No subscription locally registered for topic ${pubsubTopic}`);\n return;\n }\n await subscription.processMessage(wakuMessage);\n }\n }).then(() => {\n log.info(\"Receiving pipe closed.\");\n }, (e) => {\n log.error(\"Error with receiving pipe\", e);\n });\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n}\nfunction wakuFilter(init = { pubsubTopics: [] }) {\n return (libp2p) => new Filter(libp2p, init);\n}\nasync function pushMessage(subscriptionCallback, pubsubTopic, message) {\n const { decoders, callback } = subscriptionCallback;\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n try {\n const decodePromises = decoders.map((dec) => dec\n .fromProtoObj(pubsubTopic, message)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\")));\n const decodedMessage = await Promise.any(decodePromises);\n await callback(decodedMessage);\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ FilterCodecs: () => (/* binding */ FilterCodecs),\n/* harmony export */ wakuFilter: () => (/* binding */ wakuFilter)\n/* harmony export */ });\n/* harmony import */ var _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/interfaces */ \"./node_modules/@waku/sdk/node_modules/@waku/interfaces/dist/index.js\");\n/* harmony import */ var _waku_message_hash__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @waku/message-hash */ \"./node_modules/@waku/message-hash/dist/index.js\");\n/* harmony import */ var _waku_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @waku/utils */ \"./node_modules/@waku/utils/dist/index.js\");\n/* harmony import */ var it_all__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! it-all */ \"./node_modules/it-all/dist/src/index.js\");\n/* harmony import */ var it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! it-length-prefixed */ \"./node_modules/it-length-prefixed/dist/src/index.js\");\n/* harmony import */ var it_pipe__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! it-pipe */ \"./node_modules/it-pipe/dist/src/index.js\");\n/* harmony import */ var _base_protocol_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../base_protocol.js */ \"./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/base_protocol.js\");\n/* harmony import */ var _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./filter_rpc.js */ \"./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/filter_rpc.js\");\n\n\n\n\n\n\n\n\n\nconst log = new _waku_utils__WEBPACK_IMPORTED_MODULE_2__.Logger(\"filter:v2\");\nconst FilterCodecs = {\n SUBSCRIBE: \"/vac/waku/filter-subscribe/2.0.0-beta1\",\n PUSH: \"/vac/waku/filter-push/2.0.0-beta1\"\n};\n/**\n * A subscription object refers to a subscription to a given pubsub topic.\n */\nclass Subscription {\n peers;\n pubsubTopic;\n newStream;\n receivedMessagesHashStr = [];\n subscriptionCallbacks;\n constructor(pubsubTopic, remotePeers, newStream) {\n this.peers = remotePeers;\n this.pubsubTopic = pubsubTopic;\n this.newStream = newStream;\n this.subscriptionCallbacks = new Map();\n }\n async subscribe(decoders, callback) {\n const decodersArray = Array.isArray(decoders) ? decoders : [decoders];\n // check that all decoders are configured for the same pubsub topic as this subscription\n decodersArray.forEach((decoder) => {\n if (decoder.pubsubTopic !== this.pubsubTopic) {\n throw new Error(`Pubsub topic not configured: decoder is configured for pubsub topic ${decoder.pubsubTopic} but this subscription is for pubsub topic ${this.pubsubTopic}. Please create a new Subscription for the different pubsub topic.`);\n }\n });\n const decodersGroupedByCT = (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.groupByContentTopic)(decodersArray);\n const contentTopics = Array.from(decodersGroupedByCT.keys());\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createSubscribeRequest(this.pubsubTopic, contentTopics);\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n log.info(\"Subscribed to peer \", peer.id.toString(), \"for content topics\", contentTopics);\n }\n catch (e) {\n throw new Error(\"Error subscribing to peer: \" +\n peer.id.toString() +\n \" for content topics: \" +\n contentTopics +\n \": \" +\n e);\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"subscribe\");\n // Save the callback functions by content topics so they\n // can easily be removed (reciprocally replaced) if `unsubscribe` (reciprocally `subscribe`)\n // is called for those content topics\n decodersGroupedByCT.forEach((decoders, contentTopic) => {\n // Cast the type because a given `subscriptionCallbacks` map may hold\n // Decoder that decode to different implementations of `IDecodedMessage`\n const subscriptionCallback = {\n decoders,\n callback\n };\n // The callback and decoder may override previous values, this is on\n // purpose as the user may call `subscribe` to refresh the subscription\n this.subscriptionCallbacks.set(contentTopic, subscriptionCallback);\n });\n }\n async unsubscribe(contentTopics) {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const unsubscribeRequest = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createUnsubscribeRequest(this.pubsubTopic, contentTopics);\n try {\n await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([unsubscribeRequest.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream.sink);\n }\n catch (error) {\n throw new Error(\"Error unsubscribing: \" + error);\n }\n contentTopics.forEach((contentTopic) => {\n this.subscriptionCallbacks.delete(contentTopic);\n });\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"unsubscribe\");\n }\n async ping() {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createSubscriberPingRequest();\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n log.info(`Ping successful for peer ${peer.id.toString()}`);\n }\n catch (error) {\n log.error(\"Error pinging: \", error);\n throw error; // Rethrow the actual error instead of wrapping it\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"ping\");\n }\n async unsubscribeAll() {\n const promises = this.peers.map(async (peer) => {\n const stream = await this.newStream(peer);\n const request = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeRpc.createUnsubscribeAllRequest(this.pubsubTopic);\n try {\n const res = await (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)([request.encode()], it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.encode, stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => await (0,it_all__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(source));\n if (!res || !res.length) {\n throw Error(`No response received for request ${request.requestId}: ${res}`);\n }\n const { statusCode, requestId, statusDesc } = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterSubscribeResponse.decode(res[0].slice());\n if (statusCode < 200 || statusCode >= 300) {\n throw new Error(`Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`);\n }\n this.subscriptionCallbacks.clear();\n log.info(`Unsubscribed from all content topics for pubsub topic ${this.pubsubTopic}`);\n }\n catch (error) {\n throw new Error(\"Error unsubscribing from all content topics: \" + error);\n }\n });\n const results = await Promise.allSettled(promises);\n this.handleErrors(results, \"unsubscribeAll\");\n }\n async processMessage(message) {\n const hashedMessageStr = (0,_waku_message_hash__WEBPACK_IMPORTED_MODULE_1__.messageHashStr)(this.pubsubTopic, message);\n if (this.receivedMessagesHashStr.includes(hashedMessageStr)) {\n log.info(\"Message already received, skipping\");\n return;\n }\n this.receivedMessagesHashStr.push(hashedMessageStr);\n const { contentTopic } = message;\n const subscriptionCallback = this.subscriptionCallbacks.get(contentTopic);\n if (!subscriptionCallback) {\n log.error(\"No subscription callback available for \", contentTopic);\n return;\n }\n log.info(\"Processing message with content topic \", contentTopic, \" on pubsub topic \", this.pubsubTopic);\n await pushMessage(subscriptionCallback, this.pubsubTopic, message);\n }\n // Filter out only the rejected promises and extract & handle their reasons\n handleErrors(results, type) {\n const errors = results\n .filter((result) => result.status === \"rejected\")\n .map((rejectedResult) => rejectedResult.reason);\n if (errors.length === this.peers.length) {\n const errorCounts = new Map();\n // TODO: streamline error logging with https://github.com/orgs/waku-org/projects/2/views/1?pane=issue&itemId=42849952\n errors.forEach((error) => {\n const message = error instanceof Error ? error.message : String(error);\n errorCounts.set(message, (errorCounts.get(message) || 0) + 1);\n });\n const uniqueErrorMessages = Array.from(errorCounts, ([message, count]) => `${message} (occurred ${count} times)`).join(\", \");\n throw new Error(`Error ${type} all peers: ${uniqueErrorMessages}`);\n }\n else if (errors.length > 0) {\n // TODO: handle renewing faulty peers with new peers (https://github.com/waku-org/js-waku/issues/1463)\n log.warn(`Some ${type} failed. These will be refreshed with new peers`, errors);\n }\n else {\n log.info(`${type} successful for all peers`);\n }\n }\n}\nconst DEFAULT_NUM_PEERS = 3;\nclass Filter extends _base_protocol_js__WEBPACK_IMPORTED_MODULE_6__.BaseProtocol {\n activeSubscriptions = new Map();\n getActiveSubscription(pubsubTopic) {\n return this.activeSubscriptions.get(pubsubTopic);\n }\n setActiveSubscription(pubsubTopic, subscription) {\n this.activeSubscriptions.set(pubsubTopic, subscription);\n return subscription;\n }\n //TODO: Remove when FilterCore and FilterSDK are introduced\n numPeersToUse;\n constructor(libp2p, options) {\n super(FilterCodecs.SUBSCRIBE, libp2p.components, log, options.pubsubTopics, options);\n this.numPeersToUse = options?.numPeersToUse ?? DEFAULT_NUM_PEERS;\n libp2p.handle(FilterCodecs.PUSH, this.onRequest.bind(this)).catch((e) => {\n log.error(\"Failed to register \", FilterCodecs.PUSH, e);\n });\n this.activeSubscriptions = new Map();\n }\n /**\n * Creates a new subscription to the given pubsub topic.\n * The subscription is made to multiple peers for decentralization.\n * @param pubsubTopicShardInfo The pubsub topic to subscribe to.\n * @returns The subscription object.\n */\n async createSubscription(pubsubTopicShardInfo = _waku_interfaces__WEBPACK_IMPORTED_MODULE_0__.DefaultPubsubTopic) {\n const pubsubTopic = typeof pubsubTopicShardInfo == \"string\"\n ? pubsubTopicShardInfo\n : (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.singleShardInfoToPubsubTopic)(pubsubTopicShardInfo);\n (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.ensurePubsubTopicIsConfigured)(pubsubTopic, this.pubsubTopics);\n const peers = await this.getPeers({\n maxBootstrapPeers: 1,\n numPeers: this.numPeersToUse\n });\n if (peers.length === 0) {\n throw new Error(\"No peer found to initiate subscription.\");\n }\n log.info(`Creating filter subscription with ${peers.length} peers: `, peers.map((peer) => peer.id.toString()));\n const subscription = this.getActiveSubscription(pubsubTopic) ??\n this.setActiveSubscription(pubsubTopic, new Subscription(pubsubTopic, peers, this.getStream.bind(this)));\n return subscription;\n }\n toSubscriptionIterator(decoders) {\n return (0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.toAsyncIterator)(this, decoders);\n }\n /**\n * This method is used to satisfy the `IReceiver` interface.\n *\n * @hidden\n *\n * @param decoders The decoders to use for the subscription.\n * @param callback The callback function to use for the subscription.\n * @param opts Optional protocol options for the subscription.\n *\n * @returns A Promise that resolves to a function that unsubscribes from the subscription.\n *\n * @remarks\n * This method should not be used directly.\n * Instead, use `createSubscription` to create a new subscription.\n */\n async subscribe(decoders, callback) {\n const subscription = await this.createSubscription();\n await subscription.subscribe(decoders, callback);\n const contentTopics = Array.from((0,_waku_utils__WEBPACK_IMPORTED_MODULE_2__.groupByContentTopic)(Array.isArray(decoders) ? decoders : [decoders]).keys());\n return async () => {\n await subscription.unsubscribe(contentTopics);\n };\n }\n onRequest(streamData) {\n const { connection, stream } = streamData;\n const { remotePeer } = connection;\n log.info(`Received message from ${remotePeer.toString()}`);\n try {\n (0,it_pipe__WEBPACK_IMPORTED_MODULE_5__.pipe)(stream, it_length_prefixed__WEBPACK_IMPORTED_MODULE_4__.decode, async (source) => {\n for await (const bytes of source) {\n const response = _filter_rpc_js__WEBPACK_IMPORTED_MODULE_7__.FilterPushRpc.decode(bytes.slice());\n const { pubsubTopic, wakuMessage } = response;\n if (!wakuMessage) {\n log.error(\"Received empty message\");\n return;\n }\n if (!pubsubTopic) {\n log.error(\"Pubsub topic missing from push message\");\n return;\n }\n const subscription = this.getActiveSubscription(pubsubTopic);\n if (!subscription) {\n log.error(`No subscription locally registered for topic ${pubsubTopic}`);\n return;\n }\n await subscription.processMessage(wakuMessage);\n }\n }).then(() => {\n log.info(\"Receiving pipe closed.\");\n }, (e) => {\n log.error(\"Error with receiving pipe\", e);\n });\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n }\n}\nfunction wakuFilter(init = { pubsubTopics: [] }) {\n return (libp2p) => new Filter(libp2p, init);\n}\nasync function pushMessage(subscriptionCallback, pubsubTopic, message) {\n const { decoders, callback } = subscriptionCallback;\n const { contentTopic } = message;\n if (!contentTopic) {\n log.warn(\"Message has no content topic, skipping\");\n return;\n }\n try {\n const decodePromises = decoders.map((dec) => dec\n .fromProtoObj(pubsubTopic, message)\n .then((decoded) => decoded || Promise.reject(\"Decoding failed\")));\n const decodedMessage = await Promise.any(decodePromises);\n await callback(decodedMessage);\n }\n catch (e) {\n log.error(\"Error decoding message\", e);\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@waku/core/dist/lib/filter/index.js?"); /***/ }), @@ -11924,17 +16598,6 @@ eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=waku.j /***/ }), -/***/ "./node_modules/@waku/sdk/node_modules/@waku/message-hash/dist/index.js": -/*!******************************************************************************!*\ - !*** ./node_modules/@waku/sdk/node_modules/@waku/message-hash/dist/index.js ***! - \******************************************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ messageHash: () => (/* binding */ messageHash),\n/* harmony export */ messageHashStr: () => (/* binding */ messageHashStr)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/sha256 */ \"./node_modules/@noble/hashes/esm/sha256.js\");\n/* harmony import */ var _waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @waku/utils/bytes */ \"./node_modules/@waku/utils/dist/bytes/index.js\");\n\n\n/**\n * Deterministic Message Hashing as defined in\n * [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)\n */\nfunction messageHash(pubsubTopic, message) {\n const pubsubTopicBytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(pubsubTopic);\n const contentTopicBytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__.utf8ToBytes)(message.contentTopic);\n let bytes;\n if (message.meta) {\n bytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__.concat)([\n pubsubTopicBytes,\n message.payload,\n contentTopicBytes,\n message.meta\n ]);\n }\n else {\n bytes = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__.concat)([pubsubTopicBytes, message.payload, contentTopicBytes]);\n }\n return (0,_noble_hashes_sha256__WEBPACK_IMPORTED_MODULE_1__.sha256)(bytes);\n}\nfunction messageHashStr(pubsubTopic, message) {\n const hash = messageHash(pubsubTopic, message);\n const hashStr = (0,_waku_utils_bytes__WEBPACK_IMPORTED_MODULE_0__.bytesToUtf8)(hash);\n return hashStr;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/@waku/message-hash/dist/index.js?"); - -/***/ }), - /***/ "./node_modules/@waku/sdk/node_modules/@waku/proto/dist/index.js": /*!***********************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/@waku/proto/dist/index.js ***! @@ -12041,7 +16704,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultAddressManager: () => (/* binding */ DefaultAddressManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/utils.js\");\n\n\n\nconst defaultAddressFilter = (addrs) => addrs;\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId(ma, peerId) {\n const observedPeerIdStr = ma.getPeerId();\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(observedPeerIdStr);\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(`/p2p/${peerId.toString()}`));\n }\n }\n return ma;\n}\nclass DefaultAddressManager {\n log;\n components;\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n listen;\n announce;\n observed;\n announceFilter;\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor(components, init = {}) {\n const { listen = [], announce = [] } = init;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:address-manager');\n this.listen = listen.map(ma => ma.toString());\n this.announce = new Set(announce.map(ma => ma.toString()));\n this.observed = new Map();\n this.announceFilter = init.announceFilter ?? defaultAddressFilter;\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.debounce)(this._updatePeerStoreAddresses.bind(this), 1000);\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses();\n });\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses();\n });\n }\n _updatePeerStoreAddresses() {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat([...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(str))).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`);\n }\n return ma;\n });\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err); });\n }\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs() {\n return Array.from(this.listen).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs() {\n return Array.from(this.announce).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs() {\n return Array.from(this.observed).map(([a]) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Add peer observed addresses\n */\n addObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return;\n }\n this.observed.set(addrString, {\n confident: false\n });\n }\n confirmObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n };\n const startingConfidence = metadata.confident;\n this.observed.set(addrString, {\n confident: true\n });\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses();\n }\n }\n removeObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n this.observed.delete(addrString);\n }\n getAddresses() {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString());\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString());\n }\n // add observed addresses we are confident in\n addrs = addrs.concat(Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma));\n // dedupe multiaddrs\n const addrSet = new Set(addrs);\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma;\n }\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma;\n }\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`);\n });\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultAddressManager: () => (/* binding */ DefaultAddressManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/utils.js\");\n\n\n\nconst defaultAddressFilter = (addrs) => addrs;\n/**\n * If the passed multiaddr contains the passed peer id, remove it\n */\nfunction stripPeerId(ma, peerId) {\n const observedPeerIdStr = ma.getPeerId();\n // strip our peer id if it has been passed\n if (observedPeerIdStr != null) {\n const observedPeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_1__.peerIdFromString)(observedPeerIdStr);\n // use same encoding for comparison\n if (observedPeerId.equals(peerId)) {\n ma = ma.decapsulate((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(`/p2p/${peerId.toString()}`));\n }\n }\n return ma;\n}\nclass DefaultAddressManager {\n log;\n components;\n // this is an array to allow for duplicates, e.g. multiples of `/ip4/0.0.0.0/tcp/0`\n listen;\n announce;\n observed;\n announceFilter;\n /**\n * Responsible for managing the peer addresses.\n * Peers can specify their listen and announce addresses.\n * The listen addresses will be used by the libp2p transports to listen for new connections,\n * while the announce addresses will be used for the peer addresses' to other peers in the network.\n */\n constructor(components, init = {}) {\n const { listen = [], announce = [] } = init;\n this.components = components;\n this.log = components.logger.forComponent('libp2p:address-manager');\n this.listen = listen.map(ma => ma.toString());\n this.announce = new Set(announce.map(ma => ma.toString()));\n this.observed = new Map();\n this.announceFilter = init.announceFilter ?? defaultAddressFilter;\n // this method gets called repeatedly on startup when transports start listening so\n // debounce it so we don't cause multiple self:peer:update events to be emitted\n this._updatePeerStoreAddresses = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.debounce)(this._updatePeerStoreAddresses.bind(this), 1000);\n // update our stored addresses when new transports listen\n components.events.addEventListener('transport:listening', () => {\n this._updatePeerStoreAddresses();\n });\n // update our stored addresses when existing transports stop listening\n components.events.addEventListener('transport:close', () => {\n this._updatePeerStoreAddresses();\n });\n }\n [Symbol.toStringTag] = '@libp2p/address-manager';\n _updatePeerStoreAddresses() {\n // if announce addresses have been configured, ensure they make it into our peer\n // record for things like identify\n const addrs = this.getAnnounceAddrs()\n .concat(this.components.transportManager.getAddrs())\n .concat([...this.observed.entries()]\n .filter(([_, metadata]) => metadata.confident)\n .map(([str]) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(str))).map(ma => {\n // strip our peer id if it is present\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma.decapsulate(`/p2p/${this.components.peerId.toString()}`);\n }\n return ma;\n });\n this.components.peerStore.patch(this.components.peerId, {\n multiaddrs: addrs\n })\n .catch(err => { this.log.error('error updating addresses', err); });\n }\n /**\n * Get peer listen multiaddrs\n */\n getListenAddrs() {\n return Array.from(this.listen).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Get peer announcing multiaddrs\n */\n getAnnounceAddrs() {\n return Array.from(this.announce).map((a) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Get observed multiaddrs\n */\n getObservedAddrs() {\n return Array.from(this.observed).map(([a]) => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(a));\n }\n /**\n * Add peer observed addresses\n */\n addObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n // do not trigger the change:addresses event if we already know about this address\n if (this.observed.has(addrString)) {\n return;\n }\n this.observed.set(addrString, {\n confident: false\n });\n }\n confirmObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n const metadata = this.observed.get(addrString) ?? {\n confident: false\n };\n const startingConfidence = metadata.confident;\n this.observed.set(addrString, {\n confident: true\n });\n // only trigger the 'self:peer:update' event if our confidence in an address has changed\n if (!startingConfidence) {\n this._updatePeerStoreAddresses();\n }\n }\n removeObservedAddr(addr) {\n addr = stripPeerId(addr, this.components.peerId);\n const addrString = addr.toString();\n this.observed.delete(addrString);\n }\n getAddresses() {\n let addrs = this.getAnnounceAddrs().map(ma => ma.toString());\n if (addrs.length === 0) {\n // no configured announce addrs, add configured listen addresses\n addrs = this.components.transportManager.getAddrs().map(ma => ma.toString());\n }\n // add observed addresses we are confident in\n addrs = addrs.concat(Array.from(this.observed)\n .filter(([ma, metadata]) => metadata.confident)\n .map(([ma]) => ma));\n // dedupe multiaddrs\n const addrSet = new Set(addrs);\n // Create advertising list\n return this.announceFilter(Array.from(addrSet)\n .map(str => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(str)))\n .map(ma => {\n // do not append our peer id to a path multiaddr as it will become invalid\n if (ma.protos().pop()?.path === true) {\n return ma;\n }\n if (ma.getPeerId() === this.components.peerId.toString()) {\n return ma;\n }\n return ma.encapsulate(`/p2p/${this.components.peerId.toString()}`);\n });\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/index.js?"); /***/ }), @@ -12063,7 +16726,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ defaultComponents: () => (/* binding */ defaultComponents)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/startable.js\");\n/* harmony import */ var _libp2p_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/logger */ \"./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/index.js\");\n\n\n\nclass DefaultComponents {\n components = {};\n _started = false;\n constructor(init = {}) {\n this.components = {};\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value;\n }\n if (this.components.logger == null) {\n this.components.logger = (0,_libp2p_logger__WEBPACK_IMPORTED_MODULE_0__.defaultLogger)();\n }\n }\n isStarted() {\n return this._started;\n }\n async _invokeStartableMethod(methodName) {\n await Promise.all(Object.values(this.components)\n .filter(obj => (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.isStartable)(obj))\n .map(async (startable) => {\n await startable[methodName]?.();\n }));\n }\n async beforeStart() {\n await this._invokeStartableMethod('beforeStart');\n }\n async start() {\n await this._invokeStartableMethod('start');\n this._started = true;\n }\n async afterStart() {\n await this._invokeStartableMethod('afterStart');\n }\n async beforeStop() {\n await this._invokeStartableMethod('beforeStop');\n }\n async stop() {\n await this._invokeStartableMethod('stop');\n this._started = false;\n }\n async afterStop() {\n await this._invokeStartableMethod('afterStop');\n }\n}\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n];\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n];\nfunction defaultComponents(init = {}) {\n const components = new DefaultComponents(init);\n const proxy = new Proxy(components, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop];\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`${prop} not set`, 'ERR_SERVICE_MISSING');\n }\n return service;\n }\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value;\n }\n else {\n Reflect.set(target, prop, value);\n }\n return true;\n }\n });\n // @ts-expect-error component keys are proxied\n return proxy;\n}\n//# sourceMappingURL=components.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/components.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ checkServiceDependencies: () => (/* binding */ checkServiceDependencies),\n/* harmony export */ defaultComponents: () => (/* binding */ defaultComponents)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/startable.js\");\n/* harmony import */ var _libp2p_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/logger */ \"./node_modules/@libp2p/logger/dist/src/index.js\");\n\n\n\nclass DefaultComponents {\n components = {};\n _started = false;\n constructor(init = {}) {\n this.components = {};\n for (const [key, value] of Object.entries(init)) {\n this.components[key] = value;\n }\n if (this.components.logger == null) {\n this.components.logger = (0,_libp2p_logger__WEBPACK_IMPORTED_MODULE_0__.defaultLogger)();\n }\n }\n isStarted() {\n return this._started;\n }\n async _invokeStartableMethod(methodName) {\n await Promise.all(Object.values(this.components)\n .filter(obj => (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.isStartable)(obj))\n .map(async (startable) => {\n await startable[methodName]?.();\n }));\n }\n async beforeStart() {\n await this._invokeStartableMethod('beforeStart');\n }\n async start() {\n await this._invokeStartableMethod('start');\n this._started = true;\n }\n async afterStart() {\n await this._invokeStartableMethod('afterStart');\n }\n async beforeStop() {\n await this._invokeStartableMethod('beforeStop');\n }\n async stop() {\n await this._invokeStartableMethod('stop');\n this._started = false;\n }\n async afterStop() {\n await this._invokeStartableMethod('afterStop');\n }\n}\nconst OPTIONAL_SERVICES = [\n 'metrics',\n 'connectionProtector',\n 'dns'\n];\nconst NON_SERVICE_PROPERTIES = [\n 'components',\n 'isStarted',\n 'beforeStart',\n 'start',\n 'afterStart',\n 'beforeStop',\n 'stop',\n 'afterStop',\n 'then',\n '_invokeStartableMethod'\n];\nfunction defaultComponents(init = {}) {\n const components = new DefaultComponents(init);\n const proxy = new Proxy(components, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && !NON_SERVICE_PROPERTIES.includes(prop)) {\n const service = components.components[prop];\n if (service == null && !OPTIONAL_SERVICES.includes(prop)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`${prop} not set`, 'ERR_SERVICE_MISSING');\n }\n return service;\n }\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value) {\n if (typeof prop === 'string') {\n components.components[prop] = value;\n }\n else {\n Reflect.set(target, prop, value);\n }\n return true;\n }\n });\n // @ts-expect-error component keys are proxied\n return proxy;\n}\nfunction checkServiceDependencies(components) {\n const serviceCapabilities = {};\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceCapabilities(service)) {\n serviceCapabilities[capability] = true;\n }\n }\n for (const service of Object.values(components.components)) {\n for (const capability of getServiceDependencies(service)) {\n if (serviceCapabilities[capability] !== true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`Service \"${getServiceName(service)}\" required capability \"${capability}\" but it was not provided by any component, you may need to add additional configuration when creating your node.`, 'ERR_UNMET_SERVICE_DEPENDENCIES');\n }\n }\n }\n}\nfunction getServiceCapabilities(service) {\n if (Array.isArray(service?.[_libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.serviceCapabilities])) {\n return service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.serviceCapabilities];\n }\n return [];\n}\nfunction getServiceDependencies(service) {\n if (Array.isArray(service?.[_libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.serviceDependencies])) {\n return service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.serviceDependencies];\n }\n return [];\n}\nfunction getServiceName(service) {\n return service?.[Symbol.toStringTag] ?? service?.toString() ?? 'unknown';\n}\n//# sourceMappingURL=components.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/components.js?"); /***/ }), @@ -12074,7 +16737,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ validateConfig: () => (/* binding */ validateConfig)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var merge_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! merge-options */ \"./node_modules/merge-options/index.mjs\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n\n\nconst DefaultConfig = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_0__.dnsaddrResolver\n },\n addressSorter: _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_2__.defaultAddressSort\n },\n transportManager: {\n faultTolerance: _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.FaultTolerance.FATAL_ALL\n }\n};\nasync function validateConfig(opts) {\n const resultingOptions = (0,merge_options__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(DefaultConfig, opts);\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_5__.messages.ERR_PROTECTOR_REQUIRED, _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_PROTECTOR_REQUIRED);\n }\n if (!(await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__.peerIdFromKeys)(resultingOptions.privateKey.public.bytes, resultingOptions.privateKey.bytes)).equals(resultingOptions.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Private key doesn\\'t match peer id', _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_INVALID_KEY);\n }\n return resultingOptions;\n}\n//# sourceMappingURL=config.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ validateConfig: () => (/* binding */ validateConfig)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var merge_options__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! merge-options */ \"./node_modules/merge-options/index.mjs\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n\n\nconst DefaultConfig = {\n addresses: {\n listen: [],\n announce: [],\n noAnnounce: [],\n announceFilter: (multiaddrs) => multiaddrs\n },\n connectionManager: {\n resolvers: {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_0__.dnsaddrResolver\n },\n addressSorter: _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_2__.defaultAddressSort\n },\n transportManager: {\n faultTolerance: _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.FaultTolerance.FATAL_ALL\n }\n};\nasync function validateConfig(opts) {\n const resultingOptions = (0,merge_options__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(DefaultConfig, opts);\n if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_5__.messages.ERR_PROTECTOR_REQUIRED, _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_PROTECTOR_REQUIRED);\n }\n if (resultingOptions.privateKey != null && !(await (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__.peerIdFromKeys)(resultingOptions.privateKey.public.bytes, resultingOptions.privateKey.bytes)).equals(resultingOptions.peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Private key doesn\\'t match peer id', _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_INVALID_KEY);\n }\n return resultingOptions;\n}\n//# sourceMappingURL=config.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config.js?"); /***/ }), @@ -12085,7 +16748,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ connectionGater: () => (/* binding */ connectionGater)\n/* harmony export */ });\n/* harmony import */ var _libp2p_utils_private_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/utils/private-ip */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/private-ip.js\");\n\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nfunction connectionGater(gater = {}) {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr) => {\n const tuples = multiaddr.stringTuples();\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean((0,_libp2p_utils_private_ip__WEBPACK_IMPORTED_MODULE_0__.isPrivateIp)(`${tuples[0][1]}`));\n }\n return false;\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n };\n}\n//# sourceMappingURL=connection-gater.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config/connection-gater.browser.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ connectionGater: () => (/* binding */ connectionGater)\n/* harmony export */ });\n/* harmony import */ var _libp2p_utils_private_ip__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/utils/private-ip */ \"./node_modules/@libp2p/utils/dist/src/private-ip.js\");\n\n/**\n * Returns a connection gater that disallows dialling private addresses by\n * default. Browsers are severely limited in their resource usage so don't\n * waste time trying to dial undiallable addresses.\n */\nfunction connectionGater(gater = {}) {\n return {\n denyDialPeer: async () => false,\n denyDialMultiaddr: async (multiaddr) => {\n const tuples = multiaddr.stringTuples();\n if (tuples[0][0] === 4 || tuples[0][0] === 41) {\n return Boolean((0,_libp2p_utils_private_ip__WEBPACK_IMPORTED_MODULE_0__.isPrivateIp)(`${tuples[0][1]}`));\n }\n return false;\n },\n denyInboundConnection: async () => false,\n denyOutboundConnection: async () => false,\n denyInboundEncryptedConnection: async () => false,\n denyOutboundEncryptedConnection: async () => false,\n denyInboundUpgradedConnection: async () => false,\n denyOutboundUpgradedConnection: async () => false,\n filterMultiaddrForPeer: async () => true,\n ...gater\n };\n}\n//# sourceMappingURL=connection-gater.browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config/connection-gater.browser.js?"); /***/ }), @@ -12096,7 +16759,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AutoDial: () => (/* binding */ AutoDial)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_peer_queue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/utils/peer-queue */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/peer-queue.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n\n\n\n\nconst defaultOptions = {\n minConnections: _constants_js__WEBPACK_IMPORTED_MODULE_1__.MIN_CONNECTIONS,\n maxQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialConcurrency: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_CONCURRENCY,\n autoDialPriority: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_PRIORITY,\n autoDialInterval: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_INTERVAL,\n autoDialPeerRetryThreshold: _constants_js__WEBPACK_IMPORTED_MODULE_1__.AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\nclass AutoDial {\n connectionManager;\n peerStore;\n queue;\n minConnections;\n autoDialPriority;\n autoDialIntervalMs;\n autoDialMaxQueueLength;\n autoDialPeerRetryThresholdMs;\n autoDialDiscoveredPeersDebounce;\n autoDialInterval;\n started;\n running;\n log;\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on whether we know their keys and protocols.\n */\n constructor(components, init) {\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.minConnections = init.minConnections ?? defaultOptions.minConnections;\n this.autoDialPriority = init.autoDialPriority ?? defaultOptions.autoDialPriority;\n this.autoDialIntervalMs = init.autoDialInterval ?? defaultOptions.autoDialInterval;\n this.autoDialMaxQueueLength = init.maxQueueLength ?? defaultOptions.maxQueueLength;\n this.autoDialPeerRetryThresholdMs = init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold;\n this.autoDialDiscoveredPeersDebounce = init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce;\n this.log = components.logger.forComponent('libp2p:connection-manager:auto-dial');\n this.started = false;\n this.running = false;\n this.queue = new _libp2p_utils_peer_queue__WEBPACK_IMPORTED_MODULE_3__.PeerQueue({\n concurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n metricName: 'libp2p_autodial_queue',\n metrics: components.metrics\n });\n this.queue.addEventListener('error', (evt) => {\n this.log.error('error during auto-dial', evt.detail);\n });\n // check the min connection limit whenever a peer disconnects\n components.events.addEventListener('connection:close', () => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n });\n // sometimes peers are discovered in quick succession so add a small\n // debounce to ensure all eligible peers are autodialed\n let debounce;\n // when new peers are discovered, dial them if we don't have\n // enough connections\n components.events.addEventListener('peer:discovery', () => {\n clearTimeout(debounce);\n debounce = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n }, this.autoDialDiscoveredPeersDebounce);\n });\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n afterStart() {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }\n stop() {\n // clear the queue\n this.queue.clear();\n clearTimeout(this.autoDialInterval);\n this.started = false;\n this.running = false;\n }\n async autoDial() {\n if (!this.started || this.running) {\n return;\n }\n const connections = this.connectionManager.getConnectionsMap();\n const numConnections = connections.size;\n // already have enough connections\n if (numConnections >= this.minConnections) {\n if (this.minConnections > 0) {\n this.log.trace('have enough connections %d/%d', numConnections, this.minConnections);\n }\n // no need to schedule next autodial as it will be run when on\n // connection:close event\n return;\n }\n if (this.queue.size > this.autoDialMaxQueueLength) {\n this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections);\n this.sheduleNextAutodial();\n return;\n }\n this.running = true;\n this.log('not enough connections %d/%d - will dial peers to increase the number of connections', numConnections, this.minConnections);\n const dialQueue = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__.PeerSet(\n // @ts-expect-error boolean filter removes falsy peer IDs\n this.connectionManager.getDialQueue()\n .map(queue => queue.peerId)\n .filter(Boolean));\n // sort peers on whether we know protocols or public keys for them\n const peers = await this.peerStore.all({\n filters: [\n // remove some peers\n (peer) => {\n // remove peers without addresses\n if (peer.addresses.length === 0) {\n this.log.trace('not autodialing %p because they have no addresses', peer.id);\n return false;\n }\n // remove peers we are already connected to\n if (connections.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already connected', peer.id);\n return false;\n }\n // remove peers we are already dialling\n if (dialQueue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being dialed', peer.id);\n return false;\n }\n // remove peers already in the autodial queue\n if (this.queue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being autodialed', peer.id);\n return false;\n }\n return true;\n }\n ]\n });\n // shuffle the peers - this is so peers with the same tag values will be\n // dialled in a different order each time\n const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1);\n // sort shuffled peers by tag value\n const peerValues = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_5__.PeerMap();\n for (const peer of shuffledPeers) {\n if (peerValues.has(peer.id)) {\n continue;\n }\n // sum all tag values\n peerValues.set(peer.id, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n // sort by value, highest to lowest\n const sortedPeers = shuffledPeers.sort((a, b) => {\n const peerAValue = peerValues.get(a.id) ?? 0;\n const peerBValue = peerValues.get(b.id) ?? 0;\n if (peerAValue > peerBValue) {\n return -1;\n }\n if (peerAValue < peerBValue) {\n return 1;\n }\n return 0;\n });\n const peersThatHaveNotFailed = sortedPeers.filter(peer => {\n const lastDialFailure = peer.metadata.get(_constants_js__WEBPACK_IMPORTED_MODULE_2__.LAST_DIAL_FAILURE_KEY);\n if (lastDialFailure == null) {\n return true;\n }\n const lastDialFailureTimestamp = parseInt((0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__.toString)(lastDialFailure));\n if (isNaN(lastDialFailureTimestamp)) {\n return true;\n }\n // only dial if the time since the last failure is above the retry threshold\n return Date.now() - lastDialFailureTimestamp > this.autoDialPeerRetryThresholdMs;\n });\n this.log('selected %d/%d peers to dial', peersThatHaveNotFailed.length, peers.length);\n for (const peer of peersThatHaveNotFailed) {\n this.queue.add(async () => {\n const numConnections = this.connectionManager.getConnectionsMap().size;\n // Check to see if we still need to auto dial\n if (numConnections >= this.minConnections) {\n this.log('got enough connections now %d/%d', numConnections, this.minConnections);\n this.queue.clear();\n return;\n }\n this.log('connecting to a peerStore stored peer %p', peer.id);\n await this.connectionManager.openConnection(peer.id, {\n priority: this.autoDialPriority\n });\n }, {\n peerId: peer.id\n }).catch(err => {\n this.log.error('could not connect to peerStore stored peer', err);\n });\n }\n this.running = false;\n this.sheduleNextAutodial();\n }\n sheduleNextAutodial() {\n if (!this.started) {\n return;\n }\n this.autoDialInterval = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }, this.autoDialIntervalMs);\n }\n}\n//# sourceMappingURL=auto-dial.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/auto-dial.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AutoDial: () => (/* binding */ AutoDial)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_peer_queue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/utils/peer-queue */ \"./node_modules/@libp2p/utils/dist/src/peer-queue.js\");\n/* harmony import */ var uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arrays/to-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/to-string.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n\n\n\n\nconst defaultOptions = {\n minConnections: _constants_js__WEBPACK_IMPORTED_MODULE_1__.MIN_CONNECTIONS,\n maxQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialConcurrency: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_CONCURRENCY,\n autoDialPriority: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_PRIORITY,\n autoDialInterval: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_INTERVAL,\n autoDialPeerRetryThreshold: _constants_js__WEBPACK_IMPORTED_MODULE_1__.AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: _constants_js__WEBPACK_IMPORTED_MODULE_2__.AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\nclass AutoDial {\n connectionManager;\n peerStore;\n queue;\n minConnections;\n autoDialPriority;\n autoDialIntervalMs;\n autoDialMaxQueueLength;\n autoDialPeerRetryThresholdMs;\n autoDialDiscoveredPeersDebounce;\n autoDialInterval;\n started;\n running;\n log;\n /**\n * Proactively tries to connect to known peers stored in the PeerStore.\n * It will keep the number of connections below the upper limit and sort\n * the peers to connect based on whether we know their keys and protocols.\n */\n constructor(components, init) {\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.minConnections = init.minConnections ?? defaultOptions.minConnections;\n this.autoDialPriority = init.autoDialPriority ?? defaultOptions.autoDialPriority;\n this.autoDialIntervalMs = init.autoDialInterval ?? defaultOptions.autoDialInterval;\n this.autoDialMaxQueueLength = init.maxQueueLength ?? defaultOptions.maxQueueLength;\n this.autoDialPeerRetryThresholdMs = init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold;\n this.autoDialDiscoveredPeersDebounce = init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce;\n this.log = components.logger.forComponent('libp2p:connection-manager:auto-dial');\n this.started = false;\n this.running = false;\n this.queue = new _libp2p_utils_peer_queue__WEBPACK_IMPORTED_MODULE_3__.PeerQueue({\n concurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n metricName: 'libp2p_autodial_queue',\n metrics: components.metrics\n });\n this.queue.addEventListener('error', (evt) => {\n this.log.error('error during auto-dial', evt.detail);\n });\n // check the min connection limit whenever a peer disconnects\n components.events.addEventListener('connection:close', () => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n });\n // sometimes peers are discovered in quick succession so add a small\n // debounce to ensure all eligible peers are autodialed\n let debounce;\n // when new peers are discovered, dial them if we don't have\n // enough connections\n components.events.addEventListener('peer:discovery', () => {\n clearTimeout(debounce);\n debounce = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error(err);\n });\n }, this.autoDialDiscoveredPeersDebounce);\n });\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n afterStart() {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }\n stop() {\n // clear the queue\n this.queue.clear();\n clearTimeout(this.autoDialInterval);\n this.started = false;\n this.running = false;\n }\n async autoDial() {\n if (!this.started || this.running) {\n return;\n }\n const connections = this.connectionManager.getConnectionsMap();\n const numConnections = connections.size;\n // already have enough connections\n if (numConnections >= this.minConnections) {\n if (this.minConnections > 0) {\n this.log.trace('have enough connections %d/%d', numConnections, this.minConnections);\n }\n // no need to schedule next autodial as it will be run when on\n // connection:close event\n return;\n }\n if (this.queue.size > this.autoDialMaxQueueLength) {\n this.log('not enough connections %d/%d but auto dial queue is full', numConnections, this.minConnections);\n this.sheduleNextAutodial();\n return;\n }\n this.running = true;\n this.log('not enough connections %d/%d - will dial peers to increase the number of connections', numConnections, this.minConnections);\n const dialQueue = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__.PeerSet(\n // @ts-expect-error boolean filter removes falsy peer IDs\n this.connectionManager.getDialQueue()\n .map(queue => queue.peerId)\n .filter(Boolean));\n // sort peers on whether we know protocols or public keys for them\n const peers = await this.peerStore.all({\n filters: [\n // remove some peers\n (peer) => {\n // remove peers without addresses\n if (peer.addresses.length === 0) {\n this.log.trace('not autodialing %p because they have no addresses', peer.id);\n return false;\n }\n // remove peers we are already connected to\n if (connections.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already connected', peer.id);\n return false;\n }\n // remove peers we are already dialling\n if (dialQueue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being dialed', peer.id);\n return false;\n }\n // remove peers already in the autodial queue\n if (this.queue.has(peer.id)) {\n this.log.trace('not autodialing %p because they are already being autodialed', peer.id);\n return false;\n }\n return true;\n }\n ]\n });\n // shuffle the peers - this is so peers with the same tag values will be\n // dialled in a different order each time\n const shuffledPeers = peers.sort(() => Math.random() > 0.5 ? 1 : -1);\n // sort shuffled peers by tag value\n const peerValues = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_5__.PeerMap();\n for (const peer of shuffledPeers) {\n if (peerValues.has(peer.id)) {\n continue;\n }\n // sum all tag values\n peerValues.set(peer.id, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n // sort by value, highest to lowest\n const sortedPeers = shuffledPeers.sort((a, b) => {\n const peerAValue = peerValues.get(a.id) ?? 0;\n const peerBValue = peerValues.get(b.id) ?? 0;\n if (peerAValue > peerBValue) {\n return -1;\n }\n if (peerAValue < peerBValue) {\n return 1;\n }\n return 0;\n });\n const peersThatHaveNotFailed = sortedPeers.filter(peer => {\n const lastDialFailure = peer.metadata.get(_constants_js__WEBPACK_IMPORTED_MODULE_2__.LAST_DIAL_FAILURE_KEY);\n if (lastDialFailure == null) {\n return true;\n }\n const lastDialFailureTimestamp = parseInt((0,uint8arrays_to_string__WEBPACK_IMPORTED_MODULE_0__.toString)(lastDialFailure));\n if (isNaN(lastDialFailureTimestamp)) {\n return true;\n }\n // only dial if the time since the last failure is above the retry threshold\n return Date.now() - lastDialFailureTimestamp > this.autoDialPeerRetryThresholdMs;\n });\n this.log('selected %d/%d peers to dial', peersThatHaveNotFailed.length, peers.length);\n for (const peer of peersThatHaveNotFailed) {\n this.queue.add(async () => {\n const numConnections = this.connectionManager.getConnectionsMap().size;\n // Check to see if we still need to auto dial\n if (numConnections >= this.minConnections) {\n this.log('got enough connections now %d/%d', numConnections, this.minConnections);\n this.queue.clear();\n return;\n }\n this.log('connecting to a peerStore stored peer %p', peer.id);\n await this.connectionManager.openConnection(peer.id, {\n priority: this.autoDialPriority\n });\n }, {\n peerId: peer.id\n }).catch(err => {\n this.log.error('could not connect to peerStore stored peer', err);\n });\n }\n this.running = false;\n this.sheduleNextAutodial();\n }\n sheduleNextAutodial() {\n if (!this.started) {\n return;\n }\n this.autoDialInterval = setTimeout(() => {\n this.autoDial()\n .catch(err => {\n this.log.error('error while autodialing', err);\n });\n }, this.autoDialIntervalMs);\n }\n}\n//# sourceMappingURL=auto-dial.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/auto-dial.js?"); /***/ }), @@ -12107,7 +16770,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ConnectionPruner: () => (/* binding */ ConnectionPruner)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n\n\nconst defaultOptions = {\n maxConnections: _constants_js__WEBPACK_IMPORTED_MODULE_0__.MAX_CONNECTIONS,\n allow: []\n};\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nclass ConnectionPruner {\n maxConnections;\n connectionManager;\n peerStore;\n allow;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n this.allow = init.allow ?? defaultOptions.allow;\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner');\n // check the max connection limit whenever a peer connects\n components.events.addEventListener('connection:open', () => {\n this.maybePruneConnections()\n .catch(err => {\n this.log.error(err);\n });\n });\n }\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async maybePruneConnections() {\n const connections = this.connectionManager.getConnections();\n const numConnections = connections.length;\n const toPrune = Math.max(numConnections - this.maxConnections, 0);\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections);\n if (numConnections <= this.maxConnections) {\n return;\n }\n this.log('max connections limit exceeded %d/%d, pruning %d connection(s)', numConnections, this.maxConnections, toPrune);\n const peerValues = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_1__.PeerMap();\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer;\n if (peerValues.has(remotePeer)) {\n continue;\n }\n peerValues.set(remotePeer, 0);\n try {\n const peer = await this.peerStore.get(remotePeer);\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n this.log.error('error loading peer tags', err);\n }\n }\n }\n // sort by value, lowest to highest\n const sortedConnections = connections.sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0;\n const peerBValue = peerValues.get(b.remotePeer) ?? 0;\n if (peerAValue > peerBValue) {\n return 1;\n }\n if (peerAValue < peerBValue) {\n return -1;\n }\n // if the peers have an equal tag value then we want to close short-lived connections first\n const connectionALifespan = a.timeline.open;\n const connectionBLifespan = b.timeline.open;\n if (connectionALifespan < connectionBLifespan) {\n return 1;\n }\n if (connectionALifespan > connectionBLifespan) {\n return -1;\n }\n return 0;\n });\n // close some connections\n const toClose = [];\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer);\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString());\n });\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection);\n }\n if (toClose.length === toPrune) {\n break;\n }\n }\n // close connections\n await Promise.all(toClose.map(async (connection) => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n }));\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose });\n }\n}\n//# sourceMappingURL=connection-pruner.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/connection-pruner.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ConnectionPruner: () => (/* binding */ ConnectionPruner)\n/* harmony export */ });\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_close__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/utils/close */ \"./node_modules/@libp2p/utils/dist/src/close.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n\n\n\nconst defaultOptions = {\n maxConnections: _constants_js__WEBPACK_IMPORTED_MODULE_0__.MAX_CONNECTIONS,\n allow: []\n};\n/**\n * If we go over the max connections limit, choose some connections to close\n */\nclass ConnectionPruner {\n maxConnections;\n connectionManager;\n peerStore;\n allow;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n this.allow = init.allow ?? defaultOptions.allow;\n this.connectionManager = components.connectionManager;\n this.peerStore = components.peerStore;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager:connection-pruner');\n // check the max connection limit whenever a peer connects\n components.events.addEventListener('connection:open', () => {\n this.maybePruneConnections()\n .catch(err => {\n this.log.error(err);\n });\n });\n }\n /**\n * If we have more connections than our maximum, select some excess connections\n * to prune based on peer value\n */\n async maybePruneConnections() {\n const connections = this.connectionManager.getConnections();\n const numConnections = connections.length;\n this.log('checking max connections limit %d/%d', numConnections, this.maxConnections);\n if (numConnections <= this.maxConnections) {\n return;\n }\n const peerValues = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_1__.PeerMap();\n // work out peer values\n for (const connection of connections) {\n const remotePeer = connection.remotePeer;\n if (peerValues.has(remotePeer)) {\n continue;\n }\n peerValues.set(remotePeer, 0);\n try {\n const peer = await this.peerStore.get(remotePeer);\n // sum all tag values\n peerValues.set(remotePeer, [...peer.tags.values()].reduce((acc, curr) => {\n return acc + curr.value;\n }, 0));\n }\n catch (err) {\n if (err.code !== 'ERR_NOT_FOUND') {\n this.log.error('error loading peer tags', err);\n }\n }\n }\n const sortedConnections = this.sortConnections(connections, peerValues);\n // close some connections\n const toPrune = Math.max(numConnections - this.maxConnections, 0);\n const toClose = [];\n for (const connection of sortedConnections) {\n this.log('too many connections open - closing a connection to %p', connection.remotePeer);\n // check allow list\n const connectionInAllowList = this.allow.some((ma) => {\n return connection.remoteAddr.toString().startsWith(ma.toString());\n });\n // Connections in the allow list should be excluded from pruning\n if (!connectionInAllowList) {\n toClose.push(connection);\n }\n if (toClose.length === toPrune) {\n break;\n }\n }\n // close connections\n await Promise.all(toClose.map(async (connection) => {\n await (0,_libp2p_utils_close__WEBPACK_IMPORTED_MODULE_2__.safelyCloseConnectionIfUnused)(connection, {\n signal: AbortSignal.timeout(1000)\n });\n }));\n // despatch prune event\n this.events.safeDispatchEvent('connection:prune', { detail: toClose });\n }\n sortConnections(connections, peerValues) {\n return connections\n // sort by connection age, newest to oldest\n .sort((a, b) => {\n const connectionALifespan = a.timeline.open;\n const connectionBLifespan = b.timeline.open;\n if (connectionALifespan < connectionBLifespan) {\n return 1;\n }\n if (connectionALifespan > connectionBLifespan) {\n return -1;\n }\n return 0;\n })\n // sort by direction, incoming first then outgoing\n .sort((a, b) => {\n if (a.direction === 'outbound' && b.direction === 'inbound') {\n return 1;\n }\n if (a.direction === 'inbound' && b.direction === 'outbound') {\n return -1;\n }\n return 0;\n })\n // sort by number of streams, lowest to highest\n .sort((a, b) => {\n if (a.streams.length > b.streams.length) {\n return 1;\n }\n if (a.streams.length < b.streams.length) {\n return -1;\n }\n return 0;\n })\n // sort by tag value, lowest to highest\n .sort((a, b) => {\n const peerAValue = peerValues.get(a.remotePeer) ?? 0;\n const peerBValue = peerValues.get(b.remotePeer) ?? 0;\n if (peerAValue > peerBValue) {\n return 1;\n }\n if (peerAValue < peerBValue) {\n return -1;\n }\n return 0;\n });\n }\n}\n//# sourceMappingURL=connection-pruner.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/connection-pruner.js?"); /***/ }), @@ -12140,7 +16803,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DialQueue: () => (/* binding */ DialQueue)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _libp2p_utils_queue__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/utils/queue */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/queue/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var any_signal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! any-signal */ \"./node_modules/any-signal/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _get_peer_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../get-peer.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/utils.js\");\n/* eslint-disable max-depth */\n\n\n\n\n\n\n\n\n\n\n\n\nconst defaultOptions = {\n addressSorter: _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_4__.defaultAddressSort,\n maxParallelDials: _constants_js__WEBPACK_IMPORTED_MODULE_5__.MAX_PARALLEL_DIALS,\n maxDialQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_6__.MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: _constants_js__WEBPACK_IMPORTED_MODULE_6__.MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: _constants_js__WEBPACK_IMPORTED_MODULE_6__.DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__.dnsaddrResolver\n }\n};\nclass DialQueue {\n queue;\n components;\n addressSorter;\n maxPeerAddrsToDial;\n maxDialQueueLength;\n dialTimeout;\n shutDownController;\n connections;\n log;\n constructor(components, init = {}) {\n this.addressSorter = init.addressSorter ?? defaultOptions.addressSorter;\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial;\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength;\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout;\n this.connections = init.connections ?? new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_7__.PeerMap();\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue');\n this.components = components;\n this.shutDownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.setMaxListeners)(Infinity, this.shutDownController.signal);\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.resolvers.set(key, value);\n }\n // controls dial concurrency\n this.queue = new _libp2p_utils_queue__WEBPACK_IMPORTED_MODULE_9__.Queue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n });\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n this.log.error('error in dial queue', event.detail);\n });\n }\n start() {\n this.shutDownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.setMaxListeners)(Infinity, this.shutDownController.signal);\n }\n /**\n * Clears any pending dials\n */\n stop() {\n this.shutDownController.abort();\n this.queue.abort();\n }\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial(peerIdOrMultiaddr, options = {}) {\n const { peerId, multiaddrs } = (0,_get_peer_js__WEBPACK_IMPORTED_MODULE_10__.getPeerAddress)(peerIdOrMultiaddr);\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false;\n }\n if (conn.remotePeer.equals(peerId)) {\n return true;\n }\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr);\n });\n });\n if (existingConnection != null) {\n this.log('already connected to %a', existingConnection.remoteAddr);\n return existingConnection;\n }\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true;\n }\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs;\n if (addresses == null) {\n return false;\n }\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true;\n }\n }\n return false;\n });\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId);\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString());\n }\n return existingDial.join(options);\n }\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL');\n }\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()));\n return this.queue.add(async (options) => {\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal);\n let addrsToDial;\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n });\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr);\n });\n }\n catch (err) {\n signal.clear();\n throw err;\n }\n try {\n let dialed = 0;\n const errors = [];\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('Peer had more than maxPeerAddrsToDial', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_TOO_MANY_ADDRESSES);\n }\n dialed++;\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n });\n this.log('dial to %a succeeded', address.multiaddr);\n return conn;\n }\n catch (err) {\n this.log.error('dial failed to %a', address.multiaddr, err);\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.patch(peerId, {\n metadata: {\n [_constants_js__WEBPACK_IMPORTED_MODULE_6__.LAST_DIAL_FAILURE_KEY]: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n }\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError(err.message, _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.ERR_TIMEOUT);\n }\n errors.push(err);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.AggregateCodeError(errors, 'All multiaddr dials failed', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_TRANSPORT_DIAL_FAILED);\n }\n finally {\n // clean up abort signals/controllers\n signal.clear();\n }\n }, {\n peerId,\n priority: options.priority,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal\n });\n }\n createDialAbortController(userSignal) {\n // let any signal abort the dial\n const signal = (0,any_signal__WEBPACK_IMPORTED_MODULE_2__.anySignal)([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ]);\n // This emitter gets listened to a lot\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_8__.setMaxListeners)(Infinity, signal);\n return signal;\n }\n // eslint-disable-next-line complexity\n async calculateMultiaddrs(peerId, multiaddrs = new Set(), options = {}) {\n const addrs = [...multiaddrs].map(ma => ({\n multiaddr: (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma),\n isCertified: false\n }));\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('Tried to dial self', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_DIALED_SELF);\n }\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('The dial request is blocked by gater.allowDialPeer', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_PEER_DIAL_INTERCEPTED);\n }\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId);\n try {\n const peer = await this.components.peerStore.get(peerId);\n addrs.push(...peer.addresses);\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId);\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId);\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })));\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_NO_ROUTERS_AVAILABLE) {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err);\n }\n }\n }\n }\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(addrs.map(async (addr) => {\n const result = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_13__.resolveMultiaddrs)(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n });\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr;\n }\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }));\n })))\n .flat();\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`;\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop();\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr;\n }\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n };\n }\n return addr;\n });\n }\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.transportForMultiaddr(addr.multiaddr) == null) {\n return false;\n }\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId();\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId);\n }\n return true;\n });\n // deduplicate addresses\n const dedupedAddrs = new Map();\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString();\n const existing = dedupedAddrs.get(maStr);\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false;\n continue;\n }\n dedupedAddrs.set(maStr, addr);\n }\n const dedupedMultiaddrs = [...dedupedAddrs.values()];\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('The dial request has no valid addresses', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_NO_VALID_ADDRESSES);\n }\n const gatedAdrs = [];\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue;\n }\n gatedAdrs.push(addr);\n }\n const sortedGatedAddrs = gatedAdrs.sort(this.addressSorter);\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_11__.CodeError('The connection gater denied all addresses in the dial request', _errors_js__WEBPACK_IMPORTED_MODULE_12__.codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()));\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()));\n return sortedGatedAddrs;\n }\n}\n//# sourceMappingURL=dial-queue.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/dial-queue.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DialQueue: () => (/* binding */ DialQueue)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _libp2p_utils_priority_queue__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @libp2p/utils/priority-queue */ \"./node_modules/@libp2p/utils/dist/src/priority-queue.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var _multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @multiformats/multiaddr-matcher */ \"./node_modules/@multiformats/multiaddr-matcher/dist/src/index.js\");\n/* harmony import */ var any_signal__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! any-signal */ \"./node_modules/any-signal/dist/src/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _get_peer_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../get-peer.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/utils.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js\");\n/* eslint-disable max-depth */\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst defaultOptions = {\n addressSorter: _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_6__.defaultAddressSort,\n maxParallelDials: _constants_js__WEBPACK_IMPORTED_MODULE_7__.MAX_PARALLEL_DIALS,\n maxDialQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_8__.MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: _constants_js__WEBPACK_IMPORTED_MODULE_8__.MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: _constants_js__WEBPACK_IMPORTED_MODULE_8__.DIAL_TIMEOUT,\n resolvers: {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__.dnsaddrResolver\n }\n};\nclass DialQueue {\n queue;\n components;\n addressSorter;\n maxPeerAddrsToDial;\n maxDialQueueLength;\n dialTimeout;\n shutDownController;\n connections;\n log;\n constructor(components, init = {}) {\n this.addressSorter = init.addressSorter ?? defaultOptions.addressSorter;\n this.maxPeerAddrsToDial = init.maxPeerAddrsToDial ?? defaultOptions.maxPeerAddrsToDial;\n this.maxDialQueueLength = init.maxDialQueueLength ?? defaultOptions.maxDialQueueLength;\n this.dialTimeout = init.dialTimeout ?? defaultOptions.dialTimeout;\n this.connections = init.connections ?? new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_9__.PeerMap();\n this.log = components.logger.forComponent('libp2p:connection-manager:dial-queue');\n this.components = components;\n this.shutDownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.setMaxListeners)(Infinity, this.shutDownController.signal);\n for (const [key, value] of Object.entries(init.resolvers ?? {})) {\n _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.resolvers.set(key, value);\n }\n // controls dial concurrency\n this.queue = new _libp2p_utils_priority_queue__WEBPACK_IMPORTED_MODULE_11__.PriorityQueue({\n concurrency: init.maxParallelDials ?? defaultOptions.maxParallelDials,\n metricName: 'libp2p_dial_queue',\n metrics: components.metrics\n });\n // a started job errored\n this.queue.addEventListener('error', (event) => {\n this.log.error('error in dial queue', event.detail);\n });\n }\n start() {\n this.shutDownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.setMaxListeners)(Infinity, this.shutDownController.signal);\n }\n /**\n * Clears any pending dials\n */\n stop() {\n this.shutDownController.abort();\n this.queue.abort();\n }\n /**\n * Connects to a given peer, multiaddr or list of multiaddrs.\n *\n * If a peer is passed, all known multiaddrs will be tried. If a multiaddr or\n * multiaddrs are passed only those will be dialled.\n *\n * Where a list of multiaddrs is passed, if any contain a peer id then all\n * multiaddrs in the list must contain the same peer id.\n *\n * The dial to the first address that is successfully able to upgrade a\n * connection will be used, all other dials will be aborted when that happens.\n */\n async dial(peerIdOrMultiaddr, options = {}) {\n const { peerId, multiaddrs } = (0,_get_peer_js__WEBPACK_IMPORTED_MODULE_12__.getPeerAddress)(peerIdOrMultiaddr);\n // make sure we don't have an existing connection to any of the addresses we\n // are about to dial\n const existingConnection = Array.from(this.connections.values()).flat().find(conn => {\n if (options.force === true) {\n return false;\n }\n if (conn.remotePeer.equals(peerId)) {\n return true;\n }\n return multiaddrs.find(addr => {\n return addr.equals(conn.remoteAddr);\n });\n });\n if (existingConnection != null) {\n this.log('already connected to %a', existingConnection.remoteAddr);\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_4__.CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n // ready to dial, all async work finished - make sure we don't have any\n // pending dials in progress for this peer or set of multiaddrs\n const existingDial = this.queue.queue.find(job => {\n if (peerId?.equals(job.options.peerId) === true) {\n return true;\n }\n // does the dial contain any of the target multiaddrs?\n const addresses = job.options.multiaddrs;\n if (addresses == null) {\n return false;\n }\n for (const multiaddr of multiaddrs) {\n if (addresses.has(multiaddr.toString())) {\n return true;\n }\n }\n return false;\n });\n if (existingDial != null) {\n this.log('joining existing dial target for %p', peerId);\n // add all multiaddrs to the dial target\n for (const multiaddr of multiaddrs) {\n existingDial.options.multiaddrs.add(multiaddr.toString());\n }\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_4__.CustomProgressEvent('dial-queue:already-in-dial-queue'));\n return existingDial.join(options);\n }\n if (this.queue.size >= this.maxDialQueueLength) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('Dial queue is full', 'ERR_DIAL_QUEUE_FULL');\n }\n this.log('creating dial target for %p', peerId, multiaddrs.map(ma => ma.toString()));\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_4__.CustomProgressEvent('dial-queue:add-to-dial-queue'));\n return this.queue.add(async (options) => {\n options?.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_4__.CustomProgressEvent('dial-queue:start-dial'));\n // create abort conditions - need to do this before `calculateMultiaddrs` as\n // we may be about to resolve a dns addr which can time out\n const signal = this.createDialAbortController(options?.signal);\n let addrsToDial;\n try {\n // load addresses from address book, resolve and dnsaddrs, filter\n // undiallables, add peer IDs, etc\n addrsToDial = await this.calculateMultiaddrs(peerId, options?.multiaddrs, {\n ...options,\n signal\n });\n options?.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_4__.CustomProgressEvent('dial-queue:calculated-addresses', addrsToDial));\n addrsToDial.map(({ multiaddr }) => multiaddr.toString()).forEach(addr => {\n options?.multiaddrs.add(addr);\n });\n }\n catch (err) {\n signal.clear();\n throw err;\n }\n try {\n let dialed = 0;\n const errors = [];\n for (const address of addrsToDial) {\n if (dialed === this.maxPeerAddrsToDial) {\n this.log('dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others', dialed, peerId);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('Peer had more than maxPeerAddrsToDial', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_TOO_MANY_ADDRESSES);\n }\n dialed++;\n try {\n const conn = await this.components.transportManager.dial(address.multiaddr, {\n ...options,\n signal\n });\n this.log('dial to %a succeeded', address.multiaddr);\n return conn;\n }\n catch (err) {\n this.log.error('dial failed to %a', address.multiaddr, err);\n if (peerId != null) {\n // record the failed dial\n try {\n await this.components.peerStore.patch(peerId, {\n metadata: {\n [_constants_js__WEBPACK_IMPORTED_MODULE_8__.LAST_DIAL_FAILURE_KEY]: (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_5__.fromString)(Date.now().toString())\n }\n });\n }\n catch (err) {\n this.log.error('could not update last dial failure key for %p', peerId, err);\n }\n }\n // the user/dial timeout/shutdown controller signal aborted\n if (signal.aborted) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError(err.message, _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.ERR_TIMEOUT);\n }\n errors.push(err);\n }\n }\n if (errors.length === 1) {\n throw errors[0];\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.AggregateCodeError(errors, 'All multiaddr dials failed', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_TRANSPORT_DIAL_FAILED);\n }\n finally {\n // clean up abort signals/controllers\n signal.clear();\n }\n }, {\n peerId,\n priority: options.priority ?? _index_js__WEBPACK_IMPORTED_MODULE_15__.DEFAULT_DIAL_PRIORITY,\n multiaddrs: new Set(multiaddrs.map(ma => ma.toString())),\n signal: options.signal,\n onProgress: options.onProgress\n });\n }\n createDialAbortController(userSignal) {\n // let any signal abort the dial\n const signal = (0,any_signal__WEBPACK_IMPORTED_MODULE_3__.anySignal)([\n AbortSignal.timeout(this.dialTimeout),\n this.shutDownController.signal,\n userSignal\n ]);\n // This emitter gets listened to a lot\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_10__.setMaxListeners)(Infinity, signal);\n return signal;\n }\n // eslint-disable-next-line complexity\n async calculateMultiaddrs(peerId, multiaddrs = new Set(), options = {}) {\n const addrs = [...multiaddrs].map(ma => ({\n multiaddr: (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma),\n isCertified: false\n }));\n // if a peer id or multiaddr(s) with a peer id, make sure it isn't our peer id and that we are allowed to dial it\n if (peerId != null) {\n if (this.components.peerId.equals(peerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('Tried to dial self', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_DIALED_SELF);\n }\n if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('The dial request is blocked by gater.allowDialPeer', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_PEER_DIAL_INTERCEPTED);\n }\n // if just a peer id was passed, load available multiaddrs for this peer\n // from the peer store\n if (addrs.length === 0) {\n this.log('loading multiaddrs for %p', peerId);\n try {\n const peer = await this.components.peerStore.get(peerId);\n addrs.push(...peer.addresses);\n this.log('loaded multiaddrs for %p', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n }\n // if we still don't have any addresses for this peer, try a lookup\n // using the peer routing\n if (addrs.length === 0) {\n this.log('looking up multiaddrs for %p in the peer routing', peerId);\n try {\n const peerInfo = await this.components.peerRouting.findPeer(peerId);\n this.log('found multiaddrs for %p in the peer routing', peerId, addrs.map(({ multiaddr }) => multiaddr.toString()));\n addrs.push(...peerInfo.multiaddrs.map(multiaddr => ({\n multiaddr,\n isCertified: false\n })));\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_NO_ROUTERS_AVAILABLE) {\n this.log.error('looking up multiaddrs for %p in the peer routing failed', peerId, err);\n }\n }\n }\n }\n // resolve addresses - this can result in a one-to-many translation when\n // dnsaddrs are resolved\n let resolvedAddresses = (await Promise.all(addrs.map(async (addr) => {\n const result = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_16__.resolveMultiaddrs)(addr.multiaddr, {\n dns: this.components.dns,\n ...options,\n log: this.log\n });\n if (result.length === 1 && result[0].equals(addr.multiaddr)) {\n return addr;\n }\n return result.map(multiaddr => ({\n multiaddr,\n isCertified: false\n }));\n })))\n .flat();\n // ensure the peer id is appended to the multiaddr\n if (peerId != null) {\n const peerIdMultiaddr = `/p2p/${peerId.toString()}`;\n resolvedAddresses = resolvedAddresses.map(addr => {\n const lastProto = addr.multiaddr.protos().pop();\n // do not append peer id to path multiaddrs\n if (lastProto?.path === true) {\n return addr;\n }\n // append peer id to multiaddr if it is not already present\n if (addr.multiaddr.getPeerId() == null) {\n return {\n multiaddr: addr.multiaddr.encapsulate(peerIdMultiaddr),\n isCertified: addr.isCertified\n };\n }\n return addr;\n });\n }\n const filteredAddrs = resolvedAddresses.filter(addr => {\n // filter out any multiaddrs that we do not have transports for\n if (this.components.transportManager.dialTransportForMultiaddr(addr.multiaddr) == null) {\n return false;\n }\n // if the resolved multiaddr has a PeerID but it's the wrong one, ignore it\n // - this can happen with addresses like bootstrap.libp2p.io that resolve\n // to multiple different peers\n const addrPeerId = addr.multiaddr.getPeerId();\n if (peerId != null && addrPeerId != null) {\n return peerId.equals(addrPeerId);\n }\n return true;\n });\n // deduplicate addresses\n const dedupedAddrs = new Map();\n for (const addr of filteredAddrs) {\n const maStr = addr.multiaddr.toString();\n const existing = dedupedAddrs.get(maStr);\n if (existing != null) {\n existing.isCertified = existing.isCertified || addr.isCertified || false;\n continue;\n }\n dedupedAddrs.set(maStr, addr);\n }\n const dedupedMultiaddrs = [...dedupedAddrs.values()];\n // make sure we actually have some addresses to dial\n if (dedupedMultiaddrs.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('The dial request has no valid addresses', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_NO_VALID_ADDRESSES);\n }\n const gatedAdrs = [];\n for (const addr of dedupedMultiaddrs) {\n if (this.components.connectionGater.denyDialMultiaddr != null && await this.components.connectionGater.denyDialMultiaddr(addr.multiaddr)) {\n continue;\n }\n gatedAdrs.push(addr);\n }\n const sortedGatedAddrs = gatedAdrs.sort(this.addressSorter);\n // make sure we actually have some addresses to dial\n if (sortedGatedAddrs.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.CodeError('The connection gater denied all addresses in the dial request', _errors_js__WEBPACK_IMPORTED_MODULE_14__.codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log.trace('addresses for %p before filtering', peerId ?? 'unknown peer', resolvedAddresses.map(({ multiaddr }) => multiaddr.toString()));\n this.log.trace('addresses for %p after filtering', peerId ?? 'unknown peer', sortedGatedAddrs.map(({ multiaddr }) => multiaddr.toString()));\n return sortedGatedAddrs;\n }\n async isDialable(multiaddr, options = {}) {\n if (!Array.isArray(multiaddr)) {\n multiaddr = [multiaddr];\n }\n try {\n const addresses = await this.calculateMultiaddrs(undefined, new Set(multiaddr.map(ma => ma.toString())), options);\n if (options.runOnTransientConnection === false) {\n // return true if any resolved multiaddrs are not relay addresses\n return addresses.find(addr => {\n return !_multiformats_multiaddr_matcher__WEBPACK_IMPORTED_MODULE_2__.Circuit.matches(addr.multiaddr);\n }) != null;\n }\n return true;\n }\n catch (err) {\n this.log.trace('error calculating if multiaddr(s) were dialable', err);\n }\n return false;\n }\n}\n//# sourceMappingURL=dial-queue.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/dial-queue.js?"); /***/ }), @@ -12151,7 +16814,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultConnectionManager: () => (/* binding */ DefaultConnectionManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/utils/rate-limiter */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/rate-limiter.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _get_peer_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../get-peer.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js\");\n/* harmony import */ var _auto_dial_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./auto-dial.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/auto-dial.js\");\n/* harmony import */ var _connection_pruner_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./connection-pruner.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/connection-pruner.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _dial_queue_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./dial-queue.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/dial-queue.js\");\n\n\n\n\n\n\n\n\n\n\n\n\nconst DEFAULT_DIAL_PRIORITY = 50;\nconst defaultOptions = {\n minConnections: _constants_js__WEBPACK_IMPORTED_MODULE_2__.MIN_CONNECTIONS,\n maxConnections: _constants_js__WEBPACK_IMPORTED_MODULE_2__.MAX_CONNECTIONS,\n inboundConnectionThreshold: _constants_js__WEBPACK_IMPORTED_MODULE_3__.INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_INCOMING_PENDING_CONNECTIONS,\n autoDialConcurrency: _constants_js__WEBPACK_IMPORTED_MODULE_3__.AUTO_DIAL_CONCURRENCY,\n autoDialPriority: _constants_js__WEBPACK_IMPORTED_MODULE_3__.AUTO_DIAL_PRIORITY,\n autoDialMaxQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_3__.AUTO_DIAL_MAX_QUEUE_LENGTH\n};\n/**\n * Responsible for managing known connections.\n */\nclass DefaultConnectionManager {\n started;\n connections;\n allow;\n deny;\n maxIncomingPendingConnections;\n incomingPendingConnections;\n maxConnections;\n dialQueue;\n autoDial;\n connectionPruner;\n inboundConnectionRateLimiter;\n peerStore;\n metrics;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n const minConnections = init.minConnections ?? defaultOptions.minConnections;\n if (this.maxConnections < minConnections) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Connection Manager maxConnections must be greater than minConnections', _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_INVALID_PARAMETERS);\n }\n /**\n * Map of connections per peer\n */\n this.connections = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_6__.PeerMap();\n this.started = false;\n this.peerStore = components.peerStore;\n this.metrics = components.metrics;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager');\n this.onConnect = this.onConnect.bind(this);\n this.onDisconnect = this.onDisconnect.bind(this);\n this.events.addEventListener('connection:open', this.onConnect);\n this.events.addEventListener('connection:close', this.onDisconnect);\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma));\n this.deny = (init.deny ?? []).map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma));\n this.incomingPendingConnections = 0;\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections;\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_7__.RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n });\n // controls what happens when we don't have enough connections\n this.autoDial = new _auto_dial_js__WEBPACK_IMPORTED_MODULE_8__.AutoDial({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n minConnections,\n autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,\n maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength\n });\n // controls what happens when we have too many connections\n this.connectionPruner = new _connection_pruner_js__WEBPACK_IMPORTED_MODULE_9__.ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n });\n this.dialQueue = new _dial_queue_js__WEBPACK_IMPORTED_MODULE_10__.DialQueue(components, {\n addressSorter: init.addressSorter ?? _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_11__.defaultAddressSort,\n maxParallelDials: init.maxParallelDials ?? _constants_js__WEBPACK_IMPORTED_MODULE_2__.MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__.dnsaddrResolver\n },\n connections: this.connections\n });\n }\n isStarted() {\n return this.started;\n }\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start() {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n };\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.direction === 'inbound') {\n metric.inbound++;\n }\n else {\n metric.outbound++;\n }\n }\n }\n return metric;\n }\n });\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n metric[key] = (metric[key] ?? 0) + 1;\n }\n }\n }\n return metric;\n }\n });\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams = {};\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n streams[key] = (streams[key] ?? 0) + 1;\n }\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? [];\n allStreams[protocol].push(count);\n }\n }\n }\n const metric = {};\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b);\n const index = Math.floor(counts.length * 0.9);\n metric[protocol] = counts[index];\n }\n return metric;\n }\n });\n this.dialQueue.start();\n this.autoDial.start();\n this.started = true;\n this.log('started');\n }\n async afterStart() {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(_libp2p_interface__WEBPACK_IMPORTED_MODULE_12__.KEEP_ALIVE);\n }]\n });\n await Promise.all(keepAlivePeers.map(async (peer) => {\n await this.openConnection(peer.id)\n .catch(err => {\n this.log.error(err);\n });\n }));\n })\n .catch(err => {\n this.log.error(err);\n });\n this.autoDial.afterStart();\n }\n /**\n * Stops the Connection Manager\n */\n async stop() {\n this.dialQueue.stop();\n this.autoDial.stop();\n // Close all connections we're tracking\n const tasks = [];\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n })());\n }\n }\n this.log('closing %d connections', tasks.length);\n await Promise.all(tasks);\n this.connections.clear();\n this.log('stopped');\n }\n onConnect(evt) {\n void this._onConnect(evt).catch(err => {\n this.log.error(err);\n });\n }\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close();\n return;\n }\n const peerId = connection.remotePeer;\n const storedConns = this.connections.get(peerId);\n let isNewPeer = false;\n if (storedConns != null) {\n storedConns.push(connection);\n }\n else {\n isNewPeer = true;\n this.connections.set(peerId, [connection]);\n }\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n });\n }\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer });\n }\n }\n /**\n * Removes the connection from tracking\n */\n onDisconnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return;\n }\n const peerId = connection.remotePeer;\n let storedConn = this.connections.get(peerId);\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id);\n this.connections.set(peerId, storedConn);\n }\n else if (storedConn != null) {\n this.connections.delete(peerId);\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer });\n }\n }\n getConnections(peerId) {\n if (peerId != null) {\n return this.connections.get(peerId) ?? [];\n }\n let conns = [];\n for (const c of this.connections.values()) {\n conns = conns.concat(c);\n }\n return conns;\n }\n getConnectionsMap() {\n return this.connections;\n }\n async openConnection(peerIdOrMultiaddr, options = {}) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Not started', _errors_js__WEBPACK_IMPORTED_MODULE_5__.codes.ERR_NODE_NOT_STARTED);\n }\n options.signal?.throwIfAborted();\n const { peerId } = (0,_get_peer_js__WEBPACK_IMPORTED_MODULE_13__.getPeerAddress)(peerIdOrMultiaddr);\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId);\n const existingConnection = this.getConnections(peerId)\n .find(conn => !conn.transient);\n if (existingConnection != null) {\n this.log('had an existing non-transient connection to %p', peerId);\n return existingConnection;\n }\n }\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n });\n let peerConnections = this.connections.get(connection.remotePeer);\n if (peerConnections == null) {\n peerConnections = [];\n this.connections.set(connection.remotePeer, peerConnections);\n }\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false;\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true;\n }\n }\n if (!trackedConnection) {\n peerConnections.push(connection);\n }\n return connection;\n }\n async closeConnections(peerId, options = {}) {\n const connections = this.connections.get(peerId) ?? [];\n await Promise.all(connections.map(async (connection) => {\n try {\n await connection.close(options);\n }\n catch (err) {\n connection.abort(err);\n }\n }));\n }\n async acceptIncomingConnection(maConn) {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr);\n return false;\n }\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (allowConnection) {\n this.incomingPendingConnections++;\n return true;\n }\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr);\n return false;\n }\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address;\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1);\n }\n catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host);\n return false;\n }\n }\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++;\n return true;\n }\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr);\n return false;\n }\n afterUpgradeInbound() {\n this.incomingPendingConnections--;\n }\n getDialQueue() {\n const statusMap = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n };\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma))\n };\n });\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_DIAL_PRIORITY: () => (/* binding */ DEFAULT_DIAL_PRIORITY),\n/* harmony export */ DefaultConnectionManager: () => (/* binding */ DefaultConnectionManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-store/tags.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/map.js\");\n/* harmony import */ var _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @libp2p/utils/address-sort */ \"./node_modules/@libp2p/utils/dist/src/address-sort.js\");\n/* harmony import */ var _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/utils/rate-limiter */ \"./node_modules/@libp2p/utils/dist/src/rate-limiter.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @multiformats/multiaddr/resolvers */ \"./node_modules/@multiformats/multiaddr/dist/src/resolvers/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _get_peer_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../get-peer.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js\");\n/* harmony import */ var _auto_dial_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./auto-dial.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/auto-dial.js\");\n/* harmony import */ var _connection_pruner_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./connection-pruner.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/connection-pruner.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.browser.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _dial_queue_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./dial-queue.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/dial-queue.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\nconst DEFAULT_DIAL_PRIORITY = 50;\nconst defaultOptions = {\n minConnections: _constants_js__WEBPACK_IMPORTED_MODULE_3__.MIN_CONNECTIONS,\n maxConnections: _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_CONNECTIONS,\n inboundConnectionThreshold: _constants_js__WEBPACK_IMPORTED_MODULE_4__.INBOUND_CONNECTION_THRESHOLD,\n maxIncomingPendingConnections: _constants_js__WEBPACK_IMPORTED_MODULE_4__.MAX_INCOMING_PENDING_CONNECTIONS,\n autoDialConcurrency: _constants_js__WEBPACK_IMPORTED_MODULE_4__.AUTO_DIAL_CONCURRENCY,\n autoDialPriority: _constants_js__WEBPACK_IMPORTED_MODULE_4__.AUTO_DIAL_PRIORITY,\n autoDialMaxQueueLength: _constants_js__WEBPACK_IMPORTED_MODULE_4__.AUTO_DIAL_MAX_QUEUE_LENGTH,\n autoDialPeerRetryThreshold: _constants_js__WEBPACK_IMPORTED_MODULE_3__.AUTO_DIAL_PEER_RETRY_THRESHOLD,\n autoDialDiscoveredPeersDebounce: _constants_js__WEBPACK_IMPORTED_MODULE_4__.AUTO_DIAL_DISCOVERED_PEERS_DEBOUNCE\n};\n/**\n * Responsible for managing known connections.\n */\nclass DefaultConnectionManager {\n started;\n connections;\n allow;\n deny;\n maxIncomingPendingConnections;\n incomingPendingConnections;\n maxConnections;\n dialQueue;\n autoDial;\n connectionPruner;\n inboundConnectionRateLimiter;\n peerStore;\n metrics;\n events;\n log;\n constructor(components, init = {}) {\n this.maxConnections = init.maxConnections ?? defaultOptions.maxConnections;\n const minConnections = init.minConnections ?? defaultOptions.minConnections;\n if (this.maxConnections < minConnections) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError('Connection Manager maxConnections must be greater than minConnections', _errors_js__WEBPACK_IMPORTED_MODULE_6__.codes.ERR_INVALID_PARAMETERS);\n }\n /**\n * Map of connections per peer\n */\n this.connections = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_7__.PeerMap();\n this.started = false;\n this.peerStore = components.peerStore;\n this.metrics = components.metrics;\n this.events = components.events;\n this.log = components.logger.forComponent('libp2p:connection-manager');\n this.onConnect = this.onConnect.bind(this);\n this.onDisconnect = this.onDisconnect.bind(this);\n this.events.addEventListener('connection:open', this.onConnect);\n this.events.addEventListener('connection:close', this.onDisconnect);\n // allow/deny lists\n this.allow = (init.allow ?? []).map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma));\n this.deny = (init.deny ?? []).map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma));\n this.incomingPendingConnections = 0;\n this.maxIncomingPendingConnections = init.maxIncomingPendingConnections ?? defaultOptions.maxIncomingPendingConnections;\n // controls individual peers trying to dial us too quickly\n this.inboundConnectionRateLimiter = new _libp2p_utils_rate_limiter__WEBPACK_IMPORTED_MODULE_8__.RateLimiter({\n points: init.inboundConnectionThreshold ?? defaultOptions.inboundConnectionThreshold,\n duration: 1\n });\n // controls what happens when we don't have enough connections\n this.autoDial = new _auto_dial_js__WEBPACK_IMPORTED_MODULE_9__.AutoDial({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n minConnections,\n autoDialConcurrency: init.autoDialConcurrency ?? defaultOptions.autoDialConcurrency,\n autoDialPriority: init.autoDialPriority ?? defaultOptions.autoDialPriority,\n autoDialPeerRetryThreshold: init.autoDialPeerRetryThreshold ?? defaultOptions.autoDialPeerRetryThreshold,\n autoDialDiscoveredPeersDebounce: init.autoDialDiscoveredPeersDebounce ?? defaultOptions.autoDialDiscoveredPeersDebounce,\n maxQueueLength: init.autoDialMaxQueueLength ?? defaultOptions.autoDialMaxQueueLength\n });\n // controls what happens when we have too many connections\n this.connectionPruner = new _connection_pruner_js__WEBPACK_IMPORTED_MODULE_10__.ConnectionPruner({\n connectionManager: this,\n peerStore: components.peerStore,\n events: components.events,\n logger: components.logger\n }, {\n maxConnections: this.maxConnections,\n allow: this.allow\n });\n this.dialQueue = new _dial_queue_js__WEBPACK_IMPORTED_MODULE_11__.DialQueue(components, {\n addressSorter: init.addressSorter ?? _libp2p_utils_address_sort__WEBPACK_IMPORTED_MODULE_12__.defaultAddressSort,\n maxParallelDials: init.maxParallelDials ?? _constants_js__WEBPACK_IMPORTED_MODULE_3__.MAX_PARALLEL_DIALS,\n maxDialQueueLength: init.maxDialQueueLength ?? _constants_js__WEBPACK_IMPORTED_MODULE_4__.MAX_DIAL_QUEUE_LENGTH,\n maxPeerAddrsToDial: init.maxPeerAddrsToDial ?? _constants_js__WEBPACK_IMPORTED_MODULE_4__.MAX_PEER_ADDRS_TO_DIAL,\n dialTimeout: init.dialTimeout ?? _constants_js__WEBPACK_IMPORTED_MODULE_4__.DIAL_TIMEOUT,\n resolvers: init.resolvers ?? {\n dnsaddr: _multiformats_multiaddr_resolvers__WEBPACK_IMPORTED_MODULE_1__.dnsaddrResolver\n },\n connections: this.connections\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-manager';\n isStarted() {\n return this.started;\n }\n /**\n * Starts the Connection Manager. If Metrics are not enabled on libp2p\n * only event loop and connection limits will be monitored.\n */\n async start() {\n // track inbound/outbound connections\n this.metrics?.registerMetricGroup('libp2p_connection_manager_connections', {\n calculate: () => {\n const metric = {\n inbound: 0,\n outbound: 0\n };\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n if (conn.direction === 'inbound') {\n metric.inbound++;\n }\n else {\n metric.outbound++;\n }\n }\n }\n return metric;\n }\n });\n // track total number of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_protocol_streams_total', {\n label: 'protocol',\n calculate: () => {\n const metric = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n metric[key] = (metric[key] ?? 0) + 1;\n }\n }\n }\n return metric;\n }\n });\n // track 90th percentile of streams per protocol\n this.metrics?.registerMetricGroup('libp2p_connection_manager_protocol_streams_per_connection_90th_percentile', {\n label: 'protocol',\n calculate: () => {\n const allStreams = {};\n for (const conns of this.connections.values()) {\n for (const conn of conns) {\n const streams = {};\n for (const stream of conn.streams) {\n const key = `${stream.direction} ${stream.protocol ?? 'unnegotiated'}`;\n streams[key] = (streams[key] ?? 0) + 1;\n }\n for (const [protocol, count] of Object.entries(streams)) {\n allStreams[protocol] = allStreams[protocol] ?? [];\n allStreams[protocol].push(count);\n }\n }\n }\n const metric = {};\n for (let [protocol, counts] of Object.entries(allStreams)) {\n counts = counts.sort((a, b) => a - b);\n const index = Math.floor(counts.length * 0.9);\n metric[protocol] = counts[index];\n }\n return metric;\n }\n });\n this.dialQueue.start();\n this.autoDial.start();\n this.started = true;\n this.log('started');\n }\n async afterStart() {\n // re-connect to any peers with the KEEP_ALIVE tag\n void Promise.resolve()\n .then(async () => {\n const keepAlivePeers = await this.peerStore.all({\n filters: [(peer) => {\n return peer.tags.has(_libp2p_interface__WEBPACK_IMPORTED_MODULE_13__.KEEP_ALIVE);\n }]\n });\n await Promise.all(keepAlivePeers.map(async (peer) => {\n await this.openConnection(peer.id)\n .catch(err => {\n this.log.error(err);\n });\n }));\n })\n .catch(err => {\n this.log.error(err);\n });\n this.autoDial.afterStart();\n }\n /**\n * Stops the Connection Manager\n */\n async stop() {\n this.dialQueue.stop();\n this.autoDial.stop();\n // Close all connections we're tracking\n const tasks = [];\n for (const connectionList of this.connections.values()) {\n for (const connection of connectionList) {\n tasks.push((async () => {\n try {\n await connection.close();\n }\n catch (err) {\n this.log.error(err);\n }\n })());\n }\n }\n this.log('closing %d connections', tasks.length);\n await Promise.all(tasks);\n this.connections.clear();\n this.log('stopped');\n }\n onConnect(evt) {\n void this._onConnect(evt).catch(err => {\n this.log.error(err);\n });\n }\n /**\n * Tracks the incoming connection and check the connection limit\n */\n async _onConnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n await connection.close();\n return;\n }\n const peerId = connection.remotePeer;\n const storedConns = this.connections.get(peerId);\n let isNewPeer = false;\n if (storedConns != null) {\n storedConns.push(connection);\n }\n else {\n isNewPeer = true;\n this.connections.set(peerId, [connection]);\n }\n // only need to store RSA public keys, all other types are embedded in the peer id\n if (peerId.publicKey != null && peerId.type === 'RSA') {\n await this.peerStore.patch(peerId, {\n publicKey: peerId.publicKey\n });\n }\n if (isNewPeer) {\n this.events.safeDispatchEvent('peer:connect', { detail: connection.remotePeer });\n }\n }\n /**\n * Removes the connection from tracking\n */\n onDisconnect(evt) {\n const { detail: connection } = evt;\n if (!this.started) {\n // This can happen when we are in the process of shutting down the node\n return;\n }\n const peerId = connection.remotePeer;\n let storedConn = this.connections.get(peerId);\n if (storedConn != null && storedConn.length > 1) {\n storedConn = storedConn.filter((conn) => conn.id !== connection.id);\n this.connections.set(peerId, storedConn);\n }\n else if (storedConn != null) {\n this.connections.delete(peerId);\n this.events.safeDispatchEvent('peer:disconnect', { detail: connection.remotePeer });\n }\n }\n getConnections(peerId) {\n if (peerId != null) {\n return this.connections.get(peerId) ?? [];\n }\n let conns = [];\n for (const c of this.connections.values()) {\n conns = conns.concat(c);\n }\n return conns;\n }\n getConnectionsMap() {\n return this.connections;\n }\n async openConnection(peerIdOrMultiaddr, options = {}) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.CodeError('Not started', _errors_js__WEBPACK_IMPORTED_MODULE_6__.codes.ERR_NODE_NOT_STARTED);\n }\n options.signal?.throwIfAborted();\n const { peerId } = (0,_get_peer_js__WEBPACK_IMPORTED_MODULE_14__.getPeerAddress)(peerIdOrMultiaddr);\n if (peerId != null && options.force !== true) {\n this.log('dial %p', peerId);\n const existingConnection = this.getConnections(peerId)\n .find(conn => !conn.transient);\n if (existingConnection != null) {\n this.log('had an existing non-transient connection to %p', peerId);\n options.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_2__.CustomProgressEvent('dial-queue:already-connected'));\n return existingConnection;\n }\n }\n const connection = await this.dialQueue.dial(peerIdOrMultiaddr, {\n ...options,\n priority: options.priority ?? DEFAULT_DIAL_PRIORITY\n });\n let peerConnections = this.connections.get(connection.remotePeer);\n if (peerConnections == null) {\n peerConnections = [];\n this.connections.set(connection.remotePeer, peerConnections);\n }\n // we get notified of connections via the Upgrader emitting \"connection\"\n // events, double check we aren't already tracking this connection before\n // storing it\n let trackedConnection = false;\n for (const conn of peerConnections) {\n if (conn.id === connection.id) {\n trackedConnection = true;\n }\n }\n if (!trackedConnection) {\n peerConnections.push(connection);\n }\n return connection;\n }\n async closeConnections(peerId, options = {}) {\n const connections = this.connections.get(peerId) ?? [];\n await Promise.all(connections.map(async (connection) => {\n try {\n await connection.close(options);\n }\n catch (err) {\n connection.abort(err);\n }\n }));\n }\n async acceptIncomingConnection(maConn) {\n // check deny list\n const denyConnection = this.deny.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (denyConnection) {\n this.log('connection from %a refused - connection remote address was in deny list', maConn.remoteAddr);\n return false;\n }\n // check allow list\n const allowConnection = this.allow.some(ma => {\n return maConn.remoteAddr.toString().startsWith(ma.toString());\n });\n if (allowConnection) {\n this.incomingPendingConnections++;\n return true;\n }\n // check pending connections\n if (this.incomingPendingConnections === this.maxIncomingPendingConnections) {\n this.log('connection from %a refused - incomingPendingConnections exceeded by host', maConn.remoteAddr);\n return false;\n }\n if (maConn.remoteAddr.isThinWaistAddress()) {\n const host = maConn.remoteAddr.nodeAddress().address;\n try {\n await this.inboundConnectionRateLimiter.consume(host, 1);\n }\n catch {\n this.log('connection from %a refused - inboundConnectionThreshold exceeded by host %s', maConn.remoteAddr, host);\n return false;\n }\n }\n if (this.getConnections().length < this.maxConnections) {\n this.incomingPendingConnections++;\n return true;\n }\n this.log('connection from %a refused - maxConnections exceeded', maConn.remoteAddr);\n return false;\n }\n afterUpgradeInbound() {\n this.incomingPendingConnections--;\n }\n getDialQueue() {\n const statusMap = {\n queued: 'queued',\n running: 'active',\n errored: 'error',\n complete: 'success'\n };\n return this.dialQueue.queue.queue.map(job => {\n return {\n id: job.id,\n status: statusMap[job.status],\n peerId: job.options.peerId,\n multiaddrs: [...job.options.multiaddrs].map(ma => (0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.multiaddr)(ma))\n };\n });\n }\n async isDialable(multiaddr, options = {}) {\n return this.dialQueue.isDialable(multiaddr, options);\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js?"); /***/ }), @@ -12166,6 +16829,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-monitor.js": +/*!***********************************************************************************!*\ + !*** ./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-monitor.js ***! + \***********************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ ConnectionMonitor: () => (/* binding */ ConnectionMonitor)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/crypto */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/index.js\");\n/* harmony import */ var _libp2p_utils_adaptive_timeout__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/utils/adaptive-timeout */ \"./node_modules/@libp2p/utils/dist/src/adaptive-timeout.js\");\n/* harmony import */ var it_byte_stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-byte-stream */ \"./node_modules/it-byte-stream/dist/src/index.js\");\n\n\n\n\nconst DEFAULT_PING_INTERVAL_MS = 10000;\nconst PROTOCOL_VERSION = '1.0.0';\nconst PROTOCOL_NAME = 'ping';\nconst PROTOCOL_PREFIX = 'ipfs';\nconst PING_LENGTH = 32;\nclass ConnectionMonitor {\n protocol;\n components;\n log;\n heartbeatInterval;\n pingIntervalMs;\n abortController;\n timeout;\n constructor(components, init = {}) {\n this.components = components;\n this.protocol = `/${init.protocolPrefix ?? PROTOCOL_PREFIX}/${PROTOCOL_NAME}/${PROTOCOL_VERSION}`;\n this.log = components.logger.forComponent('libp2p:connection-monitor');\n this.pingIntervalMs = init.pingInterval ?? DEFAULT_PING_INTERVAL_MS;\n this.timeout = new _libp2p_utils_adaptive_timeout__WEBPACK_IMPORTED_MODULE_1__.AdaptiveTimeout({\n ...(init.pingTimeout ?? {}),\n metrics: components.metrics,\n metricName: 'libp2p_connection_monitor_ping_time_milliseconds'\n });\n }\n [Symbol.toStringTag] = '@libp2p/connection-monitor';\n [_libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.serviceCapabilities] = [\n '@libp2p/connection-monitor'\n ];\n start() {\n this.abortController = new AbortController();\n this.heartbeatInterval = setInterval(() => {\n this.components.connectionManager.getConnections().forEach(conn => {\n Promise.resolve().then(async () => {\n let start = Date.now();\n try {\n const signal = this.timeout.getTimeoutSignal({\n signal: this.abortController?.signal\n });\n const stream = await conn.newStream(this.protocol, {\n signal,\n runOnTransientConnection: true\n });\n const bs = (0,it_byte_stream__WEBPACK_IMPORTED_MODULE_0__.byteStream)(stream);\n start = Date.now();\n await Promise.all([\n bs.write((0,_libp2p_crypto__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(PING_LENGTH), {\n signal\n }),\n bs.read(PING_LENGTH, {\n signal\n })\n ]);\n conn.rtt = Date.now() - start;\n await bs.unwrap().close({\n signal\n });\n }\n catch (err) {\n if (err.code !== 'ERR_UNSUPPORTED_PROTOCOL') {\n throw err;\n }\n // protocol was unsupported, but that's ok as it means the remote\n // peer was still alive. We ran multistream-select which means two\n // round trips (e.g. 1x for the mss header, then another for the\n // protocol) so divide the time it took by two\n conn.rtt = (Date.now() - start) / 2;\n }\n })\n .catch(err => {\n this.log.error('error during heartbeat, aborting connection', err);\n conn.abort(err);\n });\n });\n }, this.pingIntervalMs);\n }\n stop() {\n this.abortController?.abort();\n if (this.heartbeatInterval != null) {\n clearInterval(this.heartbeatInterval);\n }\n }\n}\n//# sourceMappingURL=connection-monitor.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-monitor.js?"); + +/***/ }), + /***/ "./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection/index.js": /*!*********************************************************************************!*\ !*** ./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection/index.js ***! @@ -12184,7 +16858,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CompoundContentRouting: () => (/* binding */ CompoundContentRouting)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var it_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-merge */ \"./node_modules/it-merge/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\nclass CompoundContentRouting {\n routers;\n started;\n components;\n constructor(components, init) {\n this.routers = init.routers ?? [];\n this.started = false;\n this.components = components;\n }\n isStarted() {\n return this.started;\n }\n async start() {\n this.started = true;\n }\n async stop() {\n this.started = false;\n }\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async *findProviders(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('No content routers available', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_3__.PeerSet();\n for await (const peer of (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...self.routers.map(router => router.findProviders(key, options)))) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('No content routers available', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options);\n }));\n }\n /**\n * Store the given key/value pair in the available content routings\n */\n async put(key, value, options) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_2__.messages.NOT_STARTED_YET, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NODE_NOT_STARTED);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options);\n }));\n }\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get(key, options) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_2__.messages.NOT_STARTED_YET, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NODE_NOT_STARTED);\n }\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options);\n }));\n }\n}\n//# sourceMappingURL=content-routing.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/content-routing.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CompoundContentRouting: () => (/* binding */ CompoundContentRouting)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var it_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-merge */ \"./node_modules/it-merge/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\nclass CompoundContentRouting {\n routers;\n started;\n components;\n constructor(components, init) {\n this.routers = init.routers ?? [];\n this.started = false;\n this.components = components;\n }\n [Symbol.toStringTag] = '@libp2p/content-routing';\n isStarted() {\n return this.started;\n }\n async start() {\n this.started = true;\n }\n async stop() {\n this.started = false;\n }\n /**\n * Iterates over all content routers in parallel to find providers of the given key\n */\n async *findProviders(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('No content routers available', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_3__.PeerSet();\n for await (const peer of (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...self.routers.map(router => router.findProviders(key, options)))) {\n // the peer was yielded by a content router without multiaddrs and we\n // failed to load them\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n /**\n * Iterates over all content routers in parallel to notify it is\n * a provider of the given key\n */\n async provide(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('No content routers available', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.provide(key, options);\n }));\n }\n /**\n * Store the given key/value pair in the available content routings\n */\n async put(key, value, options) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_2__.messages.NOT_STARTED_YET, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NODE_NOT_STARTED);\n }\n await Promise.all(this.routers.map(async (router) => {\n await router.put(key, value, options);\n }));\n }\n /**\n * Get the value to the given key.\n * Times out after 1 minute by default.\n */\n async get(key, options) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_2__.messages.NOT_STARTED_YET, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NODE_NOT_STARTED);\n }\n return Promise.any(this.routers.map(async (router) => {\n return router.get(key, options);\n }));\n }\n}\n//# sourceMappingURL=content-routing.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/content-routing.js?"); /***/ }), @@ -12206,7 +16880,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getPeerAddress: () => (/* binding */ getPeerAddress)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nfunction getPeerAddress(peer) {\n if ((0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.isPeerId)(peer)) {\n return { peerId: peer, multiaddrs: [] };\n }\n if (!Array.isArray(peer)) {\n peer = [peer];\n }\n let peerId;\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId();\n peerId = peerIdStr == null ? undefined : (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromString)(peerIdStr);\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.isMultiaddr)(ma)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Invalid Multiaddr', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_MULTIADDR);\n }\n const maPeerIdStr = ma.getPeerId();\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Multiaddrs must all have the same peer id or have no peer id', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_PARAMETERS);\n }\n }\n else {\n const maPeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromString)(maPeerIdStr);\n if (peerId == null || !peerId.equals(maPeerId)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Multiaddrs must all have the same peer id or have no peer id', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_PARAMETERS);\n }\n }\n });\n }\n return {\n peerId,\n multiaddrs: peer\n };\n}\n//# sourceMappingURL=get-peer.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ getPeerAddress: () => (/* binding */ getPeerAddress)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-id/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n/**\n * Extracts a PeerId and/or multiaddr from the passed PeerId or Multiaddr or an array of Multiaddrs\n */\nfunction getPeerAddress(peer) {\n if ((0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.isPeerId)(peer)) {\n return { peerId: peer, multiaddrs: [] };\n }\n if (!Array.isArray(peer)) {\n peer = [peer];\n }\n let peerId;\n if (peer.length > 0) {\n const peerIdStr = peer[0].getPeerId();\n peerId = peerIdStr == null ? undefined : (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromString)(peerIdStr);\n // ensure PeerId is either not set or is consistent\n peer.forEach(ma => {\n if (!(0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.isMultiaddr)(ma)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Invalid Multiaddr', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_MULTIADDR);\n }\n const maPeerIdStr = ma.getPeerId();\n if (maPeerIdStr == null) {\n if (peerId != null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Multiaddrs must all have the same peer id or have no peer id', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_PARAMETERS);\n }\n }\n else {\n const maPeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_2__.peerIdFromString)(maPeerIdStr);\n if (peerId?.equals(maPeerId) !== true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Multiaddrs must all have the same peer id or have no peer id', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_PARAMETERS);\n }\n }\n });\n }\n return {\n peerId,\n multiaddrs: peer\n };\n}\n//# sourceMappingURL=get-peer.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/get-peer.js?"); /***/ }), @@ -12228,7 +16902,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Libp2pNode: () => (/* binding */ Libp2pNode),\n/* harmony export */ createLibp2pNode: () => (/* binding */ createLibp2pNode)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/logger */ \"./node_modules/@waku/sdk/node_modules/@libp2p/logger/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_id_factory__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! @libp2p/peer-id-factory */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_store__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/peer-store */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var datastore_core_memory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! datastore-core/memory */ \"./node_modules/datastore-core/dist/src/memory.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _address_manager_index_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./address-manager/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/index.js\");\n/* harmony import */ var _components_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/components.js\");\n/* harmony import */ var _config_connection_gater_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./config/connection-gater.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config/connection-gater.browser.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./config.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config.js\");\n/* harmony import */ var _connection_manager_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./connection-manager/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js\");\n/* harmony import */ var _content_routing_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./content-routing.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/content-routing.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _peer_routing_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./peer-routing.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/peer-routing.js\");\n/* harmony import */ var _registrar_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./registrar.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js\");\n/* harmony import */ var _transport_manager_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./transport-manager.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/transport-manager.js\");\n/* harmony import */ var _upgrader_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./upgrader.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/upgrader.js\");\n/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./version.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/version.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Libp2pNode extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.TypedEventEmitter {\n peerId;\n peerStore;\n contentRouting;\n peerRouting;\n metrics;\n services;\n logger;\n status;\n components;\n log;\n constructor(init) {\n super();\n this.status = 'stopped';\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.TypedEventEmitter();\n const originalDispatch = events.dispatchEvent.bind(events);\n events.dispatchEvent = (evt) => {\n const internalResult = originalDispatch(evt);\n const externalResult = this.dispatchEvent(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CustomEvent(evt.type, { detail: evt.detail }));\n return internalResult || externalResult;\n };\n // This emitter gets listened to a lot\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.setMaxListeners)(Infinity, events);\n this.peerId = init.peerId;\n this.logger = init.logger ?? (0,_libp2p_logger__WEBPACK_IMPORTED_MODULE_6__.defaultLogger)();\n this.log = this.logger.forComponent('libp2p');\n // @ts-expect-error {} may not be of type T\n this.services = {};\n const components = this.components = (0,_components_js__WEBPACK_IMPORTED_MODULE_7__.defaultComponents)({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: _version_js__WEBPACK_IMPORTED_MODULE_8__.name,\n version: _version_js__WEBPACK_IMPORTED_MODULE_8__.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new datastore_core_memory__WEBPACK_IMPORTED_MODULE_1__.MemoryDatastore(),\n connectionGater: (0,_config_connection_gater_js__WEBPACK_IMPORTED_MODULE_9__.connectionGater)(init.connectionGater),\n dns: init.dns\n });\n this.peerStore = this.configureComponent('peerStore', new _libp2p_peer_store__WEBPACK_IMPORTED_MODULE_10__.PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }));\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components));\n }\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n };\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo });\n }\n });\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components));\n }\n // Set up the Upgrader\n this.components.upgrader = new _upgrader_js__WEBPACK_IMPORTED_MODULE_11__.DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n muxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager.inboundUpgradeTimeout\n });\n // Setup the transport manager\n this.configureComponent('transportManager', new _transport_manager_js__WEBPACK_IMPORTED_MODULE_12__.DefaultTransportManager(this.components, init.transportManager));\n // Create the Connection Manager\n this.configureComponent('connectionManager', new _connection_manager_index_js__WEBPACK_IMPORTED_MODULE_13__.DefaultConnectionManager(this.components, init.connectionManager));\n // Create the Registrar\n this.configureComponent('registrar', new _registrar_js__WEBPACK_IMPORTED_MODULE_14__.DefaultRegistrar(this.components));\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new _address_manager_index_js__WEBPACK_IMPORTED_MODULE_15__.DefaultAddressManager(this.components, init.addresses));\n // Peer routers\n const peerRouters = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)));\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new _peer_routing_js__WEBPACK_IMPORTED_MODULE_16__.DefaultPeerRouting(this.components, {\n routers: peerRouters\n }));\n // Content routers\n const contentRouters = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)));\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new _content_routing_js__WEBPACK_IMPORTED_MODULE_17__.CompoundContentRouting(this.components, {\n routers: contentRouters\n }));\n (init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components));\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n });\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)));\n });\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name];\n const service = createService(this.components);\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name);\n continue;\n }\n this.services[name] = service;\n this.configureComponent(name, service);\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_18__.contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name);\n contentRouters.push(service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_18__.contentRoutingSymbol]);\n }\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_19__.peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name);\n peerRouters.push(service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_19__.peerRoutingSymbol]);\n }\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_20__.peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name);\n service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_20__.peerDiscoverySymbol].addEventListener?.('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n }\n }\n }\n }\n configureComponent(name, component) {\n if (component == null) {\n this.log.error('component %s was null or undefined', name);\n }\n this.components[name] = component;\n return component;\n }\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start() {\n if (this.status !== 'stopped') {\n return;\n }\n this.status = 'starting';\n this.log('libp2p is starting');\n try {\n await this.components.beforeStart?.();\n await this.components.start();\n await this.components.afterStart?.();\n this.status = 'started';\n this.safeDispatchEvent('start', { detail: this });\n this.log('libp2p has started');\n }\n catch (err) {\n this.log.error('An error occurred starting libp2p', err);\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started';\n await this.stop();\n throw err;\n }\n }\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop() {\n if (this.status !== 'started') {\n return;\n }\n this.log('libp2p is stopping');\n this.status = 'stopping';\n await this.components.beforeStop?.();\n await this.components.stop();\n await this.components.afterStop?.();\n this.status = 'stopped';\n this.safeDispatchEvent('stop', { detail: this });\n this.log('libp2p has stopped');\n }\n getConnections(peerId) {\n return this.components.connectionManager.getConnections(peerId);\n }\n getDialQueue() {\n return this.components.connectionManager.getDialQueue();\n }\n getPeers() {\n const peerSet = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_21__.PeerSet();\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer);\n }\n return Array.from(peerSet);\n }\n async dial(peer, options = {}) {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n });\n }\n async dialProtocol(peer, protocols, options = {}) {\n if (protocols == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_22__.CodeError('no protocols were provided to open a stream', _errors_js__WEBPACK_IMPORTED_MODULE_23__.codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n if (protocols.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_22__.CodeError('no protocols were provided to open a stream', _errors_js__WEBPACK_IMPORTED_MODULE_23__.codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n const connection = await this.dial(peer, options);\n return connection.newStream(protocols, options);\n }\n getMultiaddrs() {\n return this.components.addressManager.getAddresses();\n }\n getProtocols() {\n return this.components.registrar.getProtocols();\n }\n async hangUp(peer, options = {}) {\n if ((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.isMultiaddr)(peer)) {\n peer = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_24__.peerIdFromString)(peer.getPeerId() ?? '');\n }\n await this.components.connectionManager.closeConnections(peer, options);\n }\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey(peer, options = {}) {\n this.log('getPublicKey %p', peer);\n if (peer.publicKey != null) {\n return peer.publicKey;\n }\n try {\n const peerInfo = await this.peerStore.get(peer);\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey;\n }\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_23__.codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n const peerKey = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_2__.concat)([\n (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)('/pk/'),\n peer.multihash.digest\n ]);\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options);\n // ensure the returned key is valid\n (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_25__.unmarshalPublicKey)(bytes);\n await this.peerStore.patch(peer, {\n publicKey: bytes\n });\n return bytes;\n }\n async handle(protocols, handler, options) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.handle(protocol, handler, options);\n }));\n }\n async unhandle(protocols) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.unhandle(protocol);\n }));\n }\n async register(protocol, topology) {\n return this.components.registrar.register(protocol, topology);\n }\n unregister(id) {\n this.components.registrar.unregister(id);\n }\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer(evt) {\n const { detail: peer } = evt;\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error(new Error(_errors_js__WEBPACK_IMPORTED_MODULE_23__.codes.ERR_DISCOVERED_SELF));\n return;\n }\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err); });\n }\n}\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nasync function createLibp2pNode(options = {}) {\n const peerId = options.peerId ??= await (0,_libp2p_peer_id_factory__WEBPACK_IMPORTED_MODULE_26__.createEd25519PeerId)();\n if (peerId.privateKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_22__.CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY');\n }\n options.privateKey ??= await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_25__.unmarshalPrivateKey)(peerId.privateKey);\n return new Libp2pNode(await (0,_config_js__WEBPACK_IMPORTED_MODULE_27__.validateConfig)(options));\n}\n//# sourceMappingURL=libp2p.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/libp2p.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Libp2pNode: () => (/* binding */ Libp2pNode),\n/* harmony export */ createLibp2pNode: () => (/* binding */ createLibp2pNode)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! @libp2p/crypto/keys */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/keys/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/content-routing/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-routing/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/peer-discovery/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/logger */ \"./node_modules/@libp2p/logger/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_id_factory__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! @libp2p/peer-id-factory */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id-factory/dist/src/index.js\");\n/* harmony import */ var _libp2p_peer_store__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @libp2p/peer-store */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-store/dist/src/index.js\");\n/* harmony import */ var _multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @multiformats/multiaddr */ \"./node_modules/@multiformats/multiaddr/dist/src/index.js\");\n/* harmony import */ var datastore_core_memory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! datastore-core/memory */ \"./node_modules/datastore-core/dist/src/memory.js\");\n/* harmony import */ var uint8arrays_concat__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arrays/concat */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/concat.js\");\n/* harmony import */ var uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! uint8arrays/from-string */ \"./node_modules/@waku/sdk/node_modules/uint8arrays/dist/src/from-string.js\");\n/* harmony import */ var _address_manager_index_js__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./address-manager/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/address-manager/index.js\");\n/* harmony import */ var _components_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./components.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/components.js\");\n/* harmony import */ var _config_connection_gater_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./config/connection-gater.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config/connection-gater.browser.js\");\n/* harmony import */ var _config_js__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./config.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/config.js\");\n/* harmony import */ var _connection_manager_index_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./connection-manager/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/index.js\");\n/* harmony import */ var _connection_monitor_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./connection-monitor.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-monitor.js\");\n/* harmony import */ var _content_routing_js__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./content-routing.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/content-routing.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _peer_routing_js__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./peer-routing.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/peer-routing.js\");\n/* harmony import */ var _random_walk_js__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./random-walk.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/random-walk.js\");\n/* harmony import */ var _registrar_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./registrar.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js\");\n/* harmony import */ var _transport_manager_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./transport-manager.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/transport-manager.js\");\n/* harmony import */ var _upgrader_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./upgrader.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/upgrader.js\");\n/* harmony import */ var _version_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./version.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/version.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nclass Libp2pNode extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.TypedEventEmitter {\n peerId;\n peerStore;\n contentRouting;\n peerRouting;\n metrics;\n services;\n logger;\n status;\n components;\n log;\n constructor(init) {\n super();\n this.status = 'stopped';\n // event bus - components can listen to this emitter to be notified of system events\n // and also cause them to be emitted\n const events = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.TypedEventEmitter();\n const originalDispatch = events.dispatchEvent.bind(events);\n events.dispatchEvent = (evt) => {\n const internalResult = originalDispatch(evt);\n const externalResult = this.dispatchEvent(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CustomEvent(evt.type, { detail: evt.detail }));\n return internalResult || externalResult;\n };\n // This emitter gets listened to a lot\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.setMaxListeners)(Infinity, events);\n this.peerId = init.peerId;\n this.logger = init.logger ?? (0,_libp2p_logger__WEBPACK_IMPORTED_MODULE_6__.defaultLogger)();\n this.log = this.logger.forComponent('libp2p');\n // @ts-expect-error {} may not be of type T\n this.services = {};\n // @ts-expect-error defaultComponents is missing component types added later\n const components = this.components = (0,_components_js__WEBPACK_IMPORTED_MODULE_7__.defaultComponents)({\n peerId: init.peerId,\n privateKey: init.privateKey,\n nodeInfo: init.nodeInfo ?? {\n name: _version_js__WEBPACK_IMPORTED_MODULE_8__.name,\n version: _version_js__WEBPACK_IMPORTED_MODULE_8__.version\n },\n logger: this.logger,\n events,\n datastore: init.datastore ?? new datastore_core_memory__WEBPACK_IMPORTED_MODULE_1__.MemoryDatastore(),\n connectionGater: (0,_config_connection_gater_js__WEBPACK_IMPORTED_MODULE_9__.connectionGater)(init.connectionGater),\n dns: init.dns\n });\n this.peerStore = this.configureComponent('peerStore', new _libp2p_peer_store__WEBPACK_IMPORTED_MODULE_10__.PersistentPeerStore(components, {\n addressFilter: this.components.connectionGater.filterMultiaddrForPeer,\n ...init.peerStore\n }));\n // Create Metrics\n if (init.metrics != null) {\n this.metrics = this.configureComponent('metrics', init.metrics(this.components));\n }\n components.events.addEventListener('peer:update', evt => {\n // if there was no peer previously in the peer store this is a new peer\n if (evt.detail.previous == null) {\n const peerInfo = {\n id: evt.detail.peer.id,\n multiaddrs: evt.detail.peer.addresses.map(a => a.multiaddr)\n };\n components.events.safeDispatchEvent('peer:discovery', { detail: peerInfo });\n }\n });\n // Set up connection protector if configured\n if (init.connectionProtector != null) {\n this.configureComponent('connectionProtector', init.connectionProtector(components));\n }\n // Set up the Upgrader\n this.components.upgrader = new _upgrader_js__WEBPACK_IMPORTED_MODULE_11__.DefaultUpgrader(this.components, {\n connectionEncryption: (init.connectionEncryption ?? []).map((fn, index) => this.configureComponent(`connection-encryption-${index}`, fn(this.components))),\n muxers: (init.streamMuxers ?? []).map((fn, index) => this.configureComponent(`stream-muxers-${index}`, fn(this.components))),\n inboundUpgradeTimeout: init.connectionManager?.inboundUpgradeTimeout\n });\n // Setup the transport manager\n this.configureComponent('transportManager', new _transport_manager_js__WEBPACK_IMPORTED_MODULE_12__.DefaultTransportManager(this.components, init.transportManager));\n // Create the Connection Manager\n this.configureComponent('connectionManager', new _connection_manager_index_js__WEBPACK_IMPORTED_MODULE_13__.DefaultConnectionManager(this.components, init.connectionManager));\n if (init.connectionMonitor?.enabled !== false) {\n // Create the Connection Monitor if not disabled\n this.configureComponent('connectionMonitor', new _connection_monitor_js__WEBPACK_IMPORTED_MODULE_14__.ConnectionMonitor(this.components, init.connectionMonitor));\n }\n // Create the Registrar\n this.configureComponent('registrar', new _registrar_js__WEBPACK_IMPORTED_MODULE_15__.DefaultRegistrar(this.components));\n // Addresses {listen, announce, noAnnounce}\n this.configureComponent('addressManager', new _address_manager_index_js__WEBPACK_IMPORTED_MODULE_16__.DefaultAddressManager(this.components, init.addresses));\n // Peer routers\n const peerRouters = (init.peerRouters ?? []).map((fn, index) => this.configureComponent(`peer-router-${index}`, fn(this.components)));\n this.peerRouting = this.components.peerRouting = this.configureComponent('peerRouting', new _peer_routing_js__WEBPACK_IMPORTED_MODULE_17__.DefaultPeerRouting(this.components, {\n routers: peerRouters\n }));\n // Content routers\n const contentRouters = (init.contentRouters ?? []).map((fn, index) => this.configureComponent(`content-router-${index}`, fn(this.components)));\n this.contentRouting = this.components.contentRouting = this.configureComponent('contentRouting', new _content_routing_js__WEBPACK_IMPORTED_MODULE_18__.CompoundContentRouting(this.components, {\n routers: contentRouters\n }));\n // Random walk\n this.configureComponent('randomWalk', new _random_walk_js__WEBPACK_IMPORTED_MODULE_19__.RandomWalk(this.components));\n (init.peerDiscovery ?? []).forEach((fn, index) => {\n const service = this.configureComponent(`peer-discovery-${index}`, fn(this.components));\n service.addEventListener('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n });\n // Transport modules\n init.transports?.forEach((fn, index) => {\n this.components.transportManager.add(this.configureComponent(`transport-${index}`, fn(this.components)));\n });\n // User defined modules\n if (init.services != null) {\n for (const name of Object.keys(init.services)) {\n const createService = init.services[name];\n const service = createService(this.components);\n if (service == null) {\n this.log.error('service factory %s returned null or undefined instance', name);\n continue;\n }\n this.services[name] = service;\n this.configureComponent(name, service);\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_20__.contentRoutingSymbol] != null) {\n this.log('registering service %s for content routing', name);\n contentRouters.push(service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_20__.contentRoutingSymbol]);\n }\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_21__.peerRoutingSymbol] != null) {\n this.log('registering service %s for peer routing', name);\n peerRouters.push(service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_21__.peerRoutingSymbol]);\n }\n if (service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_22__.peerDiscoverySymbol] != null) {\n this.log('registering service %s for peer discovery', name);\n service[_libp2p_interface__WEBPACK_IMPORTED_MODULE_22__.peerDiscoverySymbol].addEventListener?.('peer', (evt) => {\n this.#onDiscoveryPeer(evt);\n });\n }\n }\n }\n // Ensure all services have their required dependencies\n (0,_components_js__WEBPACK_IMPORTED_MODULE_7__.checkServiceDependencies)(components);\n }\n configureComponent(name, component) {\n if (component == null) {\n this.log.error('component %s was null or undefined', name);\n }\n // @ts-expect-error cannot assign props\n this.components[name] = component;\n return component;\n }\n /**\n * Starts the libp2p node and all its subsystems\n */\n async start() {\n if (this.status !== 'stopped') {\n return;\n }\n this.status = 'starting';\n this.log('libp2p is starting');\n try {\n await this.components.beforeStart?.();\n await this.components.start();\n await this.components.afterStart?.();\n this.status = 'started';\n this.safeDispatchEvent('start', { detail: this });\n this.log('libp2p has started');\n }\n catch (err) {\n this.log.error('An error occurred starting libp2p', err);\n // set status to 'started' so this.stop() will stop any running components\n this.status = 'started';\n await this.stop();\n throw err;\n }\n }\n /**\n * Stop the libp2p node by closing its listeners and open connections\n */\n async stop() {\n if (this.status !== 'started') {\n return;\n }\n this.log('libp2p is stopping');\n this.status = 'stopping';\n await this.components.beforeStop?.();\n await this.components.stop();\n await this.components.afterStop?.();\n this.status = 'stopped';\n this.safeDispatchEvent('stop', { detail: this });\n this.log('libp2p has stopped');\n }\n getConnections(peerId) {\n return this.components.connectionManager.getConnections(peerId);\n }\n getDialQueue() {\n return this.components.connectionManager.getDialQueue();\n }\n getPeers() {\n const peerSet = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_23__.PeerSet();\n for (const conn of this.components.connectionManager.getConnections()) {\n peerSet.add(conn.remotePeer);\n }\n return Array.from(peerSet);\n }\n async dial(peer, options = {}) {\n return this.components.connectionManager.openConnection(peer, {\n // ensure any userland dials take top priority in the queue\n priority: 75,\n ...options\n });\n }\n async dialProtocol(peer, protocols, options = {}) {\n if (protocols == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_24__.CodeError('no protocols were provided to open a stream', _errors_js__WEBPACK_IMPORTED_MODULE_25__.codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n protocols = Array.isArray(protocols) ? protocols : [protocols];\n if (protocols.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_24__.CodeError('no protocols were provided to open a stream', _errors_js__WEBPACK_IMPORTED_MODULE_25__.codes.ERR_INVALID_PROTOCOLS_FOR_STREAM);\n }\n const connection = await this.dial(peer, options);\n return connection.newStream(protocols, options);\n }\n getMultiaddrs() {\n return this.components.addressManager.getAddresses();\n }\n getProtocols() {\n return this.components.registrar.getProtocols();\n }\n async hangUp(peer, options = {}) {\n if ((0,_multiformats_multiaddr__WEBPACK_IMPORTED_MODULE_0__.isMultiaddr)(peer)) {\n peer = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_26__.peerIdFromString)(peer.getPeerId() ?? '');\n }\n await this.components.connectionManager.closeConnections(peer, options);\n }\n /**\n * Get the public key for the given peer id\n */\n async getPublicKey(peer, options = {}) {\n this.log('getPublicKey %p', peer);\n if (peer.publicKey != null) {\n return peer.publicKey;\n }\n try {\n const peerInfo = await this.peerStore.get(peer);\n if (peerInfo.id.publicKey != null) {\n return peerInfo.id.publicKey;\n }\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_25__.codes.ERR_NOT_FOUND) {\n throw err;\n }\n }\n const peerKey = (0,uint8arrays_concat__WEBPACK_IMPORTED_MODULE_2__.concat)([\n (0,uint8arrays_from_string__WEBPACK_IMPORTED_MODULE_3__.fromString)('/pk/'),\n peer.multihash.digest\n ]);\n // search any available content routing methods\n const bytes = await this.contentRouting.get(peerKey, options);\n // ensure the returned key is valid\n (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_27__.unmarshalPublicKey)(bytes);\n await this.peerStore.patch(peer, {\n publicKey: bytes\n });\n return bytes;\n }\n async handle(protocols, handler, options) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.handle(protocol, handler, options);\n }));\n }\n async unhandle(protocols) {\n if (!Array.isArray(protocols)) {\n protocols = [protocols];\n }\n await Promise.all(protocols.map(async (protocol) => {\n await this.components.registrar.unhandle(protocol);\n }));\n }\n async register(protocol, topology) {\n return this.components.registrar.register(protocol, topology);\n }\n unregister(id) {\n this.components.registrar.unregister(id);\n }\n async isDialable(multiaddr, options = {}) {\n return this.components.connectionManager.isDialable(multiaddr, options);\n }\n /**\n * Called whenever peer discovery services emit `peer` events and adds peers\n * to the peer store.\n */\n #onDiscoveryPeer(evt) {\n const { detail: peer } = evt;\n if (peer.id.toString() === this.peerId.toString()) {\n this.log.error(new Error(_errors_js__WEBPACK_IMPORTED_MODULE_25__.codes.ERR_DISCOVERED_SELF));\n return;\n }\n void this.components.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n })\n .catch(err => { this.log.error(err); });\n }\n}\n/**\n * Returns a new Libp2pNode instance - this exposes more of the internals than the\n * libp2p interface and is useful for testing and debugging.\n */\nasync function createLibp2pNode(options = {}) {\n const peerId = options.peerId ??= await (0,_libp2p_peer_id_factory__WEBPACK_IMPORTED_MODULE_28__.createEd25519PeerId)();\n if (peerId.privateKey == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_24__.CodeError('peer id was missing private key', 'ERR_MISSING_PRIVATE_KEY');\n }\n options.privateKey ??= await (0,_libp2p_crypto_keys__WEBPACK_IMPORTED_MODULE_27__.unmarshalPrivateKey)(peerId.privateKey);\n return new Libp2pNode(await (0,_config_js__WEBPACK_IMPORTED_MODULE_29__.validateConfig)(options));\n}\n//# sourceMappingURL=libp2p.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/libp2p.js?"); /***/ }), @@ -12239,7 +16913,18 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultPeerRouting: () => (/* binding */ DefaultPeerRouting)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/peer-collections */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-collections/dist/src/set.js\");\n/* harmony import */ var it_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-merge */ \"./node_modules/it-merge/dist/src/index.js\");\n/* harmony import */ var it_parallel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-parallel */ \"./node_modules/it-parallel/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n\nclass DefaultPeerRouting {\n log;\n peerId;\n peerStore;\n routers;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing');\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.routers = init.routers ?? [];\n }\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer(id, options) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('No peer routers available', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n if (id.toString() === this.peerId.toString()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('Should not try to find self', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_FIND_SELF);\n }\n const self = this;\n const source = (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...this.routers.map(router => (async function* () {\n try {\n yield await router.findPeer(id, options);\n }\n catch (err) {\n self.log.error(err);\n }\n })()));\n for await (const peer of source) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n return peer;\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_3__.messages.NOT_FOUND, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NOT_FOUND);\n }\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async *getClosestPeers(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('No peer routers available', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = new _libp2p_peer_collections__WEBPACK_IMPORTED_MODULE_4__.PeerSet();\n for await (const peer of (0,it_parallel__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(async function* () {\n const source = (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...self.routers.map(router => router.getClosestPeers(key, options)));\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n });\n }\n catch (err) {\n self.log.error('could not find peer multiaddrs', err);\n return;\n }\n }\n return peer;\n };\n }\n }())) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id)) {\n continue;\n }\n seen.add(peer.id);\n yield peer;\n }\n }\n}\n//# sourceMappingURL=peer-routing.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/peer-routing.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultPeerRouting: () => (/* binding */ DefaultPeerRouting)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_utils_filters__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/utils/filters */ \"./node_modules/@libp2p/utils/dist/src/filters/scalable-cuckoo-filter.js\");\n/* harmony import */ var it_merge__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-merge */ \"./node_modules/it-merge/dist/src/index.js\");\n/* harmony import */ var it_parallel__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! it-parallel */ \"./node_modules/it-parallel/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\n\nclass DefaultPeerRouting {\n log;\n peerId;\n peerStore;\n routers;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:peer-routing');\n this.peerId = components.peerId;\n this.peerStore = components.peerStore;\n this.routers = init.routers ?? [];\n }\n [Symbol.toStringTag] = '@libp2p/peer-routing';\n /**\n * Iterates over all peer routers in parallel to find the given peer\n */\n async findPeer(id, options) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('No peer routers available', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n if (id.toString() === this.peerId.toString()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('Should not try to find self', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_FIND_SELF);\n }\n const self = this;\n const source = (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...this.routers.map(router => (async function* () {\n try {\n yield await router.findPeer(id, options);\n }\n catch (err) {\n self.log.error(err);\n }\n })()));\n for await (const peer of source) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n return peer;\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(_errors_js__WEBPACK_IMPORTED_MODULE_3__.messages.NOT_FOUND, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NOT_FOUND);\n }\n /**\n * Attempt to find the closest peers on the network to the given key\n */\n async *getClosestPeers(key, options = {}) {\n if (this.routers.length === 0) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('No peer routers available', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_ROUTERS_AVAILABLE);\n }\n const self = this;\n const seen = (0,_libp2p_utils_filters__WEBPACK_IMPORTED_MODULE_4__.createScalableCuckooFilter)(1024);\n for await (const peer of (0,it_parallel__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(async function* () {\n const source = (0,it_merge__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(...self.routers.map(router => router.getClosestPeers(key, options)));\n for await (let peer of source) {\n yield async () => {\n // find multiaddrs if they are missing\n if (peer.multiaddrs.length === 0) {\n try {\n peer = await self.findPeer(peer.id, {\n ...options,\n useCache: false\n });\n }\n catch (err) {\n self.log.error('could not find peer multiaddrs', err);\n return;\n }\n }\n return peer;\n };\n }\n }())) {\n if (peer == null) {\n continue;\n }\n // store the addresses for the peer if found\n if (peer.multiaddrs.length > 0) {\n await this.peerStore.merge(peer.id, {\n multiaddrs: peer.multiaddrs\n });\n }\n // deduplicate peers\n if (seen.has(peer.id.toBytes())) {\n continue;\n }\n seen.add(peer.id.toBytes());\n yield peer;\n }\n }\n}\n//# sourceMappingURL=peer-routing.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/peer-routing.js?"); + +/***/ }), + +/***/ "./node_modules/@waku/sdk/node_modules/libp2p/dist/src/random-walk.js": +/*!****************************************************************************!*\ + !*** ./node_modules/@waku/sdk/node_modules/libp2p/dist/src/random-walk.js ***! + \****************************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ RandomWalk: () => (/* binding */ RandomWalk)\n/* harmony export */ });\n/* harmony import */ var _libp2p_crypto__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/crypto */ \"./node_modules/@waku/sdk/node_modules/@libp2p/crypto/dist/src/random-bytes.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/event-target.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var any_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! any-signal */ \"./node_modules/any-signal/dist/src/index.js\");\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var race_event__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! race-event */ \"./node_modules/race-event/dist/src/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n\n\n\n\n\n\nclass RandomWalk extends _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.TypedEventEmitter {\n peerRouting;\n log;\n walking;\n walkers;\n shutdownController;\n walkController;\n needNext;\n constructor(components) {\n super();\n this.log = components.logger.forComponent('libp2p:random-walk');\n this.peerRouting = components.peerRouting;\n this.walkers = 0;\n this.walking = false;\n // stops any in-progress walks when the node is shut down\n this.shutdownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, this.shutdownController.signal);\n }\n [Symbol.toStringTag] = '@libp2p/random-walk';\n start() {\n this.shutdownController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, this.shutdownController.signal);\n }\n stop() {\n this.shutdownController.abort();\n }\n async *walk(options) {\n if (!this.walking) {\n // start the query that causes walk:peer events to be emitted\n this.startWalk();\n }\n this.walkers++;\n const signal = (0,any_signal__WEBPACK_IMPORTED_MODULE_0__.anySignal)([this.shutdownController.signal, options?.signal]);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, signal);\n try {\n while (true) {\n // if another consumer has paused the query, start it again\n this.needNext?.resolve();\n this.needNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_5__[\"default\"])();\n // wait for a walk:peer or walk:error event\n const event = await (0,race_event__WEBPACK_IMPORTED_MODULE_1__.raceEvent)(this, 'walk:peer', signal, {\n errorEvent: 'walk:error'\n });\n yield event.detail;\n }\n }\n finally {\n signal.clear();\n this.walkers--;\n // stop the walk if no more consumers are interested\n if (this.walkers === 0) {\n this.walkController?.abort();\n this.walkController = undefined;\n }\n }\n }\n startWalk() {\n this.walking = true;\n // the signal for this controller will be aborted if no more random peers\n // are required\n this.walkController = new AbortController();\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, this.walkController.signal);\n const signal = (0,any_signal__WEBPACK_IMPORTED_MODULE_0__.anySignal)([this.walkController.signal, this.shutdownController.signal]);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, signal);\n const start = Date.now();\n let found = 0;\n Promise.resolve().then(async () => {\n this.log('start walk');\n // find peers until no more consumers are interested\n while (this.walkers > 0) {\n try {\n const data = (0,_libp2p_crypto__WEBPACK_IMPORTED_MODULE_6__[\"default\"])(32);\n let s = Date.now();\n for await (const peer of this.peerRouting.getClosestPeers(data, { signal })) {\n if (signal.aborted) {\n this.log('aborting walk');\n }\n signal.throwIfAborted();\n this.log('found peer %p after %dms for %d walkers', peer.id, Date.now() - s, this.walkers);\n found++;\n this.safeDispatchEvent('walk:peer', {\n detail: peer\n });\n // if we only have one consumer, pause the query until they request\n // another random peer or they signal they are no longer interested\n if (this.walkers === 1 && this.needNext != null) {\n this.log('wait for need next');\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_2__.raceSignal)(this.needNext.promise, signal);\n }\n s = Date.now();\n }\n this.log('walk iteration for %b and %d walkers finished, found %d peers', data, this.walkers, found);\n }\n catch (err) {\n this.log.error('randomwalk errored', err);\n this.safeDispatchEvent('walk:error', {\n detail: err\n });\n }\n }\n this.log('no walkers left, ended walk');\n })\n .catch(err => {\n this.log.error('randomwalk errored', err);\n })\n .finally(() => {\n this.log('finished walk, found %d peers after %dms', found, Date.now() - start);\n this.walking = false;\n });\n }\n}\n//# sourceMappingURL=random-walk.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/random-walk.js?"); /***/ }), @@ -12250,7 +16935,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_MAX_INBOUND_STREAMS: () => (/* binding */ DEFAULT_MAX_INBOUND_STREAMS),\n/* harmony export */ DEFAULT_MAX_OUTBOUND_STREAMS: () => (/* binding */ DEFAULT_MAX_OUTBOUND_STREAMS),\n/* harmony export */ DefaultRegistrar: () => (/* binding */ DefaultRegistrar)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var merge_options__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! merge-options */ \"./node_modules/merge-options/index.mjs\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\nconst DEFAULT_MAX_INBOUND_STREAMS = 32;\nconst DEFAULT_MAX_OUTBOUND_STREAMS = 64;\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nclass DefaultRegistrar {\n log;\n topologies;\n handlers;\n components;\n constructor(components) {\n this.log = components.logger.forComponent('libp2p:registrar');\n this.topologies = new Map();\n this.handlers = new Map();\n this.components = components;\n this._onDisconnect = this._onDisconnect.bind(this);\n this._onPeerUpdate = this._onPeerUpdate.bind(this);\n this._onPeerIdentify = this._onPeerIdentify.bind(this);\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect);\n this.components.events.addEventListener('peer:update', this._onPeerUpdate);\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify);\n }\n getProtocols() {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort();\n }\n getHandler(protocol) {\n const handler = this.handlers.get(protocol);\n if (handler == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(`No handler registered for protocol ${protocol}`, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_HANDLER_FOR_PROTOCOL);\n }\n return handler;\n }\n getTopologies(protocol) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n return [];\n }\n return [\n ...topologies.values()\n ];\n }\n /**\n * Registers the `handler` for each protocol\n */\n async handle(protocol, handler, opts) {\n if (this.handlers.has(protocol)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(`Handler already registered for protocol ${protocol}`, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);\n }\n const options = merge_options__WEBPACK_IMPORTED_MODULE_0__[\"default\"].bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts);\n this.handlers.set(protocol, {\n handler,\n options\n });\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n });\n }\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle(protocols) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols];\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol);\n });\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n });\n }\n /**\n * Register handlers for a set of multicodecs given\n */\n async register(protocol, topology) {\n if (topology == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('invalid topology', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_INVALID_PARAMETERS);\n }\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`;\n let topologies = this.topologies.get(protocol);\n if (topologies == null) {\n topologies = new Map();\n this.topologies.set(protocol, topologies);\n }\n topologies.set(id, topology);\n return id;\n }\n /**\n * Unregister topology\n */\n unregister(id) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id);\n if (topologies.size === 0) {\n this.topologies.delete(protocol);\n }\n }\n }\n }\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect(evt) {\n const remotePeer = evt.detail;\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n topology.onDisconnect?.(remotePeer);\n }\n }\n })\n .catch(err => {\n if (err.code === _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NOT_FOUND) {\n // peer has not completed identify so they are not in the peer store\n return;\n }\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err);\n });\n }\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate(evt) {\n const { peer, previous } = evt.detail;\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol));\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n topology.onDisconnect?.(peer.id);\n }\n }\n }\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify(evt) {\n const protocols = evt.detail.protocols;\n const connection = evt.detail.connection;\n const peerId = evt.detail.peerId;\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (connection.transient && topology.notifyOnTransient !== true) {\n continue;\n }\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n}\n//# sourceMappingURL=registrar.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DEFAULT_MAX_INBOUND_STREAMS: () => (/* binding */ DEFAULT_MAX_INBOUND_STREAMS),\n/* harmony export */ DEFAULT_MAX_OUTBOUND_STREAMS: () => (/* binding */ DEFAULT_MAX_OUTBOUND_STREAMS),\n/* harmony export */ DefaultRegistrar: () => (/* binding */ DefaultRegistrar)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var merge_options__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! merge-options */ \"./node_modules/merge-options/index.mjs\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\nconst DEFAULT_MAX_INBOUND_STREAMS = 32;\nconst DEFAULT_MAX_OUTBOUND_STREAMS = 64;\n/**\n * Responsible for notifying registered protocols of events in the network.\n */\nclass DefaultRegistrar {\n log;\n topologies;\n handlers;\n components;\n constructor(components) {\n this.log = components.logger.forComponent('libp2p:registrar');\n this.topologies = new Map();\n this.handlers = new Map();\n this.components = components;\n this._onDisconnect = this._onDisconnect.bind(this);\n this._onPeerUpdate = this._onPeerUpdate.bind(this);\n this._onPeerIdentify = this._onPeerIdentify.bind(this);\n this.components.events.addEventListener('peer:disconnect', this._onDisconnect);\n this.components.events.addEventListener('peer:update', this._onPeerUpdate);\n this.components.events.addEventListener('peer:identify', this._onPeerIdentify);\n }\n [Symbol.toStringTag] = '@libp2p/registrar';\n getProtocols() {\n return Array.from(new Set([\n ...this.handlers.keys()\n ])).sort();\n }\n getHandler(protocol) {\n const handler = this.handlers.get(protocol);\n if (handler == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(`No handler registered for protocol ${protocol}`, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NO_HANDLER_FOR_PROTOCOL);\n }\n return handler;\n }\n getTopologies(protocol) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n return [];\n }\n return [\n ...topologies.values()\n ];\n }\n /**\n * Registers the `handler` for each protocol\n */\n async handle(protocol, handler, opts) {\n if (this.handlers.has(protocol)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError(`Handler already registered for protocol ${protocol}`, _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED);\n }\n const options = merge_options__WEBPACK_IMPORTED_MODULE_0__[\"default\"].bind({ ignoreUndefined: true })({\n maxInboundStreams: DEFAULT_MAX_INBOUND_STREAMS,\n maxOutboundStreams: DEFAULT_MAX_OUTBOUND_STREAMS\n }, opts);\n this.handlers.set(protocol, {\n handler,\n options\n });\n // Add new protocol to self protocols in the peer store\n await this.components.peerStore.merge(this.components.peerId, {\n protocols: [protocol]\n });\n }\n /**\n * Removes the handler for each protocol. The protocol\n * will no longer be supported on streams.\n */\n async unhandle(protocols) {\n const protocolList = Array.isArray(protocols) ? protocols : [protocols];\n protocolList.forEach(protocol => {\n this.handlers.delete(protocol);\n });\n // Update self protocols in the peer store\n await this.components.peerStore.patch(this.components.peerId, {\n protocols: this.getProtocols()\n });\n }\n /**\n * Register handlers for a set of multicodecs given\n */\n async register(protocol, topology) {\n if (topology == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.CodeError('invalid topology', _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_INVALID_PARAMETERS);\n }\n // Create topology\n const id = `${(Math.random() * 1e9).toString(36)}${Date.now()}`;\n let topologies = this.topologies.get(protocol);\n if (topologies == null) {\n topologies = new Map();\n this.topologies.set(protocol, topologies);\n }\n topologies.set(id, topology);\n return id;\n }\n /**\n * Unregister topology\n */\n unregister(id) {\n for (const [protocol, topologies] of this.topologies.entries()) {\n if (topologies.has(id)) {\n topologies.delete(id);\n if (topologies.size === 0) {\n this.topologies.delete(protocol);\n }\n }\n }\n }\n /**\n * Remove a disconnected peer from the record\n */\n _onDisconnect(evt) {\n const remotePeer = evt.detail;\n void this.components.peerStore.get(remotePeer)\n .then(peer => {\n for (const protocol of peer.protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(remotePeer) === false) {\n continue;\n }\n topology.filter?.remove(remotePeer);\n topology.onDisconnect?.(remotePeer);\n }\n }\n })\n .catch(err => {\n if (err.code === _errors_js__WEBPACK_IMPORTED_MODULE_2__.codes.ERR_NOT_FOUND) {\n // peer has not completed identify so they are not in the peer store\n return;\n }\n this.log.error('could not inform topologies of disconnecting peer %p', remotePeer, err);\n });\n }\n /**\n * When a peer is updated, if they have removed supported protocols notify any\n * topologies interested in the removed protocols.\n */\n _onPeerUpdate(evt) {\n const { peer, previous } = evt.detail;\n const removed = (previous?.protocols ?? []).filter(protocol => !peer.protocols.includes(protocol));\n for (const protocol of removed) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (topology.filter?.has(peer.id) === false) {\n continue;\n }\n topology.filter?.remove(peer.id);\n topology.onDisconnect?.(peer.id);\n }\n }\n }\n /**\n * After identify has completed and we have received the list of supported\n * protocols, notify any topologies interested in those protocols.\n */\n _onPeerIdentify(evt) {\n const protocols = evt.detail.protocols;\n const connection = evt.detail.connection;\n const peerId = evt.detail.peerId;\n for (const protocol of protocols) {\n const topologies = this.topologies.get(protocol);\n if (topologies == null) {\n // no topologies are interested in this protocol\n continue;\n }\n for (const topology of topologies.values()) {\n if (connection.transient && topology.notifyOnTransient !== true) {\n continue;\n }\n if (topology.filter?.has(peerId) === true) {\n continue;\n }\n topology.filter?.add(peerId);\n topology.onConnect?.(peerId, connection);\n }\n }\n }\n}\n//# sourceMappingURL=registrar.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js?"); /***/ }), @@ -12261,7 +16946,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultTransportManager: () => (/* binding */ DefaultTransportManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_utils_tracked_map__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @libp2p/utils/tracked-map */ \"./node_modules/@waku/sdk/node_modules/@libp2p/utils/dist/src/tracked-map.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\nclass DefaultTransportManager {\n log;\n components;\n transports;\n listeners;\n faultTolerance;\n started;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:transports');\n this.components = components;\n this.started = false;\n this.transports = new Map();\n this.listeners = (0,_libp2p_utils_tracked_map__WEBPACK_IMPORTED_MODULE_0__.trackedMap)({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n });\n this.faultTolerance = init.faultTolerance ?? _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.FaultTolerance.FATAL_ALL;\n }\n /**\n * Adds a `Transport` to the manager\n */\n add(transport) {\n const tag = transport[Symbol.toStringTag];\n if (tag == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('Transport must have a valid tag', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_INVALID_KEY);\n }\n if (this.transports.has(tag)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`There is already a transport with the tag ${tag}`, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_DUPLICATE_TRANSPORT);\n }\n this.log('adding transport %s', tag);\n this.transports.set(tag, transport);\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, []);\n }\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs();\n await this.listen(addrs);\n }\n /**\n * Stops all listeners\n */\n async stop() {\n const tasks = [];\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n }\n await Promise.all(tasks);\n this.log('all listeners closed');\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, []);\n }\n this.started = false;\n }\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial(ma, options) {\n const transport = this.transportForMultiaddr(ma);\n if (transport == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`No transport available for address ${String(ma)}`, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_TRANSPORT_UNAVAILABLE);\n }\n try {\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n });\n }\n catch (err) {\n if (err.code == null) {\n err.code = _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_TRANSPORT_DIAL_FAILED;\n }\n throw err;\n }\n }\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs() {\n let addrs = [];\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()];\n }\n }\n return addrs;\n }\n /**\n * Returns all the transports instances\n */\n getTransports() {\n return Array.of(...this.transports.values());\n }\n /**\n * Returns all the listener instances\n */\n getListeners() {\n return Array.of(...this.listeners.values()).flat();\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n transportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.filter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen(addrs) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError('Not started', _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NODE_NOT_STARTED);\n }\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only');\n return;\n }\n const couldNotListen = [];\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.filter(addrs);\n const tasks = [];\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr);\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n });\n let listeners = this.listeners.get(key) ?? [];\n if (listeners == null) {\n listeners = [];\n this.listeners.set(key, listeners);\n }\n listeners.push(listener);\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n });\n });\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener);\n // remove the listener\n listeners.splice(index, 1);\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n });\n });\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr));\n }\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key);\n continue;\n }\n const results = await Promise.allSettled(tasks);\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled');\n if ((isListening == null) && this.faultTolerance !== _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.FaultTolerance.NO_FATAL) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(`Transport (${key}) could not listen on any available address`, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_VALID_ADDRESSES);\n }\n }\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`;\n if (this.faultTolerance === _libp2p_interface__WEBPACK_IMPORTED_MODULE_1__.FaultTolerance.FATAL_ALL) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.CodeError(message, _errors_js__WEBPACK_IMPORTED_MODULE_3__.codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log(`libp2p in dial mode only: ${message}`);\n }\n }\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove(key) {\n const listeners = this.listeners.get(key) ?? [];\n this.log.trace('removing transport %s', key);\n // Close any running listeners\n const tasks = [];\n this.log.trace('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n await Promise.all(tasks);\n this.transports.delete(key);\n this.listeners.delete(key);\n }\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll() {\n const tasks = [];\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key));\n }\n await Promise.all(tasks);\n }\n}\n//# sourceMappingURL=transport-manager.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/transport-manager.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultTransportManager: () => (/* binding */ DefaultTransportManager)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/transport/index.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_utils_tracked_map__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @libp2p/utils/tracked-map */ \"./node_modules/@libp2p/utils/dist/src/tracked-map.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n\n\n\n\nclass DefaultTransportManager {\n log;\n components;\n transports;\n listeners;\n faultTolerance;\n started;\n constructor(components, init = {}) {\n this.log = components.logger.forComponent('libp2p:transports');\n this.components = components;\n this.started = false;\n this.transports = new Map();\n this.listeners = (0,_libp2p_utils_tracked_map__WEBPACK_IMPORTED_MODULE_1__.trackedMap)({\n name: 'libp2p_transport_manager_listeners',\n metrics: this.components.metrics\n });\n this.faultTolerance = init.faultTolerance ?? _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.FaultTolerance.FATAL_ALL;\n }\n [Symbol.toStringTag] = '@libp2p/transport-manager';\n /**\n * Adds a `Transport` to the manager\n */\n add(transport) {\n const tag = transport[Symbol.toStringTag];\n if (tag == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Transport must have a valid tag', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_INVALID_KEY);\n }\n if (this.transports.has(tag)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`There is already a transport with the tag ${tag}`, _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_DUPLICATE_TRANSPORT);\n }\n this.log('adding transport %s', tag);\n this.transports.set(tag, transport);\n if (!this.listeners.has(tag)) {\n this.listeners.set(tag, []);\n }\n }\n isStarted() {\n return this.started;\n }\n start() {\n this.started = true;\n }\n async afterStart() {\n // Listen on the provided transports for the provided addresses\n const addrs = this.components.addressManager.getListenAddrs();\n await this.listen(addrs);\n }\n /**\n * Stops all listeners\n */\n async stop() {\n const tasks = [];\n for (const [key, listeners] of this.listeners) {\n this.log('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n }\n await Promise.all(tasks);\n this.log('all listeners closed');\n for (const key of this.listeners.keys()) {\n this.listeners.set(key, []);\n }\n this.started = false;\n }\n /**\n * Dials the given Multiaddr over it's supported transport\n */\n async dial(ma, options) {\n const transport = this.dialTransportForMultiaddr(ma);\n if (transport == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`No transport available for address ${String(ma)}`, _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_TRANSPORT_UNAVAILABLE);\n }\n options?.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('transport-manager:selected-transport', transport[Symbol.toStringTag]));\n try {\n // @ts-expect-error the transport has a typed onProgress option but we\n // can't predict what transport implementation we selected so all we can\n // do is pass the onProgress handler in and hope for the best\n return await transport.dial(ma, {\n ...options,\n upgrader: this.components.upgrader\n });\n }\n catch (err) {\n if (err.code == null) {\n err.code = _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_TRANSPORT_DIAL_FAILED;\n }\n throw err;\n }\n }\n /**\n * Returns all Multiaddr's the listeners are using\n */\n getAddrs() {\n let addrs = [];\n for (const listeners of this.listeners.values()) {\n for (const listener of listeners) {\n addrs = [...addrs, ...listener.getAddrs()];\n }\n }\n return addrs;\n }\n /**\n * Returns all the transports instances\n */\n getTransports() {\n return Array.of(...this.transports.values());\n }\n /**\n * Returns all the listener instances\n */\n getListeners() {\n return Array.of(...this.listeners.values()).flat();\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n dialTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.dialFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Finds a transport that matches the given Multiaddr\n */\n listenTransportForMultiaddr(ma) {\n for (const transport of this.transports.values()) {\n const addrs = transport.listenFilter([ma]);\n if (addrs.length > 0) {\n return transport;\n }\n }\n }\n /**\n * Starts listeners for each listen Multiaddr\n */\n async listen(addrs) {\n if (!this.isStarted()) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Not started', _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_NODE_NOT_STARTED);\n }\n if (addrs == null || addrs.length === 0) {\n this.log('no addresses were provided for listening, this node is dial only');\n return;\n }\n const couldNotListen = [];\n for (const [key, transport] of this.transports.entries()) {\n const supportedAddrs = transport.listenFilter(addrs);\n const tasks = [];\n // For each supported multiaddr, create a listener\n for (const addr of supportedAddrs) {\n this.log('creating listener for %s on %a', key, addr);\n const listener = transport.createListener({\n upgrader: this.components.upgrader\n });\n let listeners = this.listeners.get(key) ?? [];\n if (listeners == null) {\n listeners = [];\n this.listeners.set(key, listeners);\n }\n listeners.push(listener);\n // Track listen/close events\n listener.addEventListener('listening', () => {\n this.components.events.safeDispatchEvent('transport:listening', {\n detail: listener\n });\n });\n listener.addEventListener('close', () => {\n const index = listeners.findIndex(l => l === listener);\n // remove the listener\n listeners.splice(index, 1);\n this.components.events.safeDispatchEvent('transport:close', {\n detail: listener\n });\n });\n // We need to attempt to listen on everything\n tasks.push(listener.listen(addr));\n }\n // Keep track of transports we had no addresses for\n if (tasks.length === 0) {\n couldNotListen.push(key);\n continue;\n }\n const results = await Promise.allSettled(tasks);\n // If we are listening on at least 1 address, succeed.\n // TODO: we should look at adding a retry (`p-retry`) here to better support\n // listening on remote addresses as they may be offline. We could then potentially\n // just wait for any (`p-any`) listener to succeed on each transport before returning\n const isListening = results.find(r => r.status === 'fulfilled');\n if ((isListening == null) && this.faultTolerance !== _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.FaultTolerance.NO_FATAL) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Transport (${key}) could not listen on any available address`, _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_NO_VALID_ADDRESSES);\n }\n }\n // If no transports were able to listen, throw an error. This likely\n // means we were given addresses we do not have transports for\n if (couldNotListen.length === this.transports.size) {\n const message = `no valid addresses were provided for transports [${couldNotListen.join(', ')}]`;\n if (this.faultTolerance === _libp2p_interface__WEBPACK_IMPORTED_MODULE_2__.FaultTolerance.FATAL_ALL) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(message, _errors_js__WEBPACK_IMPORTED_MODULE_4__.codes.ERR_NO_VALID_ADDRESSES);\n }\n this.log(`libp2p in dial mode only: ${message}`);\n }\n }\n /**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n */\n async remove(key) {\n const listeners = this.listeners.get(key) ?? [];\n this.log.trace('removing transport %s', key);\n // Close any running listeners\n const tasks = [];\n this.log.trace('closing listeners for %s', key);\n while (listeners.length > 0) {\n const listener = listeners.pop();\n if (listener == null) {\n continue;\n }\n tasks.push(listener.close());\n }\n await Promise.all(tasks);\n this.transports.delete(key);\n this.listeners.delete(key);\n }\n /**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */\n async removeAll() {\n const tasks = [];\n for (const key of this.transports.keys()) {\n tasks.push(this.remove(key));\n }\n await Promise.all(tasks);\n }\n}\n//# sourceMappingURL=transport-manager.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/transport-manager.js?"); /***/ }), @@ -12272,7 +16957,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultUpgrader: () => (/* binding */ DefaultUpgrader)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/multistream-select */ \"./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/handle.js\");\n/* harmony import */ var _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/multistream-select */ \"./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/select.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection/index.js\");\n/* harmony import */ var _connection_manager_constants_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./connection-manager/constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _registrar_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./registrar.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js\");\n\n\n\n\n\n\n\nconst DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000;\nfunction findIncomingStreamLimit(protocol, registrar) {\n try {\n const { options } = registrar.getHandler(protocol);\n return options.maxInboundStreams;\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return _registrar_js__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_MAX_INBOUND_STREAMS;\n}\nfunction findOutgoingStreamLimit(protocol, registrar, options = {}) {\n try {\n const { options } = registrar.getHandler(protocol);\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams;\n }\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return options.maxOutboundStreams ?? _registrar_js__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_MAX_OUTBOUND_STREAMS;\n}\nfunction countStreams(protocol, direction, connection) {\n let streamCount = 0;\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++;\n }\n });\n return streamCount;\n}\nclass DefaultUpgrader {\n components;\n connectionEncryption;\n muxers;\n inboundUpgradeTimeout;\n events;\n constructor(components, init) {\n this.components = components;\n this.connectionEncryption = new Map();\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter);\n });\n this.muxers = new Map();\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer);\n });\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? _connection_manager_constants_js__WEBPACK_IMPORTED_MODULE_2__.INBOUND_UPGRADE_TIMEOUT;\n this.events = components.events;\n }\n async shouldBlockConnection(remotePeer, maConn, connectionType) {\n const connectionGater = this.components.connectionGater[connectionType];\n if (connectionGater !== undefined) {\n if (await connectionGater(remotePeer, maConn)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`The multiaddr connection is blocked by gater.${connectionType}`, _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_CONNECTION_INTERCEPTED);\n }\n }\n }\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound(maConn, opts) {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn);\n if (!accept) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('connection denied', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_CONNECTION_DENIED);\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let muxerFactory;\n let cryptoProtocol;\n const signal = AbortSignal.timeout(this.inboundUpgradeTimeout);\n const onAbort = () => {\n maConn.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('inbound upgrade timeout', _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.ERR_TIMEOUT));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, signal);\n try {\n if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('The multiaddr connection is blocked by gater.acceptConnection', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_CONNECTION_INTERCEPTED);\n }\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the inbound connection upgrade');\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n maConn.log('protecting the inbound connection');\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection');\n }\n else {\n const idStr = maConn.remoteAddr.getPeerId();\n if (idStr == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('inbound connection that skipped encryption must have a peer id', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_INVALID_MULTIADDR);\n }\n const remotePeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__.peerIdFromString)(idStr);\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade inbound connection', err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection');\n maConn.log('successfully upgraded inbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n finally {\n signal.removeEventListener('abort', onAbort);\n this.components.connectionManager.afterUpgradeInbound();\n }\n }\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound(maConn, opts) {\n const idStr = maConn.remoteAddr.getPeerId();\n let remotePeerId;\n if (idStr != null) {\n remotePeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_5__.peerIdFromString)(idStr);\n await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection');\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let cryptoProtocol;\n let muxerFactory;\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the outbound connection upgrade');\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection');\n }\n else {\n if (remotePeerId == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Encryption was skipped but no peer id was passed', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_INVALID_PEER);\n }\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade outbound connection', err);\n await maConn.close(err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection');\n maConn.log('successfully upgraded outbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection(opts) {\n const { cryptoProtocol, direction, maConn, upgradedConn, remotePeer, muxerFactory, transient } = opts;\n let muxer;\n let newStream;\n let connection; // eslint-disable-line prefer-const\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return;\n }\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols();\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_6__.handle(muxedStream, protocols, {\n log: muxedStream.log,\n yieldBytes: false\n });\n if (connection == null) {\n return;\n }\n connection.log('incoming stream opened on %s', protocol);\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar);\n const streamCount = countStreams(protocol, 'inbound', connection);\n if (streamCount === incomingLimit) {\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`, _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n this._onStream({ connection, stream: muxedStream, protocol });\n })\n .catch(async (err) => {\n connection.log.error('error handling incoming stream id %s', muxedStream.id, err.message, err.code, err.stack);\n if (muxedStream.timeline.close == null) {\n await muxedStream.close();\n }\n });\n }\n });\n newStream = async (protocols, options = {}) => {\n if (muxer == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Stream is not multiplexed', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_MUXER_UNAVAILABLE);\n }\n connection.log('starting new stream for protocols %s', protocols);\n const muxedStream = await muxer.newStream();\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols);\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols);\n const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.setMaxListeners)(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n muxedStream.log.trace('selecting protocol from protocols %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n });\n muxedStream.log('selected protocol %s', protocol);\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);\n const streamCount = countStreams(protocol, 'outbound', connection);\n if (streamCount >= outgoingLimit) {\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(`Too many outbound protocol streams for protocol \"${protocol}\" - limit ${outgoingLimit}`, _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n return muxedStream;\n }\n catch (err) {\n connection.log.error('could not create new stream for protocols %s', protocols, err);\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err);\n }\n if (err.code != null) {\n throw err;\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_UNSUPPORTED_PROTOCOL);\n }\n };\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer', err);\n });\n }\n const _timeline = maConn.timeline;\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close();\n }\n }\n catch (err) {\n connection.log.error('error closing connection after timeline close', err);\n }\n finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n });\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event', err);\n });\n }\n return Reflect.set(...args);\n }\n });\n maConn.timeline.upgraded = Date.now();\n const errConnectionNotMultiplexed = () => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('connection is not multiplexed', _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_CONNECTION_NOT_MULTIPLEXED);\n };\n // Create the connection\n connection = (0,_connection_index_js__WEBPACK_IMPORTED_MODULE_8__.createConnection)({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n transient,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => { if (muxer != null) {\n return muxer.streams;\n }\n else {\n return [];\n } },\n close: async (options) => {\n // Ensure remaining streams are closed gracefully\n if (muxer != null) {\n connection.log.trace('close muxer');\n await muxer.close(options);\n }\n connection.log.trace('close maconn');\n // close the underlying transport\n await maConn.close(options);\n connection.log.trace('closed maconn');\n },\n abort: (err) => {\n maConn.abort(err);\n // Ensure remaining streams are aborted\n if (muxer != null) {\n muxer.abort(err);\n }\n }\n });\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n });\n return connection;\n }\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream(opts) {\n const { connection, stream, protocol } = opts;\n const { handler, options } = this.components.registrar.getHandler(protocol);\n if (connection.transient && options.runOnTransientConnection !== true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n handler({ connection, stream });\n }\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound(connection) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('handling inbound crypto protocol selection', protocols);\n try {\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_6__.handle(connection, protocols, {\n log: connection.log\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting inbound connection using', protocol);\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting inbound connection to %p failed', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(err.message, _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound(connection, remotePeerId) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('selecting outbound crypto protocol', protocols);\n try {\n connection.log.trace('selecting encrypter from %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting outbound connection to %p using %s', remotePeerId, encrypter);\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting outbound connection to %p failed', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(err.message, _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('outbound selecting muxer %s', protocols);\n try {\n connection.log.trace('selecting stream muxer from %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n connection.log('selected %s as muxer protocol', protocol);\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing outbound connection', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('inbound handling muxers %s', protocols);\n try {\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_6__.handle(connection, protocols, {\n log: connection.log\n });\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing inbound connection', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_3__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_0__.codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n}\n//# sourceMappingURL=upgrader.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/upgrader.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ DefaultUpgrader: () => (/* binding */ DefaultUpgrader)\n/* harmony export */ });\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/errors.js\");\n/* harmony import */ var _libp2p_interface__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @libp2p/interface */ \"./node_modules/@waku/sdk/node_modules/@libp2p/interface/dist/src/events.js\");\n/* harmony import */ var _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @libp2p/multistream-select */ \"./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/handle.js\");\n/* harmony import */ var _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @libp2p/multistream-select */ \"./node_modules/@waku/sdk/node_modules/@libp2p/multistream-select/dist/src/select.js\");\n/* harmony import */ var _libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @libp2p/peer-id */ \"./node_modules/@waku/sdk/node_modules/@libp2p/peer-id/dist/src/index.js\");\n/* harmony import */ var progress_events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! progress-events */ \"./node_modules/progress-events/dist/src/index.js\");\n/* harmony import */ var _connection_index_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./connection/index.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection/index.js\");\n/* harmony import */ var _connection_manager_constants_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./connection-manager/constants.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/connection-manager/constants.defaults.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/errors.js\");\n/* harmony import */ var _registrar_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./registrar.js */ \"./node_modules/@waku/sdk/node_modules/libp2p/dist/src/registrar.js\");\n\n\n\n\n\n\n\n\nconst DEFAULT_PROTOCOL_SELECT_TIMEOUT = 30000;\nfunction findIncomingStreamLimit(protocol, registrar) {\n try {\n const { options } = registrar.getHandler(protocol);\n return options.maxInboundStreams;\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return _registrar_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_MAX_INBOUND_STREAMS;\n}\nfunction findOutgoingStreamLimit(protocol, registrar, options = {}) {\n try {\n const { options } = registrar.getHandler(protocol);\n if (options.maxOutboundStreams != null) {\n return options.maxOutboundStreams;\n }\n }\n catch (err) {\n if (err.code !== _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_NO_HANDLER_FOR_PROTOCOL) {\n throw err;\n }\n }\n return options.maxOutboundStreams ?? _registrar_js__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_MAX_OUTBOUND_STREAMS;\n}\nfunction countStreams(protocol, direction, connection) {\n let streamCount = 0;\n connection.streams.forEach(stream => {\n if (stream.direction === direction && stream.protocol === protocol) {\n streamCount++;\n }\n });\n return streamCount;\n}\nclass DefaultUpgrader {\n components;\n connectionEncryption;\n muxers;\n inboundUpgradeTimeout;\n events;\n constructor(components, init) {\n this.components = components;\n this.connectionEncryption = new Map();\n init.connectionEncryption.forEach(encrypter => {\n this.connectionEncryption.set(encrypter.protocol, encrypter);\n });\n this.muxers = new Map();\n init.muxers.forEach(muxer => {\n this.muxers.set(muxer.protocol, muxer);\n });\n this.inboundUpgradeTimeout = init.inboundUpgradeTimeout ?? _connection_manager_constants_js__WEBPACK_IMPORTED_MODULE_3__.INBOUND_UPGRADE_TIMEOUT;\n this.events = components.events;\n }\n [Symbol.toStringTag] = '@libp2p/upgrader';\n async shouldBlockConnection(remotePeer, maConn, connectionType) {\n const connectionGater = this.components.connectionGater[connectionType];\n if (connectionGater !== undefined) {\n if (await connectionGater(remotePeer, maConn)) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`The multiaddr connection is blocked by gater.${connectionType}`, _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_CONNECTION_INTERCEPTED);\n }\n }\n }\n /**\n * Upgrades an inbound connection\n */\n async upgradeInbound(maConn, opts) {\n const accept = await this.components.connectionManager.acceptIncomingConnection(maConn);\n if (!accept) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('connection denied', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_CONNECTION_DENIED);\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let muxerFactory;\n let cryptoProtocol;\n const signal = AbortSignal.timeout(this.inboundUpgradeTimeout);\n const onAbort = () => {\n maConn.abort(new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('inbound upgrade timeout', _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.ERR_TIMEOUT));\n };\n signal.addEventListener('abort', onAbort, { once: true });\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.setMaxListeners)(Infinity, signal);\n try {\n if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('The multiaddr connection is blocked by gater.acceptConnection', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_CONNECTION_INTERCEPTED);\n }\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the inbound connection upgrade');\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n maConn.log('protecting the inbound connection');\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n opts?.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('upgrader:encrypt-inbound-connection'));\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptInbound(protectedConn));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundEncryptedConnection');\n }\n else {\n const idStr = maConn.remoteAddr.getPeerId();\n if (idStr == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('inbound connection that skipped encryption must have a peer id', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_INVALID_MULTIADDR);\n }\n const remotePeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__.peerIdFromString)(idStr);\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n opts?.onProgress?.(new progress_events__WEBPACK_IMPORTED_MODULE_0__.CustomProgressEvent('upgrader:multiplex-inbound-connection'));\n // Multiplex the connection\n const multiplexed = await this._multiplexInbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade inbound connection', err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyInboundUpgradedConnection');\n maConn.log('successfully upgraded inbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'inbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n finally {\n signal.removeEventListener('abort', onAbort);\n this.components.connectionManager.afterUpgradeInbound();\n }\n }\n /**\n * Upgrades an outbound connection\n */\n async upgradeOutbound(maConn, opts) {\n const idStr = maConn.remoteAddr.getPeerId();\n let remotePeerId;\n if (idStr != null) {\n remotePeerId = (0,_libp2p_peer_id__WEBPACK_IMPORTED_MODULE_6__.peerIdFromString)(idStr);\n await this.shouldBlockConnection(remotePeerId, maConn, 'denyOutboundConnection');\n }\n let encryptedConn;\n let remotePeer;\n let upgradedConn;\n let cryptoProtocol;\n let muxerFactory;\n this.components.metrics?.trackMultiaddrConnection(maConn);\n maConn.log('starting the outbound connection upgrade');\n // If the transport natively supports encryption, skip connection\n // protector and encryption\n // Protect\n let protectedConn = maConn;\n if (opts?.skipProtection !== true) {\n const protector = this.components.connectionProtector;\n if (protector != null) {\n protectedConn = await protector.protect(maConn);\n }\n }\n try {\n // Encrypt the connection\n encryptedConn = protectedConn;\n if (opts?.skipEncryption !== true) {\n ({\n conn: encryptedConn,\n remotePeer,\n protocol: cryptoProtocol\n } = await this._encryptOutbound(protectedConn, remotePeerId));\n const maConn = {\n ...protectedConn,\n ...encryptedConn\n };\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundEncryptedConnection');\n }\n else {\n if (remotePeerId == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Encryption was skipped but no peer id was passed', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_INVALID_PEER);\n }\n cryptoProtocol = 'native';\n remotePeer = remotePeerId;\n }\n upgradedConn = encryptedConn;\n if (opts?.muxerFactory != null) {\n muxerFactory = opts.muxerFactory;\n }\n else if (this.muxers.size > 0) {\n // Multiplex the connection\n const multiplexed = await this._multiplexOutbound({\n ...protectedConn,\n ...encryptedConn\n }, this.muxers);\n muxerFactory = multiplexed.muxerFactory;\n upgradedConn = multiplexed.stream;\n }\n }\n catch (err) {\n maConn.log.error('failed to upgrade outbound connection', err);\n await maConn.close(err);\n throw err;\n }\n await this.shouldBlockConnection(remotePeer, maConn, 'denyOutboundUpgradedConnection');\n maConn.log('successfully upgraded outbound connection');\n return this._createConnection({\n cryptoProtocol,\n direction: 'outbound',\n maConn,\n upgradedConn,\n muxerFactory,\n remotePeer,\n transient: opts?.transient\n });\n }\n /**\n * A convenience method for generating a new `Connection`\n */\n _createConnection(opts) {\n const { cryptoProtocol, direction, maConn, upgradedConn, remotePeer, muxerFactory, transient } = opts;\n let muxer;\n let newStream;\n let connection; // eslint-disable-line prefer-const\n if (muxerFactory != null) {\n // Create the muxer\n muxer = muxerFactory.createStreamMuxer({\n direction,\n // Run anytime a remote stream is created\n onIncomingStream: muxedStream => {\n if (connection == null) {\n return;\n }\n void Promise.resolve()\n .then(async () => {\n const protocols = this.components.registrar.getProtocols();\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.handle(muxedStream, protocols, {\n log: muxedStream.log,\n yieldBytes: false\n });\n if (connection == null) {\n return;\n }\n connection.log('incoming stream opened on %s', protocol);\n const incomingLimit = findIncomingStreamLimit(protocol, this.components.registrar);\n const streamCount = countStreams(protocol, 'inbound', connection);\n if (streamCount === incomingLimit) {\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`Too many inbound protocol streams for protocol \"${protocol}\" - limit ${incomingLimit}`, _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n this._onStream({ connection, stream: muxedStream, protocol });\n })\n .catch(async (err) => {\n connection.log.error('error handling incoming stream id %s', muxedStream.id, err.message, err.code, err.stack);\n if (muxedStream.timeline.close == null) {\n await muxedStream.close();\n }\n });\n }\n });\n newStream = async (protocols, options = {}) => {\n if (muxer == null) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Stream is not multiplexed', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_MUXER_UNAVAILABLE);\n }\n connection.log('starting new stream for protocols %s', protocols);\n const muxedStream = await muxer.newStream();\n connection.log.trace('started new stream %s for protocols %s', muxedStream.id, protocols);\n try {\n if (options.signal == null) {\n muxedStream.log('no abort signal was passed while trying to negotiate protocols %s falling back to default timeout', protocols);\n const signal = AbortSignal.timeout(DEFAULT_PROTOCOL_SELECT_TIMEOUT);\n (0,_libp2p_interface__WEBPACK_IMPORTED_MODULE_5__.setMaxListeners)(Infinity, signal);\n options = {\n ...options,\n signal\n };\n }\n muxedStream.log.trace('selecting protocol from protocols %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_8__.select(muxedStream, protocols, {\n ...options,\n log: muxedStream.log,\n yieldBytes: true\n });\n muxedStream.log('selected protocol %s', protocol);\n const outgoingLimit = findOutgoingStreamLimit(protocol, this.components.registrar, options);\n const streamCount = countStreams(protocol, 'outbound', connection);\n if (streamCount >= outgoingLimit) {\n const err = new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(`Too many outbound protocol streams for protocol \"${protocol}\" - ${streamCount}/${outgoingLimit}`, _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS);\n muxedStream.abort(err);\n throw err;\n }\n // If a protocol stream has been successfully negotiated and is to be passed to the application,\n // the peerstore should ensure that the peer is registered with that protocol\n await this.components.peerStore.merge(remotePeer, {\n protocols: [protocol]\n });\n // after the handshake the returned stream can have early data so override\n // the souce/sink\n muxedStream.source = stream.source;\n muxedStream.sink = stream.sink;\n muxedStream.protocol = protocol;\n // allow closing the write end of a not-yet-negotiated stream\n if (stream.closeWrite != null) {\n muxedStream.closeWrite = stream.closeWrite;\n }\n // allow closing the read end of a not-yet-negotiated stream\n if (stream.closeRead != null) {\n muxedStream.closeRead = stream.closeRead;\n }\n // make sure we don't try to negotiate a stream we are closing\n if (stream.close != null) {\n muxedStream.close = stream.close;\n }\n this.components.metrics?.trackProtocolStream(muxedStream, connection);\n return muxedStream;\n }\n catch (err) {\n connection.log.error('could not create new stream for protocols %s', protocols, err);\n if (muxedStream.timeline.close == null) {\n muxedStream.abort(err);\n }\n if (err.code != null) {\n throw err;\n }\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_UNSUPPORTED_PROTOCOL);\n }\n };\n // Pipe all data through the muxer\n void Promise.all([\n muxer.sink(upgradedConn.source),\n upgradedConn.sink(muxer.source)\n ]).catch(err => {\n connection.log.error('error piping data through muxer', err);\n });\n }\n const _timeline = maConn.timeline;\n maConn.timeline = new Proxy(_timeline, {\n set: (...args) => {\n if (connection != null && args[1] === 'close' && args[2] != null && _timeline.close == null) {\n // Wait for close to finish before notifying of the closure\n (async () => {\n try {\n if (connection.status === 'open') {\n await connection.close();\n }\n }\n catch (err) {\n connection.log.error('error closing connection after timeline close', err);\n }\n finally {\n this.events.safeDispatchEvent('connection:close', {\n detail: connection\n });\n }\n })().catch(err => {\n connection.log.error('error thrown while dispatching connection:close event', err);\n });\n }\n return Reflect.set(...args);\n }\n });\n maConn.timeline.upgraded = Date.now();\n const errConnectionNotMultiplexed = () => {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('connection is not multiplexed', _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_CONNECTION_NOT_MULTIPLEXED);\n };\n // Create the connection\n connection = (0,_connection_index_js__WEBPACK_IMPORTED_MODULE_9__.createConnection)({\n remoteAddr: maConn.remoteAddr,\n remotePeer,\n status: 'open',\n direction,\n timeline: maConn.timeline,\n multiplexer: muxer?.protocol,\n encryption: cryptoProtocol,\n transient,\n logger: this.components.logger,\n newStream: newStream ?? errConnectionNotMultiplexed,\n getStreams: () => { if (muxer != null) {\n return muxer.streams;\n }\n else {\n return [];\n } },\n close: async (options) => {\n // Ensure remaining streams are closed gracefully\n if (muxer != null) {\n connection.log.trace('close muxer');\n await muxer.close(options);\n }\n connection.log.trace('close maconn');\n // close the underlying transport\n await maConn.close(options);\n connection.log.trace('closed maconn');\n },\n abort: (err) => {\n maConn.abort(err);\n // Ensure remaining streams are aborted\n if (muxer != null) {\n muxer.abort(err);\n }\n }\n });\n this.events.safeDispatchEvent('connection:open', {\n detail: connection\n });\n return connection;\n }\n /**\n * Routes incoming streams to the correct handler\n */\n _onStream(opts) {\n const { connection, stream, protocol } = opts;\n const { handler, options } = this.components.registrar.getHandler(protocol);\n if (connection.transient && options.runOnTransientConnection !== true) {\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError('Cannot open protocol stream on transient connection', 'ERR_TRANSIENT_CONNECTION');\n }\n handler({ connection, stream });\n }\n /**\n * Attempts to encrypt the incoming `connection` with the provided `cryptos`\n */\n async _encryptInbound(connection) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('handling inbound crypto protocol selection', protocols);\n try {\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.handle(connection, protocols, {\n log: connection.log\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting inbound connection using', protocol);\n return {\n ...await encrypter.secureInbound(this.components.peerId, stream),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting inbound connection failed', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(err.message, _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Attempts to encrypt the given `connection` with the provided connection encrypters.\n * The first `ConnectionEncrypter` module to succeed will be used\n */\n async _encryptOutbound(connection, remotePeerId) {\n const protocols = Array.from(this.connectionEncryption.keys());\n connection.log('selecting outbound crypto protocol', protocols);\n try {\n connection.log.trace('selecting encrypter from %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_8__.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n const encrypter = this.connectionEncryption.get(protocol);\n if (encrypter == null) {\n throw new Error(`no crypto module found for ${protocol}`);\n }\n connection.log('encrypting outbound connection to %p using %s', remotePeerId, encrypter);\n return {\n ...await encrypter.secureOutbound(this.components.peerId, stream, remotePeerId),\n protocol\n };\n }\n catch (err) {\n connection.log.error('encrypting outbound connection to %p failed', remotePeerId, err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(err.message, _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_ENCRYPTION_FAILED);\n }\n }\n /**\n * Selects one of the given muxers via multistream-select. That\n * muxer will be used for all future streams on the connection.\n */\n async _multiplexOutbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('outbound selecting muxer %s', protocols);\n try {\n connection.log.trace('selecting stream muxer from %s', protocols);\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_8__.select(connection, protocols, {\n log: connection.log,\n yieldBytes: true\n });\n connection.log('selected %s as muxer protocol', protocol);\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing outbound connection', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n /**\n * Registers support for one of the given muxers via multistream-select. The\n * selected muxer will be used for all future streams on the connection.\n */\n async _multiplexInbound(connection, muxers) {\n const protocols = Array.from(muxers.keys());\n connection.log('inbound handling muxers %s', protocols);\n try {\n const { stream, protocol } = await _libp2p_multistream_select__WEBPACK_IMPORTED_MODULE_7__.handle(connection, protocols, {\n log: connection.log\n });\n const muxerFactory = muxers.get(protocol);\n return { stream, muxerFactory };\n }\n catch (err) {\n connection.log.error('error multiplexing inbound connection', err);\n throw new _libp2p_interface__WEBPACK_IMPORTED_MODULE_4__.CodeError(String(err), _errors_js__WEBPACK_IMPORTED_MODULE_1__.codes.ERR_MUXER_UNAVAILABLE);\n }\n }\n}\n//# sourceMappingURL=upgrader.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/upgrader.js?"); /***/ }), @@ -12283,7 +16968,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ name: () => (/* binding */ name),\n/* harmony export */ version: () => (/* binding */ version)\n/* harmony export */ });\nconst version = '1.3.3';\nconst name = 'libp2p';\n//# sourceMappingURL=version.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/version.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ name: () => (/* binding */ name),\n/* harmony export */ version: () => (/* binding */ version)\n/* harmony export */ });\nconst version = '1.9.4';\nconst name = 'libp2p';\n//# sourceMappingURL=version.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/libp2p/dist/src/version.js?"); /***/ }), @@ -12294,7 +16979,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -12338,7 +17023,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -12459,7 +17144,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -12503,7 +17188,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@waku/sdk/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/sdk/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -13064,7 +17749,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n\n//# sourceMappingURL=waku.j /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -13108,7 +17793,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -13229,7 +17914,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -13273,7 +17958,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/@waku/utils/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/@waku/utils/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -13570,18 +18255,18 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bool: () => (/* binding */ bool),\n/* harmony export */ bytes: () => (/* binding */ bytes),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ exists: () => (/* binding */ exists),\n/* harmony export */ hash: () => (/* binding */ hash),\n/* harmony export */ number: () => (/* binding */ number),\n/* harmony export */ output: () => (/* binding */ output)\n/* harmony export */ });\nfunction number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\n// copied from utils\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nconst assert = { number, bool, bytes, hash, exists, output };\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (assert);\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ bool: () => (/* binding */ bool),\n/* harmony export */ bytes: () => (/* binding */ bytes),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__),\n/* harmony export */ exists: () => (/* binding */ exists),\n/* harmony export */ hash: () => (/* binding */ hash),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ number: () => (/* binding */ number),\n/* harmony export */ output: () => (/* binding */ output)\n/* harmony export */ });\nfunction number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`positive integer expected, not ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`boolean expected, not ${b}`);\n}\n// copied from utils\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\nfunction bytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nconst assert = { number, bool, bytes, hash, exists, output };\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (assert);\n//# sourceMappingURL=_assert.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js?"); /***/ }), -/***/ "./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_sha2.js": -/*!************************************************************************************!*\ - !*** ./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_sha2.js ***! - \************************************************************************************/ +/***/ "./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_md.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_md.js ***! + \**********************************************************************************/ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ SHA2: () => (/* binding */ SHA2)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nclass SHA2 extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(this.buffer);\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n const { view, buffer, blockLen } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.output)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_sha2.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Chi: () => (/* binding */ Chi),\n/* harmony export */ HashMD: () => (/* binding */ HashMD),\n/* harmony export */ Maj: () => (/* binding */ Maj)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nclass HashMD extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(this.buffer);\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n const { view, buffer, blockLen } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.exists)(this);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_1__.output)(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.createView)(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_md.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_md.js?"); /***/ }), @@ -13614,7 +18299,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha224: () => (/* binding */ sha224),\n/* harmony export */ sha256: () => (/* binding */ sha256)\n/* harmony export */ });\n/* harmony import */ var _sha2_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_sha2.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_sha2.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _sha2_js__WEBPACK_IMPORTED_MODULE_0__.SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nconst sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());\nconst sha224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/sha256.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ sha224: () => (/* binding */ sha224),\n/* harmony export */ sha256: () => (/* binding */ sha256)\n/* harmony export */ });\n/* harmony import */ var _md_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_md.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_md.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends _md_js__WEBPACK_IMPORTED_MODULE_0__.HashMD {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = SHA256_IV[0] | 0;\n this.B = SHA256_IV[1] | 0;\n this.C = SHA256_IV[2] | 0;\n this.D = SHA256_IV[3] | 0;\n this.E = SHA256_IV[4] | 0;\n this.F = SHA256_IV[5] | 0;\n this.G = SHA256_IV[6] | 0;\n this.H = SHA256_IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 7) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W15, 18) ^ (W15 >>> 3);\n const s1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 17) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 6) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 11) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(E, 25);\n const T1 = (H + sigma1 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Chi)(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 2) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 13) ^ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.rotr)(A, 22);\n const T2 = (sigma0 + (0,_md_js__WEBPACK_IMPORTED_MODULE_0__.Maj)(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nconst sha256 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA256());\nconst sha224 = /* @__PURE__ */ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new SHA224());\n//# sourceMappingURL=sha256.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/sha256.js?"); /***/ }), @@ -13625,7 +18310,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Keccak: () => (/* binding */ Keccak),\n/* harmony export */ keccakP: () => (/* binding */ keccakP),\n/* harmony export */ keccak_224: () => (/* binding */ keccak_224),\n/* harmony export */ keccak_256: () => (/* binding */ keccak_256),\n/* harmony export */ keccak_384: () => (/* binding */ keccak_384),\n/* harmony export */ keccak_512: () => (/* binding */ keccak_512),\n/* harmony export */ sha3_224: () => (/* binding */ sha3_224),\n/* harmony export */ sha3_256: () => (/* binding */ sha3_256),\n/* harmony export */ sha3_384: () => (/* binding */ sha3_384),\n/* harmony export */ sha3_512: () => (/* binding */ sha3_512),\n/* harmony export */ shake128: () => (/* binding */ shake128),\n/* harmony export */ shake256: () => (/* binding */ shake256)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _u64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_u64.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_u64.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.split)(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlBH)(h, l, s) : (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlSH)(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlBL)(h, l, s) : (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlSL)(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nfunction keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nclass Keccak extends _utils_js__WEBPACK_IMPORTED_MODULE_1__.Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.number)(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.u32)(this.state);\n }\n keccak() {\n keccakP(this.state32, this.rounds);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.exists)(this);\n const { blockLen, state } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.exists)(this, false);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.bytes)(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.number)(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.output)(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen));\nconst sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nconst sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nconst sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nconst sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nconst keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nconst keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nconst keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nconst keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nconst shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nconst shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/sha3.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Keccak: () => (/* binding */ Keccak),\n/* harmony export */ keccakP: () => (/* binding */ keccakP),\n/* harmony export */ keccak_224: () => (/* binding */ keccak_224),\n/* harmony export */ keccak_256: () => (/* binding */ keccak_256),\n/* harmony export */ keccak_384: () => (/* binding */ keccak_384),\n/* harmony export */ keccak_512: () => (/* binding */ keccak_512),\n/* harmony export */ sha3_224: () => (/* binding */ sha3_224),\n/* harmony export */ sha3_256: () => (/* binding */ sha3_256),\n/* harmony export */ sha3_384: () => (/* binding */ sha3_384),\n/* harmony export */ sha3_512: () => (/* binding */ sha3_512),\n/* harmony export */ shake128: () => (/* binding */ shake128),\n/* harmony export */ shake256: () => (/* binding */ shake256)\n/* harmony export */ });\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js\");\n/* harmony import */ var _u64_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_u64.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_u64.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js\");\n\n\n\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.split)(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlBH)(h, l, s) : (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlSH)(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlBL)(h, l, s) : (0,_u64_js__WEBPACK_IMPORTED_MODULE_0__.rotlSL)(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nfunction keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nclass Keccak extends _utils_js__WEBPACK_IMPORTED_MODULE_1__.Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.number)(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.u32)(this.state);\n }\n keccak() {\n if (!_utils_js__WEBPACK_IMPORTED_MODULE_1__.isLE)\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.byteSwap32)(this.state32);\n keccakP(this.state32, this.rounds);\n if (!_utils_js__WEBPACK_IMPORTED_MODULE_1__.isLE)\n (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.byteSwap32)(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.exists)(this);\n const { blockLen, state } = this;\n data = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.toBytes)(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.exists)(this, false);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.bytes)(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.number)(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_2__.output)(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapConstructor)(() => new Keccak(blockLen, suffix, outputLen));\nconst sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nconst sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nconst sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nconst sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nconst keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nconst keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nconst keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nconst keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.wrapXOFConstructorWithOpts)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nconst shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nconst shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/sha3.js?"); /***/ }), @@ -13636,7 +18321,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hash: () => (/* binding */ Hash),\n/* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ checkOpts: () => (/* binding */ checkOpts),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createView: () => (/* binding */ createView),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ isLE: () => (/* binding */ isLE),\n/* harmony export */ nextTick: () => (/* binding */ nextTick),\n/* harmony export */ randomBytes: () => (/* binding */ randomBytes),\n/* harmony export */ rotr: () => (/* binding */ rotr),\n/* harmony export */ toBytes: () => (/* binding */ toBytes),\n/* harmony export */ u32: () => (/* binding */ u32),\n/* harmony export */ u8: () => (/* binding */ u8),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),\n/* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts),\n/* harmony export */ wrapXOFConstructorWithOpts: () => (/* binding */ wrapXOFConstructorWithOpts)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/crypto.js\");\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\n\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\n// Other libraries would silently corrupt the data instead of throwing an error,\n// when they don't support it.\nconst isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n if (!isBytes(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!isBytes(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a))\n throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto.getRandomValues === 'function') {\n return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_0__.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Hash: () => (/* binding */ Hash),\n/* harmony export */ asyncLoop: () => (/* binding */ asyncLoop),\n/* harmony export */ byteSwap: () => (/* binding */ byteSwap),\n/* harmony export */ byteSwap32: () => (/* binding */ byteSwap32),\n/* harmony export */ byteSwapIfBE: () => (/* binding */ byteSwapIfBE),\n/* harmony export */ bytesToHex: () => (/* binding */ bytesToHex),\n/* harmony export */ checkOpts: () => (/* binding */ checkOpts),\n/* harmony export */ concatBytes: () => (/* binding */ concatBytes),\n/* harmony export */ createView: () => (/* binding */ createView),\n/* harmony export */ hexToBytes: () => (/* binding */ hexToBytes),\n/* harmony export */ isBytes: () => (/* binding */ isBytes),\n/* harmony export */ isLE: () => (/* binding */ isLE),\n/* harmony export */ nextTick: () => (/* binding */ nextTick),\n/* harmony export */ randomBytes: () => (/* binding */ randomBytes),\n/* harmony export */ rotl: () => (/* binding */ rotl),\n/* harmony export */ rotr: () => (/* binding */ rotr),\n/* harmony export */ toBytes: () => (/* binding */ toBytes),\n/* harmony export */ u32: () => (/* binding */ u32),\n/* harmony export */ u8: () => (/* binding */ u8),\n/* harmony export */ utf8ToBytes: () => (/* binding */ utf8ToBytes),\n/* harmony export */ wrapConstructor: () => (/* binding */ wrapConstructor),\n/* harmony export */ wrapConstructorWithOpts: () => (/* binding */ wrapConstructorWithOpts),\n/* harmony export */ wrapXOFConstructorWithOpts: () => (/* binding */ wrapXOFConstructorWithOpts)\n/* harmony export */ });\n/* harmony import */ var _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @noble/hashes/crypto */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/crypto.js\");\n/* harmony import */ var _assert_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./_assert.js */ \"./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/_assert.js\");\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\n\n\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nfunction isBytes(a) {\n return (a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));\n}\n// Cast array to different type\nconst u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nconst u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nconst createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nconst rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);\nconst isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nconst byteSwap = (word) => ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nconst byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);\n// In place byte swap for Uint32Array\nfunction byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nfunction bytesToHex(bytes) {\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };\nfunction asciiToBase16(char) {\n if (char >= asciis._0 && char <= asciis._9)\n return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F)\n return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f)\n return char - (asciis._a - 10);\n return;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nfunction hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nconst nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nasync function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nfunction utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nfunction toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nfunction concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n (0,_assert_js__WEBPACK_IMPORTED_MODULE_0__.bytes)(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n// For runtime check if class implements interface\nclass Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nfunction checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nfunction wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nfunction wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nfunction wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nfunction randomBytes(bytesLength = 32) {\n if (_noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto && typeof _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues === 'function') {\n return _noble_hashes_crypto__WEBPACK_IMPORTED_MODULE_1__.crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/ethereum-cryptography/node_modules/@noble/hashes/esm/utils.js?"); /***/ }), @@ -13680,7 +18365,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -13724,7 +18409,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -13845,7 +18530,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -13889,7 +18574,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/interface-datastore/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/interface-datastore/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -14058,6 +18743,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/it-byte-stream/dist/src/errors.js": +/*!********************************************************!*\ + !*** ./node_modules/it-byte-stream/dist/src/errors.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ UnexpectedEOFError: () => (/* binding */ UnexpectedEOFError)\n/* harmony export */ });\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nclass UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-byte-stream/dist/src/errors.js?"); + +/***/ }), + /***/ "./node_modules/it-byte-stream/dist/src/index.js": /*!*******************************************************!*\ !*** ./node_modules/it-byte-stream/dist/src/index.js ***! @@ -14065,18 +18761,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ byteStream: () => (/* binding */ byteStream)\n/* harmony export */ });\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _pushable_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pushable.js */ \"./node_modules/it-byte-stream/dist/src/pushable.js\");\n/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\n\nclass CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\nclass AbortError extends CodeError {\n type;\n constructor(message) {\n super(message, 'ABORT_ERR');\n this.type = 'aborted';\n }\n}\nfunction byteStream(duplex, opts) {\n const write = (0,_pushable_js__WEBPACK_IMPORTED_MODULE_1__.pushable)();\n duplex.sink(write).catch(async (err) => {\n await write.end(err);\n });\n duplex.sink = async (source) => {\n for await (const buf of source) {\n await write.push(buf);\n }\n await write.end();\n };\n let source = duplex.source;\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]();\n }\n else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]();\n }\n const readBuffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_0__.Uint8ArrayList();\n const W = {\n read: async (bytes, options) => {\n options?.signal?.throwIfAborted();\n let listener;\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'));\n };\n options?.signal?.addEventListener('abort', listener);\n });\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n return new uint8arraylist__WEBPACK_IMPORTED_MODULE_0__.Uint8ArrayList();\n }\n return value;\n }\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n throw new CodeError('unexpected end of input', 'ERR_UNEXPECTED_EOF');\n }\n readBuffer.append(value);\n }\n const buf = readBuffer.sublist(0, bytes);\n readBuffer.consume(bytes);\n return buf;\n }\n finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener);\n }\n }\n },\n write: async (data, options) => {\n options?.signal?.throwIfAborted();\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options);\n }\n else {\n await write.push(data.subarray(), options);\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source;\n duplex.source = (async function* () {\n if (opts?.yieldBytes === false) {\n yield readBuffer;\n }\n else {\n yield* readBuffer;\n }\n yield* originalStream;\n }());\n }\n return duplex;\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-byte-stream/dist/src/index.js?"); - -/***/ }), - -/***/ "./node_modules/it-byte-stream/dist/src/pushable.js": -/*!**********************************************************!*\ - !*** ./node_modules/it-byte-stream/dist/src/pushable.js ***! - \**********************************************************/ -/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ pushable: () => (/* binding */ pushable)\n/* harmony export */ });\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/* harmony import */ var _index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index.js */ \"./node_modules/it-byte-stream/dist/src/index.js\");\n\n\n\nclass QueuelessPushable {\n readNext;\n haveNext;\n ended;\n nextResult;\n constructor() {\n this.ended = false;\n this.readNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_2__[\"default\"])();\n this.haveNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_2__[\"default\"])();\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n async next() {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise;\n }\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined');\n }\n const nextResult = this.nextResult;\n this.nextResult = undefined;\n // signal to the supplier that we read the value\n this.readNext.resolve();\n this.readNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_2__[\"default\"])();\n return nextResult;\n }\n async throw(err) {\n this.ended = true;\n if (err != null) {\n this.haveNext.reject(err);\n }\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n async return() {\n const result = {\n done: true,\n value: undefined\n };\n await this._push(undefined);\n return result;\n }\n async push(value, options) {\n await this._push(value, options);\n }\n async end(err, options) {\n if (err != null) {\n await this.throw(err);\n }\n else {\n // abortable return\n await this._push(undefined, options);\n }\n }\n async _push(value, options) {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable');\n }\n // already have a value, wait for it to be read\n if (this.nextResult != null) {\n await this.readNext.promise;\n if (this.nextResult != null) {\n throw new Error('NeedNext promise resolved but nextResult was not consumed');\n }\n }\n if (value != null) {\n this.nextResult = { done: false, value };\n }\n else {\n this.ended = true;\n this.nextResult = { done: true, value: undefined };\n }\n // let the consumer know we have a new value\n this.haveNext.resolve();\n this.haveNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_2__[\"default\"])();\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_0__.raceSignal)(this.readNext.promise, options?.signal, options);\n }\n}\nfunction pushable() {\n return new QueuelessPushable();\n}\n//# sourceMappingURL=pushable.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-byte-stream/dist/src/pushable.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ byteStream: () => (/* binding */ byteStream)\n/* harmony export */ });\n/* harmony import */ var it_queueless_pushable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-queueless-pushable */ \"./node_modules/it-queueless-pushable/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/it-byte-stream/dist/src/errors.js\");\n/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive bytes over streams.\n *\n * @example\n *\n * ```typescript\n * import { byteStream } from 'it-byte-stream'\n *\n * const stream = byteStream(duplex)\n *\n * // read the next chunk\n * const bytes = await stream.read()\n *\n * // read the next five bytes\n * const fiveBytes = await stream.read(5)\n *\n * // write bytes into the stream\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n * ```\n */\n\n\n\n/**\n * @deprecated This will not be exported in a future release\n */\nclass CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * @deprecated This will not be exported in a future release\n */\nclass AbortError extends CodeError {\n type;\n constructor(message) {\n super(message, 'ABORT_ERR');\n this.type = 'aborted';\n this.name = 'AbortError';\n }\n}\nfunction byteStream(duplex, opts) {\n const write = (0,it_queueless_pushable__WEBPACK_IMPORTED_MODULE_0__.queuelessPushable)();\n duplex.sink(write).catch(async (err) => {\n await write.end(err);\n });\n duplex.sink = async (source) => {\n for await (const buf of source) {\n await write.push(buf);\n }\n await write.end();\n };\n let source = duplex.source;\n if (duplex.source[Symbol.iterator] != null) {\n source = duplex.source[Symbol.iterator]();\n }\n else if (duplex.source[Symbol.asyncIterator] != null) {\n source = duplex.source[Symbol.asyncIterator]();\n }\n const readBuffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList();\n const W = {\n read: async (bytes, options) => {\n options?.signal?.throwIfAborted();\n let listener;\n const abortPromise = new Promise((resolve, reject) => {\n listener = () => {\n reject(new AbortError('Read aborted'));\n };\n options?.signal?.addEventListener('abort', listener);\n });\n try {\n if (bytes == null) {\n // just read whatever arrives\n const { done, value } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n return new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList();\n }\n return value;\n }\n while (readBuffer.byteLength < bytes) {\n const { value, done } = await Promise.race([\n source.next(),\n abortPromise\n ]);\n if (done === true) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.UnexpectedEOFError('unexpected end of input');\n }\n readBuffer.append(value);\n }\n const buf = readBuffer.sublist(0, bytes);\n readBuffer.consume(bytes);\n return buf;\n }\n finally {\n if (listener != null) {\n options?.signal?.removeEventListener('abort', listener);\n }\n }\n },\n write: async (data, options) => {\n options?.signal?.throwIfAborted();\n // just write\n if (data instanceof Uint8Array) {\n await write.push(data, options);\n }\n else {\n await write.push(data.subarray(), options);\n }\n },\n unwrap: () => {\n if (readBuffer.byteLength > 0) {\n const originalStream = duplex.source;\n duplex.source = (async function* () {\n if (opts?.yieldBytes === false) {\n yield readBuffer;\n }\n else {\n yield* readBuffer;\n }\n yield* originalStream;\n }());\n }\n return duplex;\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-byte-stream/dist/src/index.js?"); /***/ }), @@ -14098,7 +18783,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var it_peekable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-peekable */ \"./node_modules/it-peekable/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = val => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => val > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\n\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction filter(source, fn) {\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const entry of source) {\n if (await fn(entry)) {\n yield entry;\n }\n }\n })();\n }\n // if mapping function returns a promise we have to return an async generator\n const peekable = (0,it_peekable__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(source);\n const { value, done } = peekable.next();\n if (done === true) {\n return (function* () { }());\n }\n const res = fn(value);\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function* () {\n if (await res) {\n yield value;\n }\n for await (const entry of peekable) {\n if (await fn(entry)) {\n yield entry;\n }\n }\n })();\n }\n const func = fn;\n return (function* () {\n if (res === true) {\n yield value;\n }\n for (const entry of peekable) {\n if (func(entry)) {\n yield entry;\n }\n }\n })();\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (filter);\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-filter/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var it_peekable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-peekable */ \"./node_modules/it-peekable/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * Filter values out of an (async)iterable\n *\n * @example\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * // This can also be an iterator, generator, etc\n * const values = [0, 1, 2, 3, 4]\n *\n * const fn = (val, index) => val > 2 // Return boolean to keep item\n *\n * const arr = all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n *\n * Async sources and filter functions must be awaited:\n *\n * ```javascript\n * import all from 'it-all'\n * import filter from 'it-filter'\n *\n * const values = async function * () {\n * yield * [0, 1, 2, 3, 4]\n * }\n *\n * const fn = async val => (val, index) > 2 // Return boolean or promise of boolean to keep item\n *\n * const arr = await all(filter(values, fn))\n *\n * console.info(arr) // 3, 4\n * ```\n */\n\nfunction isAsyncIterable(thing) {\n return thing[Symbol.asyncIterator] != null;\n}\nfunction filter(source, fn) {\n let index = 0;\n if (isAsyncIterable(source)) {\n return (async function* () {\n for await (const entry of source) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n // if mapping function returns a promise we have to return an async generator\n const peekable = (0,it_peekable__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(source);\n const { value, done } = peekable.next();\n if (done === true) {\n return (function* () { }());\n }\n const res = fn(value, index++);\n // @ts-expect-error .then is not present on O\n if (typeof res.then === 'function') {\n return (async function* () {\n if (await res) {\n yield value;\n }\n for await (const entry of peekable) {\n if (await fn(entry, index++)) {\n yield entry;\n }\n }\n })();\n }\n const func = fn;\n return (function* () {\n if (res === true) {\n yield value;\n }\n for (const entry of peekable) {\n if (func(entry, index++)) {\n yield entry;\n }\n }\n })();\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (filter);\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-filter/dist/src/index.js?"); /***/ }), @@ -14113,6 +18798,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/it-length-prefixed-stream/dist/src/errors.js": +/*!*******************************************************************!*\ + !*** ./node_modules/it-length-prefixed-stream/dist/src/errors.js ***! + \*******************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ InvalidDataLengthError: () => (/* binding */ InvalidDataLengthError),\n/* harmony export */ InvalidDataLengthLengthError: () => (/* binding */ InvalidDataLengthLengthError),\n/* harmony export */ InvalidMessageLengthError: () => (/* binding */ InvalidMessageLengthError)\n/* harmony export */ });\n/**\n * The reported length of the next data message was not a positive integer\n */\nclass InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nclass InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nclass InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed-stream/dist/src/errors.js?"); + +/***/ }), + /***/ "./node_modules/it-length-prefixed-stream/dist/src/index.js": /*!******************************************************************!*\ !*** ./node_modules/it-length-prefixed-stream/dist/src/index.js ***! @@ -14120,7 +18816,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ lpStream: () => (/* binding */ lpStream)\n/* harmony export */ });\n/* harmony import */ var it_byte_stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-byte-stream */ \"./node_modules/it-byte-stream/dist/src/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\n\n\n\nclass CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\nfunction lpStream(duplex, opts = {}) {\n const bytes = (0,it_byte_stream__WEBPACK_IMPORTED_MODULE_0__.byteStream)(duplex, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = uint8_varint__WEBPACK_IMPORTED_MODULE_1__.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? uint8_varint__WEBPACK_IMPORTED_MODULE_1__.decode;\n const encodeLength = opts?.lengthEncoder ?? uint8_varint__WEBPACK_IMPORTED_MODULE_1__.encode;\n const W = {\n read: async (options) => {\n let dataLength = -1;\n const lengthBuffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options));\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new CodeError('message length length too long', 'ERR_MSG_LENGTH_TOO_LONG');\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new CodeError('message length too long', 'ERR_MSG_DATA_TOO_LONG');\n }\n return bytes.read(dataLength, options);\n },\n write: async (data, options) => {\n // encode, write\n await bytes.write(new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n writeV: async (data, options) => {\n const list = new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap: () => {\n return bytes.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed-stream/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ lpStream: () => (/* binding */ lpStream)\n/* harmony export */ });\n/* harmony import */ var it_byte_stream__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! it-byte-stream */ \"./node_modules/it-byte-stream/dist/src/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/it-length-prefixed-stream/dist/src/errors.js\");\n/**\n * @packageDocumentation\n *\n * This module makes it easy to send and receive length-prefixed byte arrays over streams.\n *\n * @example\n *\n * ```typescript\n * import { lpStream } from 'it-length-prefixed-stream'\n *\n * const stream = lpStream(duplex)\n *\n * // read the next length-prefixed chunk\n * const bytes = await stream.read()\n *\n * // write a length-prefixed chunk\n * await stream.write(Uint8Array.from([0, 1, 2, 3, 4]))\n *\n * // write several chunks, all individually length-prefixed\n * await stream.writeV([\n * Uint8Array.from([0, 1, 2, 3, 4]),\n * Uint8Array.from([5, 6, 7, 8, 9])\n * ])\n * ```\n */\n\n\n\n\nfunction lpStream(duplex, opts = {}) {\n const bytes = (0,it_byte_stream__WEBPACK_IMPORTED_MODULE_0__.byteStream)(duplex, opts);\n if (opts.maxDataLength != null && opts.maxLengthLength == null) {\n // if max data length is set but max length length is not, calculate the\n // max length length needed to encode max data length\n opts.maxLengthLength = uint8_varint__WEBPACK_IMPORTED_MODULE_1__.encodingLength(opts.maxDataLength);\n }\n const decodeLength = opts?.lengthDecoder ?? uint8_varint__WEBPACK_IMPORTED_MODULE_1__.decode;\n const encodeLength = opts?.lengthEncoder ?? uint8_varint__WEBPACK_IMPORTED_MODULE_1__.encode;\n const W = {\n read: async (options) => {\n let dataLength = -1;\n const lengthBuffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList();\n while (true) {\n // read one byte at a time until we can decode a varint\n lengthBuffer.append(await bytes.read(1, options));\n try {\n dataLength = decodeLength(lengthBuffer);\n }\n catch (err) {\n if (err instanceof RangeError) {\n continue;\n }\n throw err;\n }\n if (dataLength < 0) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.InvalidMessageLengthError('Invalid message length');\n }\n if (opts?.maxLengthLength != null && lengthBuffer.byteLength > opts.maxLengthLength) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.InvalidDataLengthLengthError('message length length too long');\n }\n if (dataLength > -1) {\n break;\n }\n }\n if (opts?.maxDataLength != null && dataLength > opts.maxDataLength) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_3__.InvalidDataLengthError('message length too long');\n }\n return bytes.read(dataLength, options);\n },\n write: async (data, options) => {\n // encode, write\n await bytes.write(new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(encodeLength(data.byteLength), data), options);\n },\n writeV: async (data, options) => {\n const list = new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList(...data.flatMap(buf => ([encodeLength(buf.byteLength), buf])));\n // encode, write\n await bytes.write(list, options);\n },\n unwrap: () => {\n return bytes.unwrap();\n }\n };\n return W;\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed-stream/dist/src/index.js?"); /***/ }), @@ -14131,7 +18827,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MAX_DATA_LENGTH: () => (/* binding */ MAX_DATA_LENGTH),\n/* harmony export */ MAX_LENGTH_LENGTH: () => (/* binding */ MAX_LENGTH_LENGTH),\n/* harmony export */ decode: () => (/* binding */ decode)\n/* harmony export */ });\n/* harmony import */ var err_code__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! err-code */ \"./node_modules/err-code/index.js\");\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/it-length-prefixed/dist/src/utils.js\");\n/* eslint max-depth: [\"error\", 6] */\n\n\n\n\n// Maximum length of the length section of the message\nconst MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nconst MAX_DATA_LENGTH = 1024 * 1024 * 4;\nvar ReadMode;\n(function (ReadMode) {\n ReadMode[ReadMode[\"LENGTH\"] = 0] = \"LENGTH\";\n ReadMode[ReadMode[\"DATA\"] = 1] = \"DATA\";\n})(ReadMode || (ReadMode = {}));\nconst defaultDecoder = (buf) => {\n const length = uint8_varint__WEBPACK_IMPORTED_MODULE_1__.decode(buf);\n defaultDecoder.bytes = uint8_varint__WEBPACK_IMPORTED_MODULE_1__.encodingLength(length);\n return length;\n};\ndefaultDecoder.bytes = 0;\nfunction decode(source, options) {\n const buffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_2__.Uint8ArrayList();\n let mode = ReadMode.LENGTH;\n let dataLength = -1;\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;\n function* maybeYield() {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer);\n if (dataLength < 0) {\n throw err_code__WEBPACK_IMPORTED_MODULE_0__(new Error('invalid message length'), 'ERR_INVALID_MSG_LENGTH');\n }\n if (dataLength > maxDataLength) {\n throw err_code__WEBPACK_IMPORTED_MODULE_0__(new Error('message length too long'), 'ERR_MSG_DATA_TOO_LONG');\n }\n const dataLengthLength = lengthDecoder.bytes;\n buffer.consume(dataLengthLength);\n if (options?.onLength != null) {\n options.onLength(dataLength);\n }\n mode = ReadMode.DATA;\n }\n catch (err) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw err_code__WEBPACK_IMPORTED_MODULE_0__(new Error('message length length too long'), 'ERR_MSG_LENGTH_TOO_LONG');\n }\n break;\n }\n throw err;\n }\n }\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break;\n }\n const data = buffer.sublist(0, dataLength);\n buffer.consume(dataLength);\n if (options?.onData != null) {\n options.onData(data);\n }\n yield data;\n mode = ReadMode.LENGTH;\n }\n }\n }\n if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_3__.isAsyncIterable)(source)) {\n return (async function* () {\n for await (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw err_code__WEBPACK_IMPORTED_MODULE_0__(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');\n }\n })();\n }\n return (function* () {\n for (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw err_code__WEBPACK_IMPORTED_MODULE_0__(new Error('unexpected end of input'), 'ERR_UNEXPECTED_EOF');\n }\n })();\n}\ndecode.fromReader = (reader, options) => {\n let byteLength = 1; // Read single byte chunks until the length is known\n const varByteSource = (async function* () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength);\n if (done === true) {\n return;\n }\n if (value != null) {\n yield value;\n }\n }\n catch (err) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null };\n }\n throw err;\n }\n finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1;\n }\n }\n }());\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l) => { byteLength = l; };\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n });\n};\n//# sourceMappingURL=decode.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed/dist/src/decode.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ MAX_DATA_LENGTH: () => (/* binding */ MAX_DATA_LENGTH),\n/* harmony export */ MAX_LENGTH_LENGTH: () => (/* binding */ MAX_LENGTH_LENGTH),\n/* harmony export */ decode: () => (/* binding */ decode)\n/* harmony export */ });\n/* harmony import */ var uint8_varint__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! uint8-varint */ \"./node_modules/uint8-varint/dist/src/index.js\");\n/* harmony import */ var uint8arraylist__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! uint8arraylist */ \"./node_modules/uint8arraylist/dist/src/index.js\");\n/* harmony import */ var _errors_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./errors.js */ \"./node_modules/it-length-prefixed/dist/src/errors.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/it-length-prefixed/dist/src/utils.js\");\n/* eslint max-depth: [\"error\", 6] */\n\n\n\n\n// Maximum length of the length section of the message\nconst MAX_LENGTH_LENGTH = 8; // Varint.encode(Number.MAX_SAFE_INTEGER).length\n// Maximum length of the data section of the message\nconst MAX_DATA_LENGTH = 1024 * 1024 * 4;\nvar ReadMode;\n(function (ReadMode) {\n ReadMode[ReadMode[\"LENGTH\"] = 0] = \"LENGTH\";\n ReadMode[ReadMode[\"DATA\"] = 1] = \"DATA\";\n})(ReadMode || (ReadMode = {}));\nconst defaultDecoder = (buf) => {\n const length = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.decode(buf);\n defaultDecoder.bytes = uint8_varint__WEBPACK_IMPORTED_MODULE_0__.encodingLength(length);\n return length;\n};\ndefaultDecoder.bytes = 0;\nfunction decode(source, options) {\n const buffer = new uint8arraylist__WEBPACK_IMPORTED_MODULE_1__.Uint8ArrayList();\n let mode = ReadMode.LENGTH;\n let dataLength = -1;\n const lengthDecoder = options?.lengthDecoder ?? defaultDecoder;\n const maxLengthLength = options?.maxLengthLength ?? MAX_LENGTH_LENGTH;\n const maxDataLength = options?.maxDataLength ?? MAX_DATA_LENGTH;\n function* maybeYield() {\n while (buffer.byteLength > 0) {\n if (mode === ReadMode.LENGTH) {\n // read length, ignore errors for short reads\n try {\n dataLength = lengthDecoder(buffer);\n if (dataLength < 0) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.InvalidMessageLengthError('Invalid message length');\n }\n if (dataLength > maxDataLength) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.InvalidDataLengthError('Message length too long');\n }\n const dataLengthLength = lengthDecoder.bytes;\n buffer.consume(dataLengthLength);\n if (options?.onLength != null) {\n options.onLength(dataLength);\n }\n mode = ReadMode.DATA;\n }\n catch (err) {\n if (err instanceof RangeError) {\n if (buffer.byteLength > maxLengthLength) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.InvalidDataLengthLengthError('Message length length too long');\n }\n break;\n }\n throw err;\n }\n }\n if (mode === ReadMode.DATA) {\n if (buffer.byteLength < dataLength) {\n // not enough data, wait for more\n break;\n }\n const data = buffer.sublist(0, dataLength);\n buffer.consume(dataLength);\n if (options?.onData != null) {\n options.onData(data);\n }\n yield data;\n mode = ReadMode.LENGTH;\n }\n }\n }\n if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_3__.isAsyncIterable)(source)) {\n return (async function* () {\n for await (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.UnexpectedEOFError('Unexpected end of input');\n }\n })();\n }\n return (function* () {\n for (const buf of source) {\n buffer.append(buf);\n yield* maybeYield();\n }\n if (buffer.byteLength > 0) {\n throw new _errors_js__WEBPACK_IMPORTED_MODULE_2__.UnexpectedEOFError('Unexpected end of input');\n }\n })();\n}\ndecode.fromReader = (reader, options) => {\n let byteLength = 1; // Read single byte chunks until the length is known\n const varByteSource = (async function* () {\n while (true) {\n try {\n const { done, value } = await reader.next(byteLength);\n if (done === true) {\n return;\n }\n if (value != null) {\n yield value;\n }\n }\n catch (err) {\n if (err.code === 'ERR_UNDER_READ') {\n return { done: true, value: null };\n }\n throw err;\n }\n finally {\n // Reset the byteLength so we continue to check for varints\n byteLength = 1;\n }\n }\n }());\n /**\n * Once the length has been parsed, read chunk for that length\n */\n const onLength = (l) => { byteLength = l; };\n return decode(varByteSource, {\n ...(options ?? {}),\n onLength\n });\n};\n//# sourceMappingURL=decode.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed/dist/src/decode.js?"); /***/ }), @@ -14146,6 +18842,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/it-length-prefixed/dist/src/errors.js": +/*!************************************************************!*\ + !*** ./node_modules/it-length-prefixed/dist/src/errors.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ InvalidDataLengthError: () => (/* binding */ InvalidDataLengthError),\n/* harmony export */ InvalidDataLengthLengthError: () => (/* binding */ InvalidDataLengthLengthError),\n/* harmony export */ InvalidMessageLengthError: () => (/* binding */ InvalidMessageLengthError),\n/* harmony export */ UnexpectedEOFError: () => (/* binding */ UnexpectedEOFError)\n/* harmony export */ });\n/**\n * The reported length of the next data message was not a positive integer\n */\nclass InvalidMessageLengthError extends Error {\n name = 'InvalidMessageLengthError';\n code = 'ERR_INVALID_MSG_LENGTH';\n}\n/**\n * The reported length of the next data message was larger than the configured\n * max allowable value\n */\nclass InvalidDataLengthError extends Error {\n name = 'InvalidDataLengthError';\n code = 'ERR_MSG_DATA_TOO_LONG';\n}\n/**\n * The varint used to specify the length of the next data message contained more\n * bytes than the configured max allowable value\n */\nclass InvalidDataLengthLengthError extends Error {\n name = 'InvalidDataLengthLengthError';\n code = 'ERR_MSG_LENGTH_TOO_LONG';\n}\n/**\n * The incoming stream ended before the expected number of bytes were read\n */\nclass UnexpectedEOFError extends Error {\n name = 'UnexpectedEOFError';\n code = 'ERR_UNEXPECTED_EOF';\n}\n//# sourceMappingURL=errors.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed/dist/src/errors.js?"); + +/***/ }), + /***/ "./node_modules/it-length-prefixed/dist/src/index.js": /*!***********************************************************!*\ !*** ./node_modules/it-length-prefixed/dist/src/index.js ***! @@ -14153,7 +18860,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_1__.decode),\n/* harmony export */ encode: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_0__.encode)\n/* harmony export */ });\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/it-length-prefixed/dist/src/encode.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/it-length-prefixed/dist/src/decode.js\");\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ decode: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_1__.decode),\n/* harmony export */ encode: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_0__.encode)\n/* harmony export */ });\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/it-length-prefixed/dist/src/encode.js\");\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/it-length-prefixed/dist/src/decode.js\");\n/**\n * @packageDocumentation\n *\n * Encode/decode streams of bytes with length-prefixes.\n *\n * @example\n *\n * ```js\n * import { pipe } from 'it-pipe'\n * import * as lp from 'it-length-prefixed'\n *\n * const encoded = []\n *\n * // encode\n * await pipe(\n * [uint8ArrayFromString('hello world')],\n * (source) => lp.encode(source),\n * async source => {\n * for await (const chunk of source) {\n * encoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)\n * }\n * }\n * )\n *\n * console.log(encoded)\n * // => [Buffer <0b 68 65 6c 6c 6f 20 77 6f 72 6c 64>]\n *\n * const decoded = []\n *\n * // decode\n * await pipe(\n * encoded, // e.g. from above\n * (source) => lp.decode(source),\n * async source => {\n * for await (const chunk of source) {\n * decoded.push(chunk.slice()) // (.slice converts Uint8ArrayList to Uint8Array)\n * }\n * }\n * )\n *\n * console.log(decoded)\n * // => [Buffer <68 65 6c 6c 6f 20 77 6f 72 6c 64>]\n * ```\n */\n\n\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-length-prefixed/dist/src/index.js?"); /***/ }), @@ -14278,6 +18985,17 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/it-queueless-pushable/dist/src/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/it-queueless-pushable/dist/src/index.js ***! + \**************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ queuelessPushable: () => (/* binding */ queuelessPushable)\n/* harmony export */ });\n/* harmony import */ var p_defer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-defer */ \"./node_modules/p-defer/index.js\");\n/* harmony import */ var race_signal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! race-signal */ \"./node_modules/race-signal/dist/src/index.js\");\n/**\n * @packageDocumentation\n *\n * A pushable async generator that waits until the current value is consumed\n * before allowing a new value to be pushed.\n *\n * Useful for when you don't want to keep memory usage under control and/or\n * allow a downstream consumer to dictate how fast data flows through a pipe,\n * but you want to be able to apply a transform to that data.\n *\n * @example\n *\n * ```typescript\n * import { queuelessPushable } from 'it-queueless-pushable'\n *\n * const pushable = queuelessPushable()\n *\n * // run asynchronously\n * Promise.resolve().then(async () => {\n * // push a value - the returned promise will not resolve until the value is\n * // read from the pushable\n * await pushable.push('hello')\n * })\n *\n * // read a value\n * const result = await pushable.next()\n * console.info(result) // { done: false, value: 'hello' }\n * ```\n */\n\n\nclass QueuelessPushable {\n readNext;\n haveNext;\n ended;\n nextResult;\n constructor() {\n this.ended = false;\n this.readNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])();\n this.haveNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])();\n }\n [Symbol.asyncIterator]() {\n return this;\n }\n async next() {\n if (this.nextResult == null) {\n // wait for the supplier to push a value\n await this.haveNext.promise;\n }\n if (this.nextResult == null) {\n throw new Error('HaveNext promise resolved but nextResult was undefined');\n }\n const nextResult = this.nextResult;\n this.nextResult = undefined;\n // signal to the supplier that we read the value\n this.readNext.resolve();\n this.readNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])();\n return nextResult;\n }\n async throw(err) {\n this.ended = true;\n if (err != null) {\n // this can cause unhandled promise rejections if nothing is awaiting the\n // next value so attach a dummy catch listener to the promise\n this.haveNext.promise.catch(() => { });\n this.haveNext.reject(err);\n }\n const result = {\n done: true,\n value: undefined\n };\n return result;\n }\n async return() {\n const result = {\n done: true,\n value: undefined\n };\n await this._push(undefined);\n return result;\n }\n async push(value, options) {\n await this._push(value, options);\n }\n async end(err, options) {\n if (err != null) {\n await this.throw(err);\n }\n else {\n // abortable return\n await this._push(undefined, options);\n }\n }\n async _push(value, options) {\n if (value != null && this.ended) {\n throw new Error('Cannot push value onto an ended pushable');\n }\n // wait for all values to be read\n while (this.nextResult != null) {\n await this.readNext.promise;\n }\n if (value != null) {\n this.nextResult = { done: false, value };\n }\n else {\n this.ended = true;\n this.nextResult = { done: true, value: undefined };\n }\n // let the consumer know we have a new value\n this.haveNext.resolve();\n this.haveNext = (0,p_defer__WEBPACK_IMPORTED_MODULE_1__[\"default\"])();\n // wait for the consumer to have finished processing the value and requested\n // the next one or for the passed signal to abort the waiting\n await (0,race_signal__WEBPACK_IMPORTED_MODULE_0__.raceSignal)(this.readNext.promise, options?.signal, options);\n }\n}\nfunction queuelessPushable() {\n return new QueuelessPushable();\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-queueless-pushable/dist/src/index.js?"); + +/***/ }), + /***/ "./node_modules/it-sort/dist/src/index.js": /*!************************************************!*\ !*** ./node_modules/it-sort/dist/src/index.js ***! @@ -14384,7 +19102,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -14428,7 +19146,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -14549,7 +19267,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -14593,7 +19311,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/it-ws/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/it-ws/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -14758,7 +19476,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var observable_webworkers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! observable-webworkers */ \"./node_modules/observable-webworkers/dist/src/index.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/mortice/dist/src/constants.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/mortice/dist/src/utils.js\");\n\n\n\nconst handleWorkerLockRequest = (emitter, masterEvent, requestType, releaseType, grantType) => {\n return (worker, event) => {\n if (event.data.type !== requestType) {\n return;\n }\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async () => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n });\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener);\n resolve();\n }\n };\n worker.addEventListener('message', releaseEventListener);\n });\n }\n }\n }));\n };\n};\nconst makeWorkerLockRequest = (name, requestType, grantType, releaseType) => {\n return async () => {\n const id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.nanoid)();\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n });\n return new Promise((resolve) => {\n const listener = (event) => {\n if (event == null || event.data == null) {\n return;\n }\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n };\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener);\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n });\n });\n }\n };\n globalThis.addEventListener('message', listener);\n });\n };\n};\nconst defaultOptions = {\n singleProcess: false\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((options) => {\n options = Object.assign({}, defaultOptions, options);\n const isPrimary = Boolean(globalThis.document) || options.singleProcess;\n if (isPrimary) {\n const emitter = new EventTarget();\n observable_webworkers__WEBPACK_IMPORTED_MODULE_0__[\"default\"].addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_READ_LOCK));\n observable_webworkers__WEBPACK_IMPORTED_MODULE_0__[\"default\"].addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_WRITE_LOCK));\n return emitter;\n }\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_WRITE_LOCK)\n };\n});\n//# sourceMappingURL=browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/mortice/dist/src/browser.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var observable_webworkers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! observable-webworkers */ \"./node_modules/observable-webworkers/dist/src/index.js\");\n/* harmony import */ var _constants_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constants.js */ \"./node_modules/mortice/dist/src/constants.js\");\n/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ \"./node_modules/mortice/dist/src/utils.js\");\n\n\n\nconst handleWorkerLockRequest = (emitter, masterEvent, requestType, releaseType, grantType) => {\n return (worker, event) => {\n if (event.data.type !== requestType) {\n return;\n }\n const requestEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n emitter.dispatchEvent(new MessageEvent(masterEvent, {\n data: {\n name: requestEvent.name,\n handler: async () => {\n // grant lock to worker\n worker.postMessage({\n type: grantType,\n name: requestEvent.name,\n identifier: requestEvent.identifier\n });\n // wait for worker to finish\n await new Promise((resolve) => {\n const releaseEventListener = (event) => {\n if (event?.data == null) {\n return;\n }\n const releaseEvent = {\n type: event.data.type,\n name: event.data.name,\n identifier: event.data.identifier\n };\n if (releaseEvent.type === releaseType && releaseEvent.identifier === requestEvent.identifier) {\n worker.removeEventListener('message', releaseEventListener);\n resolve();\n }\n };\n worker.addEventListener('message', releaseEventListener);\n });\n }\n }\n }));\n };\n};\nconst makeWorkerLockRequest = (name, requestType, grantType, releaseType) => {\n return async () => {\n const id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_2__.nanoid)();\n globalThis.postMessage({\n type: requestType,\n identifier: id,\n name\n });\n return new Promise((resolve) => {\n const listener = (event) => {\n if (event?.data == null) {\n return;\n }\n const responseEvent = {\n type: event.data.type,\n identifier: event.data.identifier\n };\n if (responseEvent.type === grantType && responseEvent.identifier === id) {\n globalThis.removeEventListener('message', listener);\n // grant lock\n resolve(() => {\n // release lock\n globalThis.postMessage({\n type: releaseType,\n identifier: id,\n name\n });\n });\n }\n };\n globalThis.addEventListener('message', listener);\n });\n };\n};\nconst defaultOptions = {\n singleProcess: false\n};\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((options) => {\n options = Object.assign({}, defaultOptions, options);\n const isPrimary = Boolean(globalThis.document) || options.singleProcess;\n if (isPrimary) {\n const emitter = new EventTarget();\n observable_webworkers__WEBPACK_IMPORTED_MODULE_0__[\"default\"].addEventListener('message', handleWorkerLockRequest(emitter, 'requestReadLock', _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_READ_LOCK));\n observable_webworkers__WEBPACK_IMPORTED_MODULE_0__[\"default\"].addEventListener('message', handleWorkerLockRequest(emitter, 'requestWriteLock', _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_WRITE_LOCK));\n return emitter;\n }\n return {\n isWorker: true,\n readLock: (name) => makeWorkerLockRequest(name, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_READ_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_READ_LOCK),\n writeLock: (name) => makeWorkerLockRequest(name, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_REQUEST_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.MASTER_GRANT_WRITE_LOCK, _constants_js__WEBPACK_IMPORTED_MODULE_1__.WORKER_RELEASE_WRITE_LOCK)\n };\n});\n//# sourceMappingURL=browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/mortice/dist/src/browser.js?"); /***/ }), @@ -14780,7 +19498,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ createMortice)\n/* harmony export */ });\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! p-queue */ \"./node_modules/p-queue/dist/index.js\");\n/* harmony import */ var p_timeout__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! p-timeout */ \"./node_modules/p-timeout/index.js\");\n/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./node.js */ \"./node_modules/mortice/dist/src/browser.js\");\n/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\n\n\n\nconst mutexes = {};\nlet implementation;\nasync function createReleaseable(queue, options) {\n let res;\n const p = new Promise((resolve) => {\n res = resolve;\n });\n void queue.add(async () => (0,p_timeout__WEBPACK_IMPORTED_MODULE_0__[\"default\"])((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve();\n });\n });\n })(), {\n milliseconds: options.timeout\n }));\n return p;\n}\nconst createMutex = (name, options) => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n };\n }\n const masterQueue = new p_queue__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({ concurrency: 1 });\n let readQueue;\n return {\n async readLock() {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options);\n }\n // Create a new read queue\n readQueue = new p_queue__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({\n concurrency: options.concurrency,\n autoStart: false\n });\n const localReadQueue = readQueue;\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options);\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start();\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null;\n }\n });\n });\n return readPromise;\n },\n async writeLock() {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null;\n return createReleaseable(masterQueue, options);\n }\n };\n};\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n};\nfunction createMortice(options) {\n const opts = Object.assign({}, defaultOptions, options);\n if (implementation == null) {\n implementation = (0,_node_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(opts);\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].readLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n implementation.addEventListener('requestWriteLock', async (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].writeLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n }\n }\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts);\n }\n return mutexes[opts.name];\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/mortice/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ createMortice)\n/* harmony export */ });\n/* harmony import */ var p_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! p-queue */ \"./node_modules/p-queue/dist/index.js\");\n/* harmony import */ var p_timeout__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-timeout */ \"./node_modules/p-timeout/index.js\");\n/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node.js */ \"./node_modules/mortice/dist/src/browser.js\");\n/**\n * @packageDocumentation\n *\n * - Reads occur concurrently\n * - Writes occur one at a time\n * - No reads occur while a write operation is in progress\n * - Locks can be created with different names\n * - Reads/writes can time out\n *\n * ## Usage\n *\n * ```javascript\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * // the lock name & options objects are both optional\n * const mutex = mortice('my-lock', {\n *\n * // how long before write locks time out (default: 24 hours)\n * timeout: 30000,\n *\n * // control how many read operations are executed concurrently (default: Infinity)\n * concurrency: 5,\n *\n * // by default the the lock will be held on the main thread, set this to true if the\n * // a lock should reside on each worker (default: false)\n * singleProcess: false\n * })\n *\n * Promise.all([\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 2')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.writeLock()\n *\n * try {\n * await delay(1000)\n *\n * console.info('write 1')\n * } finally {\n * release()\n * }\n * })(),\n * (async () => {\n * const release = await mutex.readLock()\n *\n * try {\n * console.info('read 3')\n * } finally {\n * release()\n * }\n * })()\n * ])\n * ```\n *\n * read 1\n * read 2\n * \n * write 1\n * read 3\n *\n * ## Browser\n *\n * Because there's no global way to evesdrop on messages sent by Web Workers, please pass all created Web Workers to the [`observable-webworkers`](https://npmjs.org/package/observable-webworkers) module:\n *\n * ```javascript\n * // main.js\n * import mortice from 'mortice'\n * import observe from 'observable-webworkers'\n *\n * // create our lock on the main thread, it will be held here\n * const mutex = mortice()\n *\n * const worker = new Worker('worker.js')\n *\n * observe(worker)\n * ```\n *\n * ```javascript\n * // worker.js\n * import mortice from 'mortice'\n * import delay from 'delay'\n *\n * const mutex = mortice()\n *\n * let release = await mutex.readLock()\n * // read something\n * release()\n *\n * release = await mutex.writeLock()\n * // write something\n * release()\n * ```\n */\n\n\n\nconst mutexes = {};\nlet implementation;\nasync function createReleaseable(queue, options) {\n let res;\n const p = new Promise((resolve) => {\n res = resolve;\n });\n void queue.add(async () => (0,p_timeout__WEBPACK_IMPORTED_MODULE_1__[\"default\"])((async () => {\n await new Promise((resolve) => {\n res(() => {\n resolve();\n });\n });\n })(), {\n milliseconds: options.timeout\n }));\n return p;\n}\nconst createMutex = (name, options) => {\n if (implementation.isWorker === true) {\n return {\n readLock: implementation.readLock(name, options),\n writeLock: implementation.writeLock(name, options)\n };\n }\n const masterQueue = new p_queue__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({ concurrency: 1 });\n let readQueue;\n return {\n async readLock() {\n // If there's already a read queue, just add the task to it\n if (readQueue != null) {\n return createReleaseable(readQueue, options);\n }\n // Create a new read queue\n readQueue = new p_queue__WEBPACK_IMPORTED_MODULE_2__[\"default\"]({\n concurrency: options.concurrency,\n autoStart: false\n });\n const localReadQueue = readQueue;\n // Add the task to the read queue\n const readPromise = createReleaseable(readQueue, options);\n void masterQueue.add(async () => {\n // Start the task only once the master queue has completed processing\n // any previous tasks\n localReadQueue.start();\n // Once all the tasks in the read queue have completed, remove it so\n // that the next read lock will occur after any write locks that were\n // started in the interim\n await localReadQueue.onIdle()\n .then(() => {\n if (readQueue === localReadQueue) {\n readQueue = null;\n }\n });\n });\n return readPromise;\n },\n async writeLock() {\n // Remove the read queue reference, so that any later read locks will be\n // added to a new queue that starts after this write lock has been\n // released\n readQueue = null;\n return createReleaseable(masterQueue, options);\n }\n };\n};\nconst defaultOptions = {\n name: 'lock',\n concurrency: Infinity,\n timeout: 84600000,\n singleProcess: false\n};\nfunction createMortice(options) {\n const opts = Object.assign({}, defaultOptions, options);\n if (implementation == null) {\n implementation = (0,_node_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(opts);\n if (implementation.isWorker !== true) {\n // we are master, set up worker requests\n implementation.addEventListener('requestReadLock', (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].readLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n implementation.addEventListener('requestWriteLock', async (event) => {\n if (mutexes[event.data.name] == null) {\n return;\n }\n void mutexes[event.data.name].writeLock()\n .then(async (release) => event.data.handler().finally(() => { release(); }));\n });\n }\n }\n if (mutexes[opts.name] == null) {\n mutexes[opts.name] = createMutex(opts.name, opts);\n }\n return mutexes[opts.name];\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/mortice/dist/src/index.js?"); /***/ }), @@ -14967,7 +19685,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ PQueue)\n/* harmony export */ });\n/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.mjs\");\n/* harmony import */ var p_timeout__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! p-timeout */ \"./node_modules/p-timeout/index.js\");\n/* harmony import */ var _priority_queue_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./priority-queue.js */ \"./node_modules/p-queue/dist/priority-queue.js\");\n\n\n\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends eventemitter3__WEBPACK_IMPORTED_MODULE_0__.EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: _priority_queue_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"],\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = (0,p_timeout__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof p_timeout__WEBPACK_IMPORTED_MODULE_1__.TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/p-queue/dist/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ PQueue)\n/* harmony export */ });\n/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! eventemitter3 */ \"./node_modules/eventemitter3/index.mjs\");\n/* harmony import */ var p_timeout__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! p-timeout */ \"./node_modules/p-timeout/index.js\");\n/* harmony import */ var _priority_queue_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./priority-queue.js */ \"./node_modules/p-queue/dist/priority-queue.js\");\n\n\n\n/**\nPromise queue with concurrency control.\n*/\nclass PQueue extends eventemitter3__WEBPACK_IMPORTED_MODULE_0__.EventEmitter {\n #carryoverConcurrencyCount;\n #isIntervalIgnored;\n #intervalCount = 0;\n #intervalCap;\n #interval;\n #intervalEnd = 0;\n #intervalId;\n #timeoutId;\n #queue;\n #queueClass;\n #pending = 0;\n // The `!` is needed because of https://github.com/microsoft/TypeScript/issues/32194\n #concurrency;\n #isPaused;\n #throwOnTimeout;\n /**\n Per-operation timeout in milliseconds. Operations fulfill once `timeout` elapses if they haven't already.\n\n Applies to each future operation.\n */\n timeout;\n // TODO: The `throwOnTimeout` option should affect the return types of `add()` and `addAll()`\n constructor(options) {\n super();\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n options = {\n carryoverConcurrencyCount: false,\n intervalCap: Number.POSITIVE_INFINITY,\n interval: 0,\n concurrency: Number.POSITIVE_INFINITY,\n autoStart: true,\n queueClass: _priority_queue_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n ...options,\n };\n if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) {\n throw new TypeError(`Expected \\`intervalCap\\` to be a number from 1 and up, got \\`${options.intervalCap?.toString() ?? ''}\\` (${typeof options.intervalCap})`);\n }\n if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) {\n throw new TypeError(`Expected \\`interval\\` to be a finite number >= 0, got \\`${options.interval?.toString() ?? ''}\\` (${typeof options.interval})`);\n }\n this.#carryoverConcurrencyCount = options.carryoverConcurrencyCount;\n this.#isIntervalIgnored = options.intervalCap === Number.POSITIVE_INFINITY || options.interval === 0;\n this.#intervalCap = options.intervalCap;\n this.#interval = options.interval;\n this.#queue = new options.queueClass();\n this.#queueClass = options.queueClass;\n this.concurrency = options.concurrency;\n this.timeout = options.timeout;\n this.#throwOnTimeout = options.throwOnTimeout === true;\n this.#isPaused = options.autoStart === false;\n }\n get #doesIntervalAllowAnother() {\n return this.#isIntervalIgnored || this.#intervalCount < this.#intervalCap;\n }\n get #doesConcurrentAllowAnother() {\n return this.#pending < this.#concurrency;\n }\n #next() {\n this.#pending--;\n this.#tryToStartAnother();\n this.emit('next');\n }\n #onResumeInterval() {\n this.#onInterval();\n this.#initializeIntervalIfNeeded();\n this.#timeoutId = undefined;\n }\n get #isIntervalPaused() {\n const now = Date.now();\n if (this.#intervalId === undefined) {\n const delay = this.#intervalEnd - now;\n if (delay < 0) {\n // Act as the interval was done\n // We don't need to resume it here because it will be resumed on line 160\n this.#intervalCount = (this.#carryoverConcurrencyCount) ? this.#pending : 0;\n }\n else {\n // Act as the interval is pending\n if (this.#timeoutId === undefined) {\n this.#timeoutId = setTimeout(() => {\n this.#onResumeInterval();\n }, delay);\n }\n return true;\n }\n }\n return false;\n }\n #tryToStartAnother() {\n if (this.#queue.size === 0) {\n // We can clear the interval (\"pause\")\n // Because we can redo it later (\"resume\")\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n this.#intervalId = undefined;\n this.emit('empty');\n if (this.#pending === 0) {\n this.emit('idle');\n }\n return false;\n }\n if (!this.#isPaused) {\n const canInitializeInterval = !this.#isIntervalPaused;\n if (this.#doesIntervalAllowAnother && this.#doesConcurrentAllowAnother) {\n const job = this.#queue.dequeue();\n if (!job) {\n return false;\n }\n this.emit('active');\n job();\n if (canInitializeInterval) {\n this.#initializeIntervalIfNeeded();\n }\n return true;\n }\n }\n return false;\n }\n #initializeIntervalIfNeeded() {\n if (this.#isIntervalIgnored || this.#intervalId !== undefined) {\n return;\n }\n this.#intervalId = setInterval(() => {\n this.#onInterval();\n }, this.#interval);\n this.#intervalEnd = Date.now() + this.#interval;\n }\n #onInterval() {\n if (this.#intervalCount === 0 && this.#pending === 0 && this.#intervalId) {\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n }\n this.#intervalCount = this.#carryoverConcurrencyCount ? this.#pending : 0;\n this.#processQueue();\n }\n /**\n Executes all queued functions until it reaches the limit.\n */\n #processQueue() {\n // eslint-disable-next-line no-empty\n while (this.#tryToStartAnother()) { }\n }\n get concurrency() {\n return this.#concurrency;\n }\n set concurrency(newConcurrency) {\n if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) {\n throw new TypeError(`Expected \\`concurrency\\` to be a number from 1 and up, got \\`${newConcurrency}\\` (${typeof newConcurrency})`);\n }\n this.#concurrency = newConcurrency;\n this.#processQueue();\n }\n async #throwOnAbort(signal) {\n return new Promise((_resolve, reject) => {\n signal.addEventListener('abort', () => {\n reject(signal.reason);\n }, { once: true });\n });\n }\n async add(function_, options = {}) {\n options = {\n timeout: this.timeout,\n throwOnTimeout: this.#throwOnTimeout,\n ...options,\n };\n return new Promise((resolve, reject) => {\n this.#queue.enqueue(async () => {\n this.#pending++;\n this.#intervalCount++;\n try {\n options.signal?.throwIfAborted();\n let operation = function_({ signal: options.signal });\n if (options.timeout) {\n operation = (0,p_timeout__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(Promise.resolve(operation), { milliseconds: options.timeout });\n }\n if (options.signal) {\n operation = Promise.race([operation, this.#throwOnAbort(options.signal)]);\n }\n const result = await operation;\n resolve(result);\n this.emit('completed', result);\n }\n catch (error) {\n if (error instanceof p_timeout__WEBPACK_IMPORTED_MODULE_2__.TimeoutError && !options.throwOnTimeout) {\n resolve();\n return;\n }\n reject(error);\n this.emit('error', error);\n }\n finally {\n this.#next();\n }\n }, options);\n this.emit('add');\n this.#tryToStartAnother();\n });\n }\n async addAll(functions, options) {\n return Promise.all(functions.map(async (function_) => this.add(function_, options)));\n }\n /**\n Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.)\n */\n start() {\n if (!this.#isPaused) {\n return this;\n }\n this.#isPaused = false;\n this.#processQueue();\n return this;\n }\n /**\n Put queue execution on hold.\n */\n pause() {\n this.#isPaused = true;\n }\n /**\n Clear the queue.\n */\n clear() {\n this.#queue = new this.#queueClass();\n }\n /**\n Can be called multiple times. Useful if you for example add additional items at a later time.\n\n @returns A promise that settles when the queue becomes empty.\n */\n async onEmpty() {\n // Instantly resolve if the queue is empty\n if (this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('empty');\n }\n /**\n @returns A promise that settles when the queue size is less than the given limit: `queue.size < limit`.\n\n If you want to avoid having the queue grow beyond a certain size you can `await queue.onSizeLessThan()` before adding a new item.\n\n Note that this only limits the number of items waiting to start. There could still be up to `concurrency` jobs already running that this call does not include in its calculation.\n */\n async onSizeLessThan(limit) {\n // Instantly resolve if the queue is empty.\n if (this.#queue.size < limit) {\n return;\n }\n await this.#onEvent('next', () => this.#queue.size < limit);\n }\n /**\n The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet.\n\n @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`.\n */\n async onIdle() {\n // Instantly resolve if none pending and if nothing else is queued\n if (this.#pending === 0 && this.#queue.size === 0) {\n return;\n }\n await this.#onEvent('idle');\n }\n async #onEvent(event, filter) {\n return new Promise(resolve => {\n const listener = () => {\n if (filter && !filter()) {\n return;\n }\n this.off(event, listener);\n resolve();\n };\n this.on(event, listener);\n });\n }\n /**\n Size of the queue, the number of queued items waiting to run.\n */\n get size() {\n return this.#queue.size;\n }\n /**\n Size of the queue, filtered by the given options.\n\n For example, this can be used to find the number of items remaining in the queue with a specific priority level.\n */\n sizeBy(options) {\n // eslint-disable-next-line unicorn/no-array-callback-reference\n return this.#queue.filter(options).length;\n }\n /**\n Number of running items (no longer in the queue).\n */\n get pending() {\n return this.#pending;\n }\n /**\n Whether the queue is currently paused.\n */\n get isPaused() {\n return this.#isPaused;\n }\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/p-queue/dist/index.js?"); /***/ }), @@ -15000,7 +19718,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ TimeoutError: () => (/* binding */ TimeoutError),\n/* harmony export */ \"default\": () => (/* binding */ pTimeout)\n/* harmony export */ });\nclass TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nfunction pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tsignal.addEventListener('abort', () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/p-timeout/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ TimeoutError: () => (/* binding */ TimeoutError),\n/* harmony export */ \"default\": () => (/* binding */ pTimeout)\n/* harmony export */ });\nclass TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nclass AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nfunction pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/p-timeout/index.js?"); /***/ }), @@ -15011,7 +19729,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomProgressEvent: () => (/* binding */ CustomProgressEvent)\n/* harmony export */ });\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nclass CustomProgressEvent extends Event {\n constructor(type, detail) {\n super(type);\n this.detail = detail;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/progress-events/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CustomProgressEvent: () => (/* binding */ CustomProgressEvent)\n/* harmony export */ });\n/**\n * An implementation of the ProgressEvent interface, this is essentially\n * a typed `CustomEvent` with a `type` property that lets us disambiguate\n * events passed to `progress` callbacks.\n */\nclass CustomProgressEvent extends Event {\n type;\n detail;\n constructor(type, detail) {\n super(type);\n this.type = type;\n // @ts-expect-error detail may be undefined\n this.detail = detail;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/progress-events/dist/src/index.js?"); /***/ }), @@ -15077,7 +19795,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ decodeMessage: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_0__.decodeMessage),\n/* harmony export */ encodeMessage: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_1__.encodeMessage),\n/* harmony export */ enumeration: () => (/* reexport safe */ _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__.enumeration),\n/* harmony export */ message: () => (/* reexport safe */ _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__.message),\n/* harmony export */ reader: () => (/* reexport safe */ _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__.createReader),\n/* harmony export */ writer: () => (/* reexport safe */ _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__.createWriter)\n/* harmony export */ });\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/protons-runtime/dist/src/decode.js\");\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/protons-runtime/dist/src/encode.js\");\n/* harmony import */ var _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/enum.js */ \"./node_modules/protons-runtime/dist/src/codecs/enum.js\");\n/* harmony import */ var _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./codecs/message.js */ \"./node_modules/protons-runtime/dist/src/codecs/message.js\");\n/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/reader.js */ \"./node_modules/protons-runtime/dist/src/utils/reader.js\");\n/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/writer.js */ \"./node_modules/protons-runtime/dist/src/utils/writer.js\");\n/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\n\n\n\n\n\nclass CodeError extends Error {\n code;\n constructor(message, code, options) {\n super(message, options);\n this.code = code;\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CodeError: () => (/* binding */ CodeError),\n/* harmony export */ MaxLengthError: () => (/* binding */ MaxLengthError),\n/* harmony export */ MaxSizeError: () => (/* binding */ MaxSizeError),\n/* harmony export */ NoMessagesFoundError: () => (/* binding */ NoMessagesFoundError),\n/* harmony export */ ParseError: () => (/* binding */ ParseError),\n/* harmony export */ decodeMessage: () => (/* reexport safe */ _decode_js__WEBPACK_IMPORTED_MODULE_0__.decodeMessage),\n/* harmony export */ encodeMessage: () => (/* reexport safe */ _encode_js__WEBPACK_IMPORTED_MODULE_1__.encodeMessage),\n/* harmony export */ enumeration: () => (/* reexport safe */ _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__.enumeration),\n/* harmony export */ message: () => (/* reexport safe */ _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__.message),\n/* harmony export */ reader: () => (/* reexport safe */ _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__.createReader),\n/* harmony export */ writer: () => (/* reexport safe */ _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__.createWriter)\n/* harmony export */ });\n/* harmony import */ var _decode_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./decode.js */ \"./node_modules/protons-runtime/dist/src/decode.js\");\n/* harmony import */ var _encode_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./encode.js */ \"./node_modules/protons-runtime/dist/src/encode.js\");\n/* harmony import */ var _codecs_enum_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./codecs/enum.js */ \"./node_modules/protons-runtime/dist/src/codecs/enum.js\");\n/* harmony import */ var _codecs_message_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./codecs/message.js */ \"./node_modules/protons-runtime/dist/src/codecs/message.js\");\n/* harmony import */ var _utils_reader_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/reader.js */ \"./node_modules/protons-runtime/dist/src/utils/reader.js\");\n/* harmony import */ var _utils_writer_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/writer.js */ \"./node_modules/protons-runtime/dist/src/utils/writer.js\");\n/**\n * @packageDocumentation\n *\n * This module contains serialization/deserialization code used when encoding/decoding protobufs.\n *\n * It should be declared as a dependency of your project:\n *\n * ```console\n * npm i protons-runtime\n * ```\n */\n\n\n\n\n\n\n/**\n * This will be removed in a future release\n *\n * @deprecated\n */\nclass CodeError extends Error {\n code;\n constructor(message, code) {\n super(message);\n this.code = code;\n }\n}\n/**\n * Thrown when a repeated field has too many elements\n */\nclass MaxLengthError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_LENGTH';\n name = 'MaxLengthError';\n}\n/**\n * Thrown when a map has too many elements\n */\nclass MaxSizeError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_MAX_SIZE';\n name = 'MaxSizeError';\n}\nclass ParseError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_PARSE_ERROR';\n name = 'ParseError';\n}\nclass NoMessagesFoundError extends Error {\n /**\n * This will be removed in a future release\n *\n * @deprecated use the `.name` property instead\n */\n code = 'ERR_NO_MESSAGES_FOUND';\n name = 'NoMessagesFoundError';\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/dist/src/index.js?"); /***/ }), @@ -15154,7 +19872,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefix.codePointAt(0);\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Codec: () => (/* binding */ Codec),\n/* harmony export */ baseX: () => (/* binding */ baseX),\n/* harmony export */ from: () => (/* binding */ from),\n/* harmony export */ or: () => (/* binding */ or),\n/* harmony export */ rfc4648: () => (/* binding */ rfc4648)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../vendor/base-x.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/vendor/base-x.js\");\n\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder {\n name;\n prefix;\n baseEncode;\n constructor(name, prefix, baseEncode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n }\n encode(bytes) {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`;\n }\n else {\n throw Error('Unknown type, must be binary type');\n }\n }\n}\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder {\n name;\n prefix;\n baseDecode;\n prefixCodePoint;\n constructor(name, prefix, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n const prefixCodePoint = prefix.codePointAt(0);\n /* c8 ignore next 3 */\n if (prefixCodePoint === undefined) {\n throw new Error('Invalid prefix character');\n }\n this.prefixCodePoint = prefixCodePoint;\n this.baseDecode = baseDecode;\n }\n decode(text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);\n }\n return this.baseDecode(text.slice(this.prefix.length));\n }\n else {\n throw Error('Can only multibase decode strings');\n }\n }\n or(decoder) {\n return or(this, decoder);\n }\n}\nclass ComposedDecoder {\n decoders;\n constructor(decoders) {\n this.decoders = decoders;\n }\n or(decoder) {\n return or(this, decoder);\n }\n decode(input) {\n const prefix = input[0];\n const decoder = this.decoders[prefix];\n if (decoder != null) {\n return decoder.decode(input);\n }\n else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);\n }\n }\n}\nfunction or(left, right) {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [left.prefix]: left }),\n ...(right.decoders ?? { [right.prefix]: right })\n });\n}\nclass Codec {\n name;\n prefix;\n baseEncode;\n baseDecode;\n encoder;\n decoder;\n constructor(name, prefix, baseEncode, baseDecode) {\n this.name = name;\n this.prefix = prefix;\n this.baseEncode = baseEncode;\n this.baseDecode = baseDecode;\n this.encoder = new Encoder(name, prefix, baseEncode);\n this.decoder = new Decoder(name, prefix, baseDecode);\n }\n encode(input) {\n return this.encoder.encode(input);\n }\n decode(input) {\n return this.decoder.decode(input);\n }\n}\nfunction from({ name, prefix, encode, decode }) {\n return new Codec(name, prefix, encode, decode);\n}\nfunction baseX({ name, prefix, alphabet }) {\n const { encode, decode } = (0,_vendor_base_x_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])(alphabet, name);\n return from({\n prefix,\n name,\n encode,\n decode: (text) => (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(decode(text))\n });\n}\nfunction decode(string, alphabet, bitsPerChar, name) {\n // Build the character lookup table:\n const codes = {};\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i;\n }\n // Count the padding bytes:\n let end = string.length;\n while (string[end - 1] === '=') {\n --end;\n }\n // Allocate the output:\n const out = new Uint8Array((end * bitsPerChar / 8) | 0);\n // Parse the data:\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n let written = 0; // Next byte to write\n for (let i = 0; i < end; ++i) {\n // Read one character from the string:\n const value = codes[string[i]];\n if (value === undefined) {\n throw new SyntaxError(`Non-${name} character`);\n }\n // Append the bits to the buffer:\n buffer = (buffer << bitsPerChar) | value;\n bits += bitsPerChar;\n // Write out some bits if the buffer has a byte's worth:\n if (bits >= 8) {\n bits -= 8;\n out[written++] = 0xff & (buffer >> bits);\n }\n }\n // Verify that we have received just enough bits:\n if (bits >= bitsPerChar || (0xff & (buffer << (8 - bits))) !== 0) {\n throw new SyntaxError('Unexpected end of data');\n }\n return out;\n}\nfunction encode(data, alphabet, bitsPerChar) {\n const pad = alphabet[alphabet.length - 1] === '=';\n const mask = (1 << bitsPerChar) - 1;\n let out = '';\n let bits = 0; // Number of bits currently in the buffer\n let buffer = 0; // Bits waiting to be written out, MSB first\n for (let i = 0; i < data.length; ++i) {\n // Slurp data into the buffer:\n buffer = (buffer << 8) | data[i];\n bits += 8;\n // Write out as much as we can:\n while (bits > bitsPerChar) {\n bits -= bitsPerChar;\n out += alphabet[mask & (buffer >> bits)];\n }\n }\n // Partial character:\n if (bits !== 0) {\n out += alphabet[mask & (buffer << (bitsPerChar - bits))];\n }\n // Add padding characters until we hit a byte boundary:\n if (pad) {\n while (((out.length * bitsPerChar) & 7) !== 0) {\n out += '=';\n }\n }\n return out;\n}\n/**\n * RFC4648 Factory\n */\nfunction rfc4648({ name, prefix, bitsPerChar, alphabet }) {\n return from({\n prefix,\n name,\n encode(input) {\n return encode(input, alphabet, bitsPerChar);\n },\n decode(input) {\n return decode(input, alphabet, bitsPerChar, name);\n }\n });\n}\n//# sourceMappingURL=base.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base.js?"); /***/ }), @@ -15198,7 +19916,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => { p[c.codePointAt(0)] = i; return p; }, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const byt = alphabetCharsToBytes[char.codePointAt(0)];\n if (byt === undefined) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base256emoji.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ base256emoji: () => (/* binding */ base256emoji)\n/* harmony export */ });\n/* harmony import */ var _base_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base.js\");\n\nconst alphabet = Array.from('🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂');\nconst alphabetBytesToChars = (alphabet.reduce((p, c, i) => { p[i] = c; return p; }, ([])));\nconst alphabetCharsToBytes = (alphabet.reduce((p, c, i) => {\n const codePoint = c.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${c}`);\n }\n p[codePoint] = i;\n return p;\n}, ([])));\nfunction encode(data) {\n return data.reduce((p, c) => {\n p += alphabetBytesToChars[c];\n return p;\n }, '');\n}\nfunction decode(str) {\n const byts = [];\n for (const char of str) {\n const codePoint = char.codePointAt(0);\n if (codePoint == null) {\n throw new Error(`Invalid character: ${char}`);\n }\n const byt = alphabetCharsToBytes[codePoint];\n if (byt == null) {\n throw new Error(`Non-base256emoji character: ${char}`);\n }\n byts.push(byt);\n }\n return new Uint8Array(byts);\n}\nconst base256emoji = (0,_base_js__WEBPACK_IMPORTED_MODULE_0__.from)({\n prefix: '🚀',\n name: 'base256emoji',\n encode,\n decode\n});\n//# sourceMappingURL=base256emoji.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base256emoji.js?"); /***/ }), @@ -15319,7 +20037,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_2__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_3__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_4__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_1__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_4__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/cid.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ CID: () => (/* binding */ CID),\n/* harmony export */ format: () => (/* binding */ format),\n/* harmony export */ fromJSON: () => (/* binding */ fromJSON),\n/* harmony export */ toJSON: () => (/* binding */ toJSON)\n/* harmony export */ });\n/* harmony import */ var _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bases/base32.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base32.js\");\n/* harmony import */ var _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bases/base36.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base36.js\");\n/* harmony import */ var _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./bases/base58.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bases/base58.js\");\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hashes/digest.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/hashes/digest.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./varint.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/varint.js\");\n/* harmony import */ var _link_interface_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./link/interface.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/link/interface.js\");\n\n\n\n\n\n\n// This way TS will also expose all the types from module\n\nfunction format(link, base) {\n const { bytes, version } = link;\n switch (version) {\n case 0:\n return toStringV0(bytes, baseCache(link), base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.encoder);\n default:\n return toStringV1(bytes, baseCache(link), (base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.encoder));\n }\n}\nfunction toJSON(link) {\n return {\n '/': format(link)\n };\n}\nfunction fromJSON(json) {\n return CID.parse(json['/']);\n}\nconst cache = new WeakMap();\nfunction baseCache(cid) {\n const baseCache = cache.get(cid);\n if (baseCache == null) {\n const baseCache = new Map();\n cache.set(cid, baseCache);\n return baseCache;\n }\n return baseCache;\n}\nclass CID {\n code;\n version;\n multihash;\n bytes;\n '/';\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor(version, code, multihash, bytes) {\n this.code = code;\n this.version = version;\n this.multihash = multihash;\n this.bytes = bytes;\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes;\n }\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID() {\n return this;\n }\n // ArrayBufferView\n get byteOffset() {\n return this.bytes.byteOffset;\n }\n // ArrayBufferView\n get byteLength() {\n return this.bytes.byteLength;\n }\n toV0() {\n switch (this.version) {\n case 0: {\n return this;\n }\n case 1: {\n const { code, multihash } = this;\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0');\n }\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0');\n }\n return (CID.createV0(multihash));\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);\n }\n }\n }\n toV1() {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash;\n const multihash = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.create(code, digest);\n return (CID.createV1(this.code, multihash));\n }\n case 1: {\n return this;\n }\n default: {\n throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`);\n }\n }\n }\n equals(other) {\n return CID.equals(this, other);\n }\n static equals(self, other) {\n const unknown = other;\n return (unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.equals(self.multihash, unknown.multihash));\n }\n toString(base) {\n return format(this, base);\n }\n toJSON() {\n return { '/': format(this) };\n }\n link() {\n return this;\n }\n [Symbol.toStringTag] = 'CID';\n // Legacy\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `CID(${this.toString()})`;\n }\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID(input) {\n if (input == null) {\n return null;\n }\n const value = input;\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value;\n }\n else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value;\n return new CID(version, code, multihash, bytes ?? encodeCID(version, code, multihash.bytes));\n }\n else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value;\n const digest = _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.decode(multihash);\n return CID.create(version, code, digest);\n }\n else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null;\n }\n }\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create(version, code, digest) {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported');\n }\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest');\n }\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);\n }\n else {\n return new CID(version, code, digest, digest.bytes);\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes);\n return new CID(version, code, digest, bytes);\n }\n default: {\n throw new Error('Invalid version');\n }\n }\n }\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0(digest) {\n return CID.create(0, DAG_PB_CODE, digest);\n }\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1(code, digest) {\n return CID.create(1, code, digest);\n }\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode(bytes) {\n const [cid, remainder] = CID.decodeFirst(bytes);\n if (remainder.length !== 0) {\n throw new Error('Incorrect length');\n }\n return cid;\n }\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst(bytes) {\n const specs = CID.inspectBytes(bytes);\n const prefixSize = specs.size - specs.multihashSize;\n const multihashBytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_3__.coerce)(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length');\n }\n const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);\n const digest = new _hashes_digest_js__WEBPACK_IMPORTED_MODULE_4__.Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);\n const cid = specs.version === 0\n ? CID.createV0(digest)\n : CID.createV1(specs.codec, digest);\n return [cid, bytes.subarray(specs.size)];\n }\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes(initialBytes) {\n let offset = 0;\n const next = () => {\n const [i, length] = _varint_js__WEBPACK_IMPORTED_MODULE_5__.decode(initialBytes.subarray(offset));\n offset += length;\n return i;\n };\n let version = next();\n let codec = DAG_PB_CODE;\n if (version === 18) {\n // CIDv0\n version = 0;\n offset = 0;\n }\n else {\n codec = next();\n }\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`);\n }\n const prefixSize = offset;\n const multihashCode = next(); // multihash code\n const digestSize = next(); // multihash length\n const size = offset + digestSize;\n const multihashSize = size - prefixSize;\n return { version, codec, multihashCode, digestSize, multihashSize, size };\n }\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse(source, base) {\n const [prefix, bytes] = parseCIDtoBytes(source, base);\n const cid = CID.decode(bytes);\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix');\n }\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source);\n return cid;\n }\n}\nfunction parseCIDtoBytes(source, base) {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [\n _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix,\n decoder.decode(`${_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix}${source}`)\n ];\n }\n case _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix: {\n const decoder = base ?? _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc;\n return [_bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix, decoder.decode(source)];\n }\n case _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix: {\n const decoder = base ?? _bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32;\n return [_bases_base32_js__WEBPACK_IMPORTED_MODULE_0__.base32.prefix, decoder.decode(source)];\n }\n case _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix: {\n const decoder = base ?? _bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36;\n return [_bases_base36_js__WEBPACK_IMPORTED_MODULE_1__.base36.prefix, decoder.decode(source)];\n }\n default: {\n if (base == null) {\n throw Error('To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided');\n }\n return [source[0], base.decode(source)];\n }\n }\n}\nfunction toStringV0(bytes, cache, base) {\n const { prefix } = base;\n if (prefix !== _bases_base58_js__WEBPACK_IMPORTED_MODULE_2__.base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`);\n }\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes).slice(1);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nfunction toStringV1(bytes, cache, base) {\n const { prefix } = base;\n const cid = cache.get(prefix);\n if (cid == null) {\n const cid = base.encode(bytes);\n cache.set(prefix, cid);\n return cid;\n }\n else {\n return cid;\n }\n}\nconst DAG_PB_CODE = 0x70;\nconst SHA_256_CODE = 0x12;\nfunction encodeCID(version, code, multihash) {\n const codeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(version);\n const hashOffset = codeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodingLength(code);\n const bytes = new Uint8Array(hashOffset + multihash.byteLength);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(version, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_5__.encodeTo(code, bytes, codeOffset);\n bytes.set(multihash, hashOffset);\n return bytes;\n}\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID');\n//# sourceMappingURL=cid.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/cid.js?"); /***/ }), @@ -15363,7 +20081,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/hashes/digest.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ Digest: () => (/* binding */ Digest),\n/* harmony export */ create: () => (/* binding */ create),\n/* harmony export */ decode: () => (/* binding */ decode),\n/* harmony export */ equals: () => (/* binding */ equals),\n/* harmony export */ hasCode: () => (/* binding */ hasCode)\n/* harmony export */ });\n/* harmony import */ var _bytes_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../bytes.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/bytes.js\");\n/* harmony import */ var _varint_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../varint.js */ \"./node_modules/protons-runtime/node_modules/multiformats/dist/src/varint.js\");\n\n\n/**\n * Creates a multihash digest.\n */\nfunction create(code, digest) {\n const size = digest.byteLength;\n const sizeOffset = _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(code);\n const digestOffset = sizeOffset + _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodingLength(size);\n const bytes = new Uint8Array(digestOffset + size);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(code, bytes, 0);\n _varint_js__WEBPACK_IMPORTED_MODULE_1__.encodeTo(size, bytes, sizeOffset);\n bytes.set(digest, digestOffset);\n return new Digest(code, size, digest, bytes);\n}\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nfunction decode(multihash) {\n const bytes = (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.coerce)(multihash);\n const [code, sizeOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes);\n const [size, digestOffset] = _varint_js__WEBPACK_IMPORTED_MODULE_1__.decode(bytes.subarray(sizeOffset));\n const digest = bytes.subarray(sizeOffset + digestOffset);\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length');\n }\n return new Digest(code, size, digest, bytes);\n}\nfunction equals(a, b) {\n if (a === b) {\n return true;\n }\n else {\n const data = b;\n return (a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n (0,_bytes_js__WEBPACK_IMPORTED_MODULE_0__.equals)(a.bytes, data.bytes));\n }\n}\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nclass Digest {\n code;\n size;\n digest;\n bytes;\n /**\n * Creates a multihash digest.\n */\n constructor(code, size, digest, bytes) {\n this.code = code;\n this.size = size;\n this.digest = digest;\n this.bytes = bytes;\n }\n}\n/**\n * Used to check that the passed multihash has the passed code\n */\nfunction hasCode(digest, code) {\n return digest.code === code;\n}\n//# sourceMappingURL=digest.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/protons-runtime/node_modules/multiformats/dist/src/hashes/digest.js?"); /***/ }), @@ -15517,7 +20235,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ raceEvent: () => (/* binding */ raceEvent)\n/* harmony export */ });\n/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n/**\n * An abort error class that extends error\n */\nclass AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nasync function raceEvent(emitter, eventName, signal, opts) {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n if (signal?.aborted === true) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n const eventListener = (evt) => {\n try {\n if (opts?.filter?.(evt) === false) {\n return;\n }\n }\n catch (err) {\n emitter.removeEventListener(eventName, eventListener);\n signal?.removeEventListener('abort', abortListener);\n reject(err);\n return;\n }\n emitter.removeEventListener(eventName, eventListener);\n signal?.removeEventListener('abort', abortListener);\n resolve(evt);\n };\n const abortListener = () => {\n emitter.removeEventListener(eventName, eventListener);\n signal?.removeEventListener('abort', abortListener);\n reject(error);\n };\n emitter.addEventListener(eventName, eventListener);\n signal?.addEventListener('abort', abortListener);\n });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/race-event/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ raceEvent: () => (/* binding */ raceEvent)\n/* harmony export */ });\n/**\n * @packageDocumentation\n *\n * Race an event against an AbortSignal, taking care to remove any event\n * listeners that were added.\n *\n * @example Getting started\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * setTimeout(() => {\n * // too late\n * emitter.dispatchEvent(new CustomEvent('event'))\n * }, 1000)\n *\n * // throws an AbortError\n * const resolve = await raceEvent(emitter, 'event', controller.signal)\n * ```\n *\n * @example Aborting the promise with an error event\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * emitter.dispatchEvent(new CustomEvent('failure', {\n * detail: new Error('Oh no!')\n * }))\n * }, 1000)\n *\n * // throws 'Oh no!' error\n * const resolve = await raceEvent(emitter, 'success', AbortSignal.timeout(5000), {\n * errorEvent: 'failure'\n * })\n * ```\n *\n * @example Customising the thrown AbortError\n *\n * The error message and `.code` property of the thrown `AbortError` can be\n * specified by passing options:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * setTimeout(() => {\n * controller.abort()\n * }, 500)\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * errorMessage: 'Oh no!',\n * errorCode: 'ERR_OH_NO'\n * })\n * ```\n *\n * @example Only resolving on specific events\n *\n * Where multiple events with the same type are emitted, a `filter` function can\n * be passed to only resolve on one of them:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws a Error: Oh no!\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt: Event) => {\n * return evt.detail.foo === 'bar'\n * }\n * })\n * ```\n *\n * @example Terminating early by throwing from the filter\n *\n * You can cause listening for the event to cease and all event listeners to be\n * removed by throwing from the filter:\n *\n * ```TypeScript\n * import { raceEvent } from 'race-event'\n *\n * const controller = new AbortController()\n * const emitter = new EventTarget()\n *\n * // throws Error: Cannot continue\n * const resolve = await raceEvent(emitter, 'event', controller.signal, {\n * filter: (evt) => {\n * if (...reasons) {\n * throw new Error('Cannot continue')\n * }\n *\n * return true\n * }\n * })\n * ```\n */\n/**\n * An abort error class that extends error\n */\nclass AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nasync function raceEvent(emitter, eventName, signal, opts) {\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n if (signal?.aborted === true) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n function removeListeners() {\n signal?.removeEventListener('abort', abortListener);\n emitter.removeEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.removeEventListener(opts.errorEvent, errorEventListener);\n }\n }\n const eventListener = (evt) => {\n try {\n if (opts?.filter?.(evt) === false) {\n return;\n }\n }\n catch (err) {\n removeListeners();\n reject(err);\n return;\n }\n removeListeners();\n resolve(evt);\n };\n const errorEventListener = (evt) => {\n removeListeners();\n reject(evt.detail);\n };\n const abortListener = () => {\n removeListeners();\n reject(error);\n };\n signal?.addEventListener('abort', abortListener);\n emitter.addEventListener(eventName, eventListener);\n if (opts?.errorEvent != null) {\n emitter.addEventListener(opts.errorEvent, errorEventListener);\n }\n });\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/race-event/dist/src/index.js?"); /***/ }), @@ -15528,7 +20246,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ raceSignal: () => (/* binding */ raceSignal)\n/* harmony export */ });\n/**\n * An abort error class that extends error\n */\nclass AbortError extends Error {\n type;\n code;\n constructor(message, code) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nasync function raceSignal(promise, signal, opts) {\n if (signal == null) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode));\n }\n let listener;\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode);\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error);\n };\n signal.addEventListener('abort', listener);\n })\n ]);\n }\n finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/race-signal/dist/src/index.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ AbortError: () => (/* binding */ AbortError),\n/* harmony export */ raceSignal: () => (/* binding */ raceSignal)\n/* harmony export */ });\n/**\n * An abort error class that extends error\n */\nclass AbortError extends Error {\n type;\n code;\n constructor(message, code, name) {\n super(message ?? 'The operation was aborted');\n this.type = 'aborted';\n this.name = name ?? 'AbortError';\n this.code = code ?? 'ABORT_ERR';\n }\n}\n/**\n * Race a promise against an abort signal\n */\nasync function raceSignal(promise, signal, opts) {\n if (signal == null) {\n return promise;\n }\n if (signal.aborted) {\n return Promise.reject(new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName));\n }\n let listener;\n // create the error here so we have more context in the stack trace\n const error = new AbortError(opts?.errorMessage, opts?.errorCode, opts?.errorName);\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject) => {\n listener = () => {\n reject(error);\n };\n signal.addEventListener('abort', listener);\n })\n ]);\n }\n finally {\n if (listener != null) {\n signal.removeEventListener('abort', listener);\n }\n }\n}\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/race-signal/dist/src/index.js?"); /***/ }), @@ -15994,6 +20712,50 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /***/ }), +/***/ "./node_modules/weald/dist/src/browser.js": +/*!************************************************!*\ + !*** ./node_modules/weald/dist/src/browser.js ***! + \************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var ms__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ms */ \"./node_modules/weald/node_modules/ms/dist/index.mjs\");\n/* harmony import */ var _common_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./common.js */ \"./node_modules/weald/dist/src/common.js\");\n/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/restrict-plus-operands */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/* eslint-env browser */\n/**\n * This is the web browser implementation of `debug()`.\n */\n\n\nconst storage = localstorage();\n/**\n * Colors.\n */\nconst colors = [\n '#0000CC',\n '#0000FF',\n '#0033CC',\n '#0033FF',\n '#0066CC',\n '#0066FF',\n '#0099CC',\n '#0099FF',\n '#00CC00',\n '#00CC33',\n '#00CC66',\n '#00CC99',\n '#00CCCC',\n '#00CCFF',\n '#3300CC',\n '#3300FF',\n '#3333CC',\n '#3333FF',\n '#3366CC',\n '#3366FF',\n '#3399CC',\n '#3399FF',\n '#33CC00',\n '#33CC33',\n '#33CC66',\n '#33CC99',\n '#33CCCC',\n '#33CCFF',\n '#6600CC',\n '#6600FF',\n '#6633CC',\n '#6633FF',\n '#66CC00',\n '#66CC33',\n '#9900CC',\n '#9900FF',\n '#9933CC',\n '#9933FF',\n '#99CC00',\n '#99CC33',\n '#CC0000',\n '#CC0033',\n '#CC0066',\n '#CC0099',\n '#CC00CC',\n '#CC00FF',\n '#CC3300',\n '#CC3333',\n '#CC3366',\n '#CC3399',\n '#CC33CC',\n '#CC33FF',\n '#CC6600',\n '#CC6633',\n '#CC9900',\n '#CC9933',\n '#CCCC00',\n '#CCCC33',\n '#FF0000',\n '#FF0033',\n '#FF0066',\n '#FF0099',\n '#FF00CC',\n '#FF00FF',\n '#FF3300',\n '#FF3333',\n '#FF3366',\n '#FF3399',\n '#FF33CC',\n '#FF33FF',\n '#FF6600',\n '#FF6633',\n '#FF9900',\n '#FF9933',\n '#FFCC00',\n '#FFCC33'\n];\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n// eslint-disable-next-line complexity\nfunction useColors() {\n // NB: In an Electron preload script, document will be defined but not fully\n // initialized. Since we know we're in Chrome, we'll just detect this case\n // explicitly\n // @ts-expect-error window.process.type and window.process.__nwjs are not in the types\n if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n return true;\n }\n // Internet Explorer and Edge do not support colors.\n if (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/(edge|trident)\\/(\\d+)/) != null)) {\n return false;\n }\n // Is webkit? http://stackoverflow.com/a/16459606/376773\n // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n // @ts-expect-error document.documentElement.style.WebkitAppearance is not in the types\n return (typeof document !== 'undefined' && document.documentElement?.style?.WebkitAppearance) ||\n // Is firebug? http://stackoverflow.com/a/398120/376773\n // @ts-expect-error window.console.firebug and window.console.exception are not in the types\n (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n // Is firefox >= v31?\n // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n (typeof navigator !== 'undefined' && (navigator.userAgent?.toLowerCase().match(/firefox\\/(\\d+)/) != null) && parseInt(RegExp.$1, 10) >= 31) ||\n // Double check webkit in userAgent just in case we are in a worker\n (typeof navigator !== 'undefined' && navigator.userAgent?.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n/**\n * Colorize log arguments if enabled.\n */\nfunction formatArgs(args) {\n args[0] = (this.useColors ? '%c' : '') +\n this.namespace +\n (this.useColors ? ' %c' : ' ') +\n args[0] +\n (this.useColors ? '%c ' : ' ') +\n '+' + (0,ms__WEBPACK_IMPORTED_MODULE_0__[\"default\"])(this.diff);\n if (!this.useColors) {\n return;\n }\n const c = 'color: ' + this.color;\n args.splice(1, 0, c, 'color: inherit');\n // The final \"%c\" is somewhat tricky, because there could be other\n // arguments passed either before or after the %c, so we need to\n // figure out the correct index to insert the CSS into\n let index = 0;\n let lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, (match) => {\n if (match === '%%') {\n return;\n }\n index++;\n if (match === '%c') {\n // We only are interested in the *last* %c\n // (the user may have provided their own)\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n}\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n */\nconst log = console.debug ?? console.log ?? (() => { });\n/**\n * Save `namespaces`.\n *\n * @param {string} namespaces\n */\nfunction save(namespaces) {\n try {\n if (namespaces) {\n storage?.setItem('debug', namespaces);\n }\n else {\n storage?.removeItem('debug');\n }\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\n/**\n * Load `namespaces`.\n *\n * @returns {string} returns the previously persisted debug modes\n */\nfunction load() {\n let r;\n try {\n r = storage?.getItem('debug');\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n // If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n if (!r && typeof globalThis.process !== 'undefined' && 'env' in globalThis.process) {\n r = globalThis.process.env.DEBUG;\n }\n return r;\n}\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n */\nfunction localstorage() {\n try {\n // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n // The Browser also has localStorage in the global context.\n return localStorage;\n }\n catch (error) {\n // Swallow\n // XXX (@Qix-) should we be logging these?\n }\n}\nfunction setupFormatters(formatters) {\n /**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n formatters.j = function (v) {\n try {\n return JSON.stringify(v);\n }\n catch (error) {\n return '[UnexpectedJSONParseError]: ' + error.message;\n }\n };\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((0,_common_js__WEBPACK_IMPORTED_MODULE_1__[\"default\"])({ formatArgs, save, load, useColors, setupFormatters, colors, storage, log }));\n//# sourceMappingURL=browser.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/weald/dist/src/browser.js?"); + +/***/ }), + +/***/ "./node_modules/weald/dist/src/common.js": +/*!***********************************************!*\ + !*** ./node_modules/weald/dist/src/common.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ setup)\n/* harmony export */ });\n/* harmony import */ var ms__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ms */ \"./node_modules/weald/node_modules/ms/dist/index.mjs\");\n/* eslint-disable no-console */\n/* eslint-disable @typescript-eslint/strict-boolean-expressions */\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n createDebug.debug = createDebug;\n createDebug.default = createDebug;\n createDebug.coerce = coerce;\n createDebug.disable = disable;\n createDebug.enable = enable;\n createDebug.enabled = enabled;\n createDebug.humanize = ms__WEBPACK_IMPORTED_MODULE_0__[\"default\"];\n createDebug.destroy = destroy;\n Object.keys(env).forEach(key => {\n // @ts-expect-error cannot use string to index type\n createDebug[key] = env[key];\n });\n /**\n * The currently active debug mode names, and names to skip.\n */\n createDebug.names = [];\n createDebug.skips = [];\n /**\n * Map of special \"%n\" handling functions, for the debug \"format\" argument.\n *\n * Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n */\n createDebug.formatters = {};\n /**\n * Selects a color for a debug namespace\n *\n * @param {string} namespace - The namespace string for the debug instance to be colored\n * @returns {number | string} An ANSI color code for the given namespace\n */\n function selectColor(namespace) {\n let hash = 0;\n for (let i = 0; i < namespace.length; i++) {\n hash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n hash |= 0; // Convert to 32bit integer\n }\n // @ts-expect-error colors is not in the types\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n }\n createDebug.selectColor = selectColor;\n /**\n * Create a debugger with the given `namespace`.\n *\n * @param {string} namespace\n * @returns {Function}\n */\n function createDebug(namespace) {\n let prevTime;\n let enableOverride = null;\n let namespacesCache;\n let enabledCache;\n function debug(...args) {\n // Disabled?\n // @ts-expect-error enabled is not in the types\n if (!debug.enabled) {\n return;\n }\n const self = debug;\n // Set `diff` timestamp\n const curr = Number(new Date());\n const ms = curr - (prevTime || curr);\n self.diff = ms;\n self.prev = prevTime;\n self.curr = curr;\n prevTime = curr;\n args[0] = createDebug.coerce(args[0]);\n if (typeof args[0] !== 'string') {\n // Anything else let's inspect with %O\n args.unshift('%O');\n }\n // Apply any `formatters` transformations\n let index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n // If we encounter an escaped % then don't increase the array index\n if (match === '%%') {\n return '%';\n }\n index++;\n // @ts-expect-error formatters is not in the types\n const formatter = createDebug.formatters[format];\n if (typeof formatter === 'function') {\n const val = args[index];\n match = formatter.call(self, val);\n // Now we need to remove `args[index]` since it's inlined in the `format`\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n // Apply env-specific formatting (colors, etc.)\n // @ts-expect-error formatArgs is not in the types\n createDebug.formatArgs.call(self, args);\n // @ts-expect-error log is not in the types\n const logFn = self.log || createDebug.log;\n logFn.apply(self, args);\n }\n debug.namespace = namespace;\n // @ts-expect-error useColors is not in the types\n debug.useColors = createDebug.useColors();\n debug.color = createDebug.selectColor(namespace);\n debug.extend = extend;\n debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n Object.defineProperty(debug, 'enabled', {\n enumerable: true,\n configurable: false,\n get: () => {\n if (enableOverride !== null) {\n return enableOverride;\n }\n // @ts-expect-error namespaces is not in the types\n if (namespacesCache !== createDebug.namespaces) {\n // @ts-expect-error namespaces is not in the types\n namespacesCache = createDebug.namespaces;\n enabledCache = createDebug.enabled(namespace);\n }\n return enabledCache;\n },\n set: v => {\n enableOverride = v;\n }\n });\n // Env-specific initialization logic for debug instances\n // @ts-expect-error init is not in the types\n if (typeof createDebug.init === 'function') {\n // @ts-expect-error init is not in the types\n createDebug.init(debug);\n }\n // @ts-expect-error some properties are added dynamically\n return debug;\n }\n function extend(namespace, delimiter) {\n const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n newDebug.log = this.log;\n return newDebug;\n }\n /**\n * Enables a debug mode by namespaces. This can include modes\n * separated by a colon and wildcards.\n *\n * @param {string} namespaces\n */\n function enable(namespaces) {\n // @ts-expect-error save is not in the types\n createDebug.save(namespaces);\n // @ts-expect-error namespaces is not in the types\n createDebug.namespaces = namespaces;\n createDebug.names = [];\n createDebug.skips = [];\n let i;\n const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n const len = split.length;\n for (i = 0; i < len; i++) {\n if (!split[i]) {\n // ignore empty strings\n continue;\n }\n namespaces = split[i].replace(/\\*/g, '.*?');\n if (namespaces[0] === '-') {\n createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n }\n else {\n createDebug.names.push(new RegExp('^' + namespaces + '$'));\n }\n }\n }\n /**\n * Disable debug output.\n *\n * @returns {string} namespaces\n */\n function disable() {\n const namespaces = [\n ...createDebug.names.map(toNamespace),\n ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n ].join(',');\n createDebug.enable('');\n return namespaces;\n }\n /**\n * Returns true if the given mode name is enabled, false otherwise.\n *\n * @param {string} name\n * @returns {boolean}\n */\n function enabled(name) {\n if (name[name.length - 1] === '*') {\n return true;\n }\n let i;\n let len;\n for (i = 0, len = createDebug.skips.length; i < len; i++) {\n if (createDebug.skips[i].test(name)) {\n return false;\n }\n }\n for (i = 0, len = createDebug.names.length; i < len; i++) {\n if (createDebug.names[i].test(name)) {\n return true;\n }\n }\n return false;\n }\n /**\n * Convert regexp to namespace\n */\n function toNamespace(regexp) {\n return regexp.toString()\n .substring(2, regexp.toString().length - 2)\n .replace(/\\.\\*\\?$/, '*');\n }\n /**\n * Coerce `val`.\n */\n function coerce(val) {\n if (val instanceof Error) {\n return val.stack ?? val.message;\n }\n return val;\n }\n /**\n * XXX DO NOT USE. This is a temporary stub function.\n * XXX It WILL be removed in the next major release.\n */\n function destroy() {\n console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n }\n // @ts-expect-error setupFormatters is not in the types\n createDebug.setupFormatters(createDebug.formatters);\n // @ts-expect-error load is not in the types\n createDebug.enable(createDebug.load());\n // @ts-expect-error some properties are added dynamically\n return createDebug;\n}\n//# sourceMappingURL=common.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/weald/dist/src/common.js?"); + +/***/ }), + +/***/ "./node_modules/weald/dist/src/index.js": +/*!**********************************************!*\ + !*** ./node_modules/weald/dist/src/index.js ***! + \**********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _node_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node.js */ \"./node_modules/weald/dist/src/browser.js\");\n/**\n * @packageDocumentation\n *\n * This module is a fork of the [debug](https://www.npmjs.com/package/debug) module. It has been converted to TypeScript and the output is ESM.\n *\n * It is API compatible with no extra features or bug fixes, it should only be used if you want a 100% ESM application.\n *\n * ESM should be arriving in `debug@5.x.x` so this module can be retired after that.\n *\n * Please see [debug](https://www.npmjs.com/package/debug) for API details.\n */\n/**\n * Module dependencies.\n */\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_js__WEBPACK_IMPORTED_MODULE_0__[\"default\"]);\n//# sourceMappingURL=index.js.map\n\n//# sourceURL=webpack://rln-chat/./node_modules/weald/dist/src/index.js?"); + +/***/ }), + +/***/ "./node_modules/weald/node_modules/ms/dist/index.mjs": +/*!***********************************************************!*\ + !*** ./node_modules/weald/node_modules/ms/dist/index.mjs ***! + \***********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n// Helpers.\nconst s = 1000;\nconst m = s * 60;\nconst h = m * 60;\nconst d = h * 24;\nconst w = d * 7;\nconst y = d * 365.25;\nfunction ms(value, options) {\n try {\n if (typeof value === 'string' && value.length > 0) {\n return parse(value);\n }\n else if (typeof value === 'number' && isFinite(value)) {\n return options?.long ? fmtLong(value) : fmtShort(value);\n }\n throw new Error('Value is not a string or number.');\n }\n catch (error) {\n const message = isError(error)\n ? `${error.message}. value=${JSON.stringify(value)}`\n : 'An unknown error has occured.';\n throw new Error(message);\n }\n}\n/**\n * Parse the given `str` and return milliseconds.\n */\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n throw new Error('Value exceeds the maximum length of 100 characters.');\n }\n const match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return NaN;\n }\n const n = parseFloat(match[1]);\n const type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n // This should never occur.\n throw new Error(`The unit ${type} was matched, but no matching case exists.`);\n }\n}\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ms);\n/**\n * Short format for `ms`.\n */\nfunction fmtShort(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return `${Math.round(ms / d)}d`;\n }\n if (msAbs >= h) {\n return `${Math.round(ms / h)}h`;\n }\n if (msAbs >= m) {\n return `${Math.round(ms / m)}m`;\n }\n if (msAbs >= s) {\n return `${Math.round(ms / s)}s`;\n }\n return `${ms}ms`;\n}\n/**\n * Long format for `ms`.\n */\nfunction fmtLong(ms) {\n const msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return `${ms} ms`;\n}\n/**\n * Pluralization helper.\n */\nfunction plural(ms, msAbs, n, name) {\n const isPlural = msAbs >= n * 1.5;\n return `${Math.round(ms / n)} ${name}${isPlural ? 's' : ''}`;\n}\n/**\n * A type guard for errors.\n */\nfunction isError(error) {\n return typeof error === 'object' && error !== null && 'message' in error;\n}\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/weald/node_modules/ms/dist/index.mjs?"); + +/***/ }), + /***/ "./node_modules/wherearewe/src/index.js": /*!**********************************************!*\ !*** ./node_modules/wherearewe/src/index.js ***! @@ -16003,6 +20765,83 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ isBrowser: () => (/* binding */ isBrowser),\n/* harmony export */ isElectron: () => (/* binding */ isElectron),\n/* harmony export */ isElectronMain: () => (/* binding */ isElectronMain),\n/* harmony export */ isElectronRenderer: () => (/* binding */ isElectronRenderer),\n/* harmony export */ isEnvWithDom: () => (/* binding */ isEnvWithDom),\n/* harmony export */ isNode: () => (/* binding */ isNode),\n/* harmony export */ isReactNative: () => (/* binding */ isReactNative),\n/* harmony export */ isTest: () => (/* binding */ isTest),\n/* harmony export */ isWebWorker: () => (/* binding */ isWebWorker)\n/* harmony export */ });\n/* harmony import */ var is_electron__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! is-electron */ \"./node_modules/is-electron/index.js\");\n\n\nconst isEnvWithDom = typeof window === 'object' && typeof document === 'object' && document.nodeType === 9\nconst isElectron = is_electron__WEBPACK_IMPORTED_MODULE_0__()\n\n/**\n * Detects browser main thread **NOT** web worker or service worker\n */\nconst isBrowser = isEnvWithDom && !isElectron\nconst isElectronMain = isElectron && !isEnvWithDom\nconst isElectronRenderer = isElectron && isEnvWithDom\nconst isNode = typeof globalThis.process !== 'undefined' && typeof globalThis.process.release !== 'undefined' && globalThis.process.release.name === 'node' && !isElectron\n// @ts-ignore\n// eslint-disable-next-line no-undef\nconst isWebWorker = typeof importScripts === 'function' && typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope\n\n// defeat bundlers replacing process.env.NODE_ENV with \"development\" or whatever\nconst isTest = typeof globalThis.process !== 'undefined' && typeof globalThis.process.env !== 'undefined' && globalThis.process.env['NODE' + (() => '_')() + 'ENV'] === 'test'\nconst isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n\n\n//# sourceURL=webpack://rln-chat/./node_modules/wherearewe/src/index.js?"); +/***/ }), + +/***/ "./node_modules/browserify-aes/modes/list.json": +/*!*****************************************************!*\ + !*** ./node_modules/browserify-aes/modes/list.json ***! + \*****************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"aes-128-ecb\":{\"cipher\":\"AES\",\"key\":128,\"iv\":0,\"mode\":\"ECB\",\"type\":\"block\"},\"aes-192-ecb\":{\"cipher\":\"AES\",\"key\":192,\"iv\":0,\"mode\":\"ECB\",\"type\":\"block\"},\"aes-256-ecb\":{\"cipher\":\"AES\",\"key\":256,\"iv\":0,\"mode\":\"ECB\",\"type\":\"block\"},\"aes-128-cbc\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes-192-cbc\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes-256-cbc\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes128\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes192\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes256\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CBC\",\"type\":\"block\"},\"aes-128-cfb\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CFB\",\"type\":\"stream\"},\"aes-192-cfb\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CFB\",\"type\":\"stream\"},\"aes-256-cfb\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CFB\",\"type\":\"stream\"},\"aes-128-cfb8\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CFB8\",\"type\":\"stream\"},\"aes-192-cfb8\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CFB8\",\"type\":\"stream\"},\"aes-256-cfb8\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CFB8\",\"type\":\"stream\"},\"aes-128-cfb1\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CFB1\",\"type\":\"stream\"},\"aes-192-cfb1\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CFB1\",\"type\":\"stream\"},\"aes-256-cfb1\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CFB1\",\"type\":\"stream\"},\"aes-128-ofb\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"OFB\",\"type\":\"stream\"},\"aes-192-ofb\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"OFB\",\"type\":\"stream\"},\"aes-256-ofb\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"OFB\",\"type\":\"stream\"},\"aes-128-ctr\":{\"cipher\":\"AES\",\"key\":128,\"iv\":16,\"mode\":\"CTR\",\"type\":\"stream\"},\"aes-192-ctr\":{\"cipher\":\"AES\",\"key\":192,\"iv\":16,\"mode\":\"CTR\",\"type\":\"stream\"},\"aes-256-ctr\":{\"cipher\":\"AES\",\"key\":256,\"iv\":16,\"mode\":\"CTR\",\"type\":\"stream\"},\"aes-128-gcm\":{\"cipher\":\"AES\",\"key\":128,\"iv\":12,\"mode\":\"GCM\",\"type\":\"auth\"},\"aes-192-gcm\":{\"cipher\":\"AES\",\"key\":192,\"iv\":12,\"mode\":\"GCM\",\"type\":\"auth\"},\"aes-256-gcm\":{\"cipher\":\"AES\",\"key\":256,\"iv\":12,\"mode\":\"GCM\",\"type\":\"auth\"}}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-aes/modes/list.json?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/browser/algorithms.json": +/*!**************************************************************!*\ + !*** ./node_modules/browserify-sign/browser/algorithms.json ***! + \**************************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"sha224WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha224\",\"id\":\"302d300d06096086480165030402040500041c\"},\"RSA-SHA224\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha224\",\"id\":\"302d300d06096086480165030402040500041c\"},\"sha256WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha256\",\"id\":\"3031300d060960864801650304020105000420\"},\"RSA-SHA256\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha256\",\"id\":\"3031300d060960864801650304020105000420\"},\"sha384WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha384\",\"id\":\"3041300d060960864801650304020205000430\"},\"RSA-SHA384\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha384\",\"id\":\"3041300d060960864801650304020205000430\"},\"sha512WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"sha512\",\"id\":\"3051300d060960864801650304020305000440\"},\"RSA-SHA512\":{\"sign\":\"ecdsa/rsa\",\"hash\":\"sha512\",\"id\":\"3051300d060960864801650304020305000440\"},\"RSA-SHA1\":{\"sign\":\"rsa\",\"hash\":\"sha1\",\"id\":\"3021300906052b0e03021a05000414\"},\"ecdsa-with-SHA1\":{\"sign\":\"ecdsa\",\"hash\":\"sha1\",\"id\":\"\"},\"sha256\":{\"sign\":\"ecdsa\",\"hash\":\"sha256\",\"id\":\"\"},\"sha224\":{\"sign\":\"ecdsa\",\"hash\":\"sha224\",\"id\":\"\"},\"sha384\":{\"sign\":\"ecdsa\",\"hash\":\"sha384\",\"id\":\"\"},\"sha512\":{\"sign\":\"ecdsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-SHA\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA-SHA1\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA\":{\"sign\":\"dsa\",\"hash\":\"sha1\",\"id\":\"\"},\"DSA-WITH-SHA224\":{\"sign\":\"dsa\",\"hash\":\"sha224\",\"id\":\"\"},\"DSA-SHA224\":{\"sign\":\"dsa\",\"hash\":\"sha224\",\"id\":\"\"},\"DSA-WITH-SHA256\":{\"sign\":\"dsa\",\"hash\":\"sha256\",\"id\":\"\"},\"DSA-SHA256\":{\"sign\":\"dsa\",\"hash\":\"sha256\",\"id\":\"\"},\"DSA-WITH-SHA384\":{\"sign\":\"dsa\",\"hash\":\"sha384\",\"id\":\"\"},\"DSA-SHA384\":{\"sign\":\"dsa\",\"hash\":\"sha384\",\"id\":\"\"},\"DSA-WITH-SHA512\":{\"sign\":\"dsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-SHA512\":{\"sign\":\"dsa\",\"hash\":\"sha512\",\"id\":\"\"},\"DSA-RIPEMD160\":{\"sign\":\"dsa\",\"hash\":\"rmd160\",\"id\":\"\"},\"ripemd160WithRSA\":{\"sign\":\"rsa\",\"hash\":\"rmd160\",\"id\":\"3021300906052b2403020105000414\"},\"RSA-RIPEMD160\":{\"sign\":\"rsa\",\"hash\":\"rmd160\",\"id\":\"3021300906052b2403020105000414\"},\"md5WithRSAEncryption\":{\"sign\":\"rsa\",\"hash\":\"md5\",\"id\":\"3020300c06082a864886f70d020505000410\"},\"RSA-MD5\":{\"sign\":\"rsa\",\"hash\":\"md5\",\"id\":\"3020300c06082a864886f70d020505000410\"}}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/browser/algorithms.json?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/browser/curves.json": +/*!**********************************************************!*\ + !*** ./node_modules/browserify-sign/browser/curves.json ***! + \**********************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"1.3.132.0.10\":\"secp256k1\",\"1.3.132.0.33\":\"p224\",\"1.2.840.10045.3.1.1\":\"p192\",\"1.2.840.10045.3.1.7\":\"p256\",\"1.3.132.0.34\":\"p384\",\"1.3.132.0.35\":\"p521\"}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/browser/curves.json?"); + +/***/ }), + +/***/ "./node_modules/browserify-sign/node_modules/elliptic/package.json": +/*!*************************************************************************!*\ + !*** ./node_modules/browserify-sign/node_modules/elliptic/package.json ***! + \*************************************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"name\":\"elliptic\",\"version\":\"6.6.1\",\"description\":\"EC cryptography\",\"main\":\"lib/elliptic.js\",\"files\":[\"lib\"],\"scripts\":{\"lint\":\"eslint lib test\",\"lint:fix\":\"npm run lint -- --fix\",\"unit\":\"istanbul test _mocha --reporter=spec test/index.js\",\"test\":\"npm run lint && npm run unit\",\"version\":\"grunt dist && git add dist/\"},\"repository\":{\"type\":\"git\",\"url\":\"git@github.com:indutny/elliptic\"},\"keywords\":[\"EC\",\"Elliptic\",\"curve\",\"Cryptography\"],\"author\":\"Fedor Indutny \",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/indutny/elliptic/issues\"},\"homepage\":\"https://github.com/indutny/elliptic\",\"devDependencies\":{\"brfs\":\"^2.0.2\",\"coveralls\":\"^3.1.0\",\"eslint\":\"^7.6.0\",\"grunt\":\"^1.2.1\",\"grunt-browserify\":\"^5.3.0\",\"grunt-cli\":\"^1.3.2\",\"grunt-contrib-connect\":\"^3.0.0\",\"grunt-contrib-copy\":\"^1.0.0\",\"grunt-contrib-uglify\":\"^5.0.0\",\"grunt-mocha-istanbul\":\"^5.0.2\",\"grunt-saucelabs\":\"^9.0.1\",\"istanbul\":\"^0.4.5\",\"mocha\":\"^8.0.1\"},\"dependencies\":{\"bn.js\":\"^4.11.9\",\"brorand\":\"^1.1.0\",\"hash.js\":\"^1.0.0\",\"hmac-drbg\":\"^1.0.1\",\"inherits\":\"^2.0.4\",\"minimalistic-assert\":\"^1.0.1\",\"minimalistic-crypto-utils\":\"^1.0.1\"}}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/browserify-sign/node_modules/elliptic/package.json?"); + +/***/ }), + +/***/ "./node_modules/diffie-hellman/lib/primes.json": +/*!*****************************************************!*\ + !*** ./node_modules/diffie-hellman/lib/primes.json ***! + \*****************************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"modp1\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff\"},\"modp2\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff\"},\"modp5\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"},\"modp14\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff\"},\"modp15\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff\"},\"modp16\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff\"},\"modp17\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff\"},\"modp18\":{\"gen\":\"02\",\"prime\":\"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff\"}}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/diffie-hellman/lib/primes.json?"); + +/***/ }), + +/***/ "./node_modules/elliptic/package.json": +/*!********************************************!*\ + !*** ./node_modules/elliptic/package.json ***! + \********************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"name\":\"elliptic\",\"version\":\"6.5.4\",\"description\":\"EC cryptography\",\"main\":\"lib/elliptic.js\",\"files\":[\"lib\"],\"scripts\":{\"lint\":\"eslint lib test\",\"lint:fix\":\"npm run lint -- --fix\",\"unit\":\"istanbul test _mocha --reporter=spec test/index.js\",\"test\":\"npm run lint && npm run unit\",\"version\":\"grunt dist && git add dist/\"},\"repository\":{\"type\":\"git\",\"url\":\"git@github.com:indutny/elliptic\"},\"keywords\":[\"EC\",\"Elliptic\",\"curve\",\"Cryptography\"],\"author\":\"Fedor Indutny \",\"license\":\"MIT\",\"bugs\":{\"url\":\"https://github.com/indutny/elliptic/issues\"},\"homepage\":\"https://github.com/indutny/elliptic\",\"devDependencies\":{\"brfs\":\"^2.0.2\",\"coveralls\":\"^3.1.0\",\"eslint\":\"^7.6.0\",\"grunt\":\"^1.2.1\",\"grunt-browserify\":\"^5.3.0\",\"grunt-cli\":\"^1.3.2\",\"grunt-contrib-connect\":\"^3.0.0\",\"grunt-contrib-copy\":\"^1.0.0\",\"grunt-contrib-uglify\":\"^5.0.0\",\"grunt-mocha-istanbul\":\"^5.0.2\",\"grunt-saucelabs\":\"^9.0.1\",\"istanbul\":\"^0.4.5\",\"mocha\":\"^8.0.1\"},\"dependencies\":{\"bn.js\":\"^4.11.9\",\"brorand\":\"^1.1.0\",\"hash.js\":\"^1.0.0\",\"hmac-drbg\":\"^1.0.1\",\"inherits\":\"^2.0.4\",\"minimalistic-assert\":\"^1.0.1\",\"minimalistic-crypto-utils\":\"^1.0.1\"}}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/elliptic/package.json?"); + +/***/ }), + +/***/ "./node_modules/parse-asn1/aesid.json": +/*!********************************************!*\ + !*** ./node_modules/parse-asn1/aesid.json ***! + \********************************************/ +/***/ ((module) => { + +"use strict"; +eval("module.exports = /*#__PURE__*/JSON.parse('{\"2.16.840.1.101.3.4.1.1\":\"aes-128-ecb\",\"2.16.840.1.101.3.4.1.2\":\"aes-128-cbc\",\"2.16.840.1.101.3.4.1.3\":\"aes-128-ofb\",\"2.16.840.1.101.3.4.1.4\":\"aes-128-cfb\",\"2.16.840.1.101.3.4.1.21\":\"aes-192-ecb\",\"2.16.840.1.101.3.4.1.22\":\"aes-192-cbc\",\"2.16.840.1.101.3.4.1.23\":\"aes-192-ofb\",\"2.16.840.1.101.3.4.1.24\":\"aes-192-cfb\",\"2.16.840.1.101.3.4.1.41\":\"aes-256-ecb\",\"2.16.840.1.101.3.4.1.42\":\"aes-256-cbc\",\"2.16.840.1.101.3.4.1.43\":\"aes-256-ofb\",\"2.16.840.1.101.3.4.1.44\":\"aes-256-cfb\"}');\n\n//# sourceURL=webpack://rln-chat/./node_modules/parse-asn1/aesid.json?"); + /***/ }) /******/ }); @@ -16155,7 +20994,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /******/ if (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + ""; /******/ var document = __webpack_require__.g.document; /******/ if (!scriptUrl && document) { -/******/ if (document.currentScript) +/******/ if (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') /******/ scriptUrl = document.currentScript.src; /******/ if (!scriptUrl) { /******/ var scripts = document.getElementsByTagName("script"); @@ -16203,7 +21042,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module can't be inlined because the eval devtool is used. -/******/ var __webpack_exports__ = __webpack_require__("./src/index.js"); +/******/ var __webpack_exports__ = __webpack_require__("./src/index.ts"); /******/ /******/ })() ; \ No newline at end of file diff --git a/flush-notes/404.html b/flush-notes/404.html index 13ae208..f8d9cf0 100644 --- a/flush-notes/404.html +++ b/flush-notes/404.html @@ -1 +1 @@ -Share notes

    Loading...

    \ No newline at end of file +Share notes

    Loading...

    \ No newline at end of file diff --git a/flush-notes/_next/static/ETpyOCOevb8glrvTpN0hj/_buildManifest.js b/flush-notes/_next/static/3Q62ubAw2P7WMT3tUBoT2/_buildManifest.js similarity index 100% rename from flush-notes/_next/static/ETpyOCOevb8glrvTpN0hj/_buildManifest.js rename to flush-notes/_next/static/3Q62ubAw2P7WMT3tUBoT2/_buildManifest.js diff --git a/flush-notes/_next/static/ETpyOCOevb8glrvTpN0hj/_ssgManifest.js b/flush-notes/_next/static/3Q62ubAw2P7WMT3tUBoT2/_ssgManifest.js similarity index 100% rename from flush-notes/_next/static/ETpyOCOevb8glrvTpN0hj/_ssgManifest.js rename to flush-notes/_next/static/3Q62ubAw2P7WMT3tUBoT2/_ssgManifest.js diff --git a/flush-notes/index.html b/flush-notes/index.html index 2c1ea1d..abe8fc3 100644 --- a/flush-notes/index.html +++ b/flush-notes/index.html @@ -1 +1 @@ -Share notes

    Loading...

    \ No newline at end of file +Share notes

    Loading...

    \ No newline at end of file diff --git a/flush-notes/index.txt b/flush-notes/index.txt index 2cc171b..190d419 100644 --- a/flush-notes/index.txt +++ b/flush-notes/index.txt @@ -1,6 +1,6 @@ 1:HL["/_next/static/media/a34f9d1faa5f3315-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/93e318bfbcd18d37.css","style",{"crossOrigin":""}] -0:["ETpyOCOevb8glrvTpN0hj",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +0:["3Q62ubAw2P7WMT3tUBoT2",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] 5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6076b03a814c7003.js"],""] 6:I[6954,[],""] 7:I[7264,[],""] diff --git a/flush-notes/view.html b/flush-notes/view.html index 98a9575..37d76b0 100644 --- a/flush-notes/view.html +++ b/flush-notes/view.html @@ -1 +1 @@ -Share notes

    Loading...

    \ No newline at end of file +Share notes

    Loading...

    \ No newline at end of file diff --git a/flush-notes/view.txt b/flush-notes/view.txt index 380f976..3554edf 100644 --- a/flush-notes/view.txt +++ b/flush-notes/view.txt @@ -1,6 +1,6 @@ 1:HL["/_next/static/media/a34f9d1faa5f3315-s.p.woff2","font",{"crossOrigin":"","type":"font/woff2"}] 2:HL["/_next/static/css/93e318bfbcd18d37.css","style",{"crossOrigin":""}] -0:["ETpyOCOevb8glrvTpN0hj",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +0:["3Q62ubAw2P7WMT3tUBoT2",[[["",{"children":["view",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L3",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/93e318bfbcd18d37.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] 5:I[5685,["948","static/chunks/948-50bbf5866eb892b4.js","185","static/chunks/app/layout-6076b03a814c7003.js"],""] 6:I[6954,[],""] 7:I[7264,[],""]